summaryrefslogtreecommitdiffhomepage
path: root/desktop/packages/mullvad-vpn/src/renderer/components/Map.tsx
blob: a8e41e80789cb9c4b0adc51f0fb440f9b96e37a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { useCallback, useEffect, useMemo, useRef } from 'react';
import styled from 'styled-components';

import { TunnelState } from '../../shared/daemon-rpc-types';
import log from '../../shared/logging';
import { useAppContext } from '../context';
import GlMap, { ConnectionState, Coordinate } from '../lib/3dmap';
import { getReduceMotion } from '../lib/functions';
import {
  useCombinedRefs,
  useEffectEvent,
  useRefCallback,
  useRerenderer,
} from '../lib/utility-hooks';
import { useSelector } from '../redux/store';

// Default to Gothenburg when we don't know the actual location.
const defaultLocation: Coordinate = { latitude: 57.70887, longitude: 11.97456 };

const StyledCanvas = styled.canvas({
  position: 'absolute',
  width: '100%',
  height: '100%',
});

interface MapParams {
  location: Coordinate;
  connectionState: ConnectionState;
}

export default function Map() {
  const connection = useSelector((state) => state.connection);
  const animateMap = useSelector((state) => state.settings.guiSettings.animateMap);

  const hasLocationValue = hasLocation(connection);
  const location = useMemo<Coordinate | undefined>(() => {
    return hasLocationValue
      ? {
          latitude: connection.latitude,
          longitude: connection.longitude,
        }
      : defaultLocation;
  }, [hasLocationValue, connection.longitude, connection.latitude]);

  if (window.env.e2e) {
    return null;
  }

  const connectionState = getConnectionState(hasLocationValue, connection.status.state);

  const reduceMotion = getReduceMotion();
  const animate = !reduceMotion && animateMap;

  return (
    <MapInner
      location={location ?? defaultLocation}
      connectionState={connectionState}
      animate={animate}
    />
  );
}

function hasLocation(location: Partial<Coordinate>): location is Coordinate {
  return typeof location.latitude === 'number' && typeof location.longitude === 'number';
}

function getConnectionState(hasLocation: boolean, connectionState: TunnelState['state']) {
  if (!hasLocation) {
    return ConnectionState.noMarker;
  }

  switch (connectionState) {
    case 'connected':
      return ConnectionState.connected;
    case 'disconnected':
      return ConnectionState.disconnected;
    default:
      return ConnectionState.noMarker;
  }
}

interface MapInnerProps extends MapParams {
  animate: boolean;
}

function MapInner(props: MapInnerProps) {
  const { getMapData } = useAppContext();

  // When location or connection state changes it's stored here until passed to 3dmap
  const newParams = useRef<MapParams>(undefined);

  // This is set to true when rendering should be paused
  const pause = useRef<boolean>(false);

  const mapRef = useRef<GlMap>(undefined);
  const canvasRef = useRef<HTMLCanvasElement>(undefined);

  const width = applyPixelRatio(canvasRef.current?.clientWidth ?? window.innerWidth);

  // This constant is used for the height the first frame that is rendered only.
  const height = applyPixelRatio(canvasRef.current?.clientHeight ?? 493);

  // Hack to rerender when window size changes or when ref is set.
  const [onSizeChangeImpl, sizeChangeCounter] = useRerenderer();
  const onSizeChange = useEffectEvent(onSizeChangeImpl);

  const animationFrameCallback = useEffectEvent((now: number) => {
    now *= 0.001; // convert to seconds

    // Propagate location change to the map
    if (newParams.current) {
      mapRef.current?.setLocation(
        newParams.current.location,
        newParams.current.connectionState,
        now,
        props.animate,
      );
      newParams.current = undefined;
    }

    mapRef.current?.draw(now);

    // Stops rendering if pause is true. This happens when there is no ongoing movements
    if (!pause.current) {
      render();
    }
  });

  // These lint rules are disabled for now because the react plugin for eslint does
  // not understand that useEffectEvent should not be added to the dependency array.
  // Enable these rules again when eslint can lint useEffectEvent properly.
  // eslint-disable-next-line react-compiler/react-compiler
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const render = useCallback(() => requestAnimationFrame(animationFrameCallback), []);

  // This is called when the canvas has been rendered the first time and initializes the gl context
  // and the map.
  const canvasCallback = useRefCallback(async (canvas: HTMLCanvasElement | null) => {
    if (!canvas) {
      return;
    }

    onSizeChange();

    const gl = canvas.getContext('webgl2', { antialias: true })!;

    mapRef.current = new GlMap(
      gl,
      await getMapData(),
      props.location,
      props.connectionState,
      () => (pause.current = true),
    );

    render();
  });

  // Set new params when the location or connection state has changed, and unpause if paused
  useEffect(() => {
    newParams.current = {
      location: props.location,
      connectionState: props.connectionState,
    };

    if (pause.current) {
      pause.current = false;
      render();
    }
  }, [props.location, props.connectionState, render]);

  useEffect(() => {
    mapRef.current?.updateViewport();
    render();
  }, [width, height, sizeChangeCounter, render]);

  // Resize canvas if window size changes
  useEffect(() => {
    addEventListener('resize', onSizeChange);
    return () => removeEventListener('resize', onSizeChange);
    // These lint rules are disabled for now because the react plugin for eslint does
    // not understand that useEffectEvent should not be added to the dependency array.
    // Enable these rules again when eslint can lint useEffectEvent properly.
    // eslint-disable-next-line react-compiler/react-compiler
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    const unsubscribe = window.ipc.window.listenScaleFactorChange(onSizeChange);
    return () => unsubscribe();
    // These lint rules are disabled for now because the react plugin for eslint does
    // not understand that useEffectEvent should not be added to the dependency array.
    // Enable these rules again when eslint can lint useEffectEvent properly.
    // eslint-disable-next-line react-compiler/react-compiler
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const devicePixelRatio = window.devicePixelRatio;

  // Log new scale factor if it changes
  useEffect(() => {
    log.verbose(`Map canvas scale factor: ${devicePixelRatio}, using: ${getPixelRatio()}`);
  }, [devicePixelRatio]);

  const combinedCanvasRef = useCombinedRefs(canvasRef, canvasCallback);

  return <StyledCanvas ref={combinedCanvasRef} width={width} height={height} />;
}

function getPixelRatio(): number {
  let pixelRatio = window.devicePixelRatio;

  // Wayland renders non-integer values as the next integer and then scales it back down.
  if (window.env.platform === 'linux') {
    pixelRatio = Math.ceil(pixelRatio);
  }

  return pixelRatio;
}

function applyPixelRatio(dimension: number): number {
  return Math.floor(dimension * getPixelRatio());
}