Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,12 @@ export function registerIpc({ settings, secrets, bookmarks, disable3dTiles, isTr
handle(IPC.profilesUpdate, (id: unknown, patch: unknown) => bookmarks.updateProfile(str(id, 100), patch))
handle(IPC.profilesRemove, (id: unknown) => bookmarks.removeProfile(str(id, 100)))

// Turned off in Settings: answer without a request so nothing counts toward the quota.
const placesOff = () => !settings.get().placesApi
const PLACES_OFF = { ok: false, error: { status: 'error', message: 'Places API is turned off in Settings.' } } as const

handle(IPC.placesAutocomplete, (req: unknown) => {
if (placesOff()) return PLACES_OFF
const r = (req ?? {}) as Partial<AutocompleteRequest>
const bias =
r.bias && Number.isFinite(r.bias.latitude) && Number.isFinite(r.bias.longitude)
Expand All @@ -110,9 +115,10 @@ export function registerIpc({ settings, secrets, bookmarks, disable3dTiles, isTr
})
})
handle(IPC.placesDetails, (placeId: unknown, token: unknown) =>
placeDetails(secrets.get().googleApiKey, str(placeId, 300), str(token, 100))
placesOff() ? PLACES_OFF : placeDetails(secrets.get().googleApiKey, str(placeId, 300), str(token, 100))
)
handle(IPC.placesNearby, (req: unknown) => {
if (placesOff()) return PLACES_OFF
const r = (req ?? {}) as Partial<NearbyRequest>
const { latitude, longitude } = r.center ?? {}
if (
Expand All @@ -130,6 +136,7 @@ export function registerIpc({ settings, secrets, bookmarks, disable3dTiles, isTr
})
})
handle(IPC.placesCities, (req: unknown) => {
if (placesOff()) return PLACES_OFF
const r = (req ?? {}) as Partial<CitiesRequest>
const { south, west, north, east } = r
if (
Expand Down
3 changes: 2 additions & 1 deletion src/renderer/src/components/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ function PaletteDialog() {
const set = useAppStore((s) => s.set)
const bookmarks = useAppStore((s) => s.bookmarks)
const profiles = useAppStore((s) => s.profiles)
const hasGoogleKey = useAppStore((s) => !!s.keys.googleApiKey)
// Place search needs a Google key and the Places API setting on.
const hasGoogleKey = useAppStore((s) => !!s.keys.googleApiKey && s.settings.placesApi)
const target = useAppStore((s) => s.target)
const [query, setQuery] = useState('')
const [selected, setSelected] = useState(0)
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/src/components/HorizonPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ function HorizonPanelBody() {
onPick={(utc) => engine?.sun.setInstant(utc)}
/>
)}
{state.peakStatus === 'unavailable' && prefs.peakNames && <span className="faint">Peak names need a Google Maps Platform key with Places API (New).</span>}
{state.peakStatus === 'unavailable' && prefs.peakNames && <span className="faint">Peak names need a Google Maps Platform key with Places API (New), turned on in Settings.</span>}
{hover && (
<span className="horizon-hover">
<span className="mono">
Expand Down
5 changes: 3 additions & 2 deletions src/renderer/src/components/RightRail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export function RightRail() {
const camera = useAppStore((s) => s.camera)
const pinElsewhere = !!pin && (!camera || haversine(pin, camera) > 5)
const placeLabels = useAppStore((s) => s.settings.placeLabels)
const placesApi = useAppStore((s) => s.settings.placesApi)
const lightPollution = useAppStore((s) => s.settings.lightPollution.enabled)
const viewfinder = useAppStore((s) => s.viewfinder)
const patchSettings = useAppStore((s) => s.patchSettings)
Expand Down Expand Up @@ -230,9 +231,9 @@ export function RightRail() {
/>
<RailButton
icon="labels"
label="Place names"
label={placesApi ? 'Place names' : 'Place names (Places API is off in Settings)'}
keys="M"
active={placeLabels}
active={placeLabels && placesApi}
pressed={placeLabels}
onClick={() => patchSettings((d) => void (d.placeLabels = !d.placeLabels))}
/>
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/components/SettingsDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ function KeysSection() {
const secrets = useAppStore((s) => s.secrets)
const showToast = useAppStore((s) => s.showToast)
const info = useAppInfo()
const placesApi = useAppStore((s) => s.settings.placesApi)
const patch = useAppStore((s) => s.patchSettings)
const { keys, setKeys, result, validating, validate, setResult } = useKeyFields(initial)
return (
<div>
Expand All @@ -44,6 +46,9 @@ function KeysSection() {
</div>
)}
<KeyFields keys={keys} setKeys={setKeys} result={result} referer={info?.googleReferer ?? ''} />
<Field label="Use Places API" hint="Place search, map place names and horizon peak names. Turn off to stop all Places requests, e.g. when the free quota runs out.">
<input type="checkbox" checked={placesApi} onChange={(e) => patch((d) => void (d.placesApi = e.target.checked))} />
</Field>
<div className="row" style={{ justifyContent: 'flex-end' }}>
<button
className="btn danger"
Expand Down
18 changes: 13 additions & 5 deletions src/renderer/src/engine/Engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from 'cesium'
import { estimateTarget, matchesFilter } from '@shared/locations'
import { DEFAULT_VIEW } from '@shared/settings'
import type { ApiCheck, ApiKeys, Bookmark, CameraView, GeoPosition, NewBookmark, PlaceDetails, SavedProfile } from '@shared/types'
import type { ApiCheck, ApiKeys, Bookmark, CameraView, GeoPosition, NewBookmark, PlaceDetails, SavedProfile, Settings } from '@shared/types'
import { formatLatLon, type ParsedLocation } from '@shared/coords'
import { loadGeoid } from '../lib/geoid'
import type { GeoPoint } from '../lib/profile'
Expand Down Expand Up @@ -59,6 +59,9 @@ function subscribeJson<T>(selector: (s: AppState) => T, listener: (value: T) =>
})
}

/** Map labels show when turned on and the Places API setting allows the requests. */
const labelsOn = (s: Settings): boolean => s.placeLabels && s.placesApi

function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T> {
return Promise.race([promise, new Promise<T>((resolve) => setTimeout(() => resolve(fallback), ms))])
}
Expand Down Expand Up @@ -212,7 +215,7 @@ export class Engine {
provider: () => this.terrain.provider,
nearby: (req) => window.photoearth.places.nearby(req),
knownPeaks: () => this.labels.knownPeaks(),
canNamePeaks: () => !!this.keys.googleApiKey
canNamePeaks: () => !!this.keys.googleApiKey && appState().settings.placesApi
})
this.alignment = new AlignmentTool(this.widget, {
sampleGround: (lon, lat) => this.preciseGround(lon, lat),
Expand Down Expand Up @@ -330,7 +333,7 @@ export class Engine {
}
if (changed.google || this.failed.labels) {
dismissBanner('labels')
this.labels.configure(keys.googleApiKey, appState().settings.placeLabels, this.failed.labels)
this.labels.configure(keys.googleApiKey, labelsOn(appState().settings), this.failed.labels)
this.failed.labels = false
}
if (changed.ion || this.failed.terrain) {
Expand Down Expand Up @@ -420,7 +423,7 @@ export class Engine {
)
s.push(
subscribeJson(
(st) => st.settings.placeLabels,
(st) => labelsOn(st.settings),
(on) => this.labels.configure(this.keys.googleApiKey, on)
)
)
Expand All @@ -441,7 +444,12 @@ export class Engine {
)
)
s.push(useAppStore.subscribe((st) => st.profile.hoverIndex, () => this.requestRender()))
s.push(useAppStore.subscribe((st) => st.settings.horizon.peakNames, () => void this.horizon.namePeaks()))
s.push(
subscribeJson(
(st) => [st.settings.horizon.peakNames, st.settings.placesApi],
() => void this.horizon.namePeaks()
)
)
// A token added while the panorama or viewshed shows "needs terrain" retries it.
s.push(
useAppStore.subscribe(
Expand Down
2 changes: 2 additions & 0 deletions src/shared/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export function defaultSettings(): Settings {
lastCamera: null,
imagery: 'roadmap',
placeLabels: true,
placesApi: true,
lightPollution: { enabled: false, opacity: 0.6, source: 'atlas-2025' },
verticalExaggeration: 1,
lighting: 'sun',
Expand Down Expand Up @@ -228,6 +229,7 @@ export function sanitizeSettings(raw: Json): Settings {
lastCamera: sanitizeCameraView(r.lastCamera),
imagery: oneOf(r.imagery, IMAGERY_TYPES, d.imagery),
placeLabels: bool(r.placeLabels, d.placeLabels),
placesApi: bool(r.placesApi, d.placesApi),
lightPollution: {
enabled: bool(lp.enabled, d.lightPollution.enabled),
opacity: num(lp.opacity, d.lightPollution.opacity, 0, 1),
Expand Down
7 changes: 6 additions & 1 deletion src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,13 @@ export interface Settings {
navigation: NavigationSettings
lastCamera: CameraView | null
imagery: ImageryType
/** Google place names on the map (a labels-only Map Tiles layer). */
/** Google place names on the map (Places API Nearby / Text Search). */
placeLabels: boolean
/**
* Whether the app calls Google Places API (New) at all: place search, map labels and
* horizon peak names. Off keeps those requests from counting toward the key's quota.
*/
placesApi: boolean
/** Artificial night sky brightness overlay. */
lightPollution: LightPollutionSettings
verticalExaggeration: number
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/shared.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import { buildAutocompleteBody, parseAutocomplete, parsePlaceDetails } from '@sh
import { DETAIL_SHADOW_RANGE, MIN_CORE_ALTITUDE_RANGE, defaultSettings, sanitizeSettings } from '@shared/settings'

describe('settings sanitization', () => {
it('the Places API is on by default and the switch survives sanitizing', () => {
expect(defaultSettings().placesApi).toBe(true)
expect(sanitizeSettings({ placesApi: false }).placesApi).toBe(false)
expect(sanitizeSettings({ placesApi: 'off' }).placesApi).toBe(true)
})

it('returns defaults for garbage', () => {
expect(sanitizeSettings(undefined)).toEqual(defaultSettings())
expect(sanitizeSettings('nope')).toEqual(defaultSettings())
Expand Down
Loading