"""Native station selection shared by the directory, details and existing map worker.""" import importlib.util import math import datetime import re from pathlib import Path import time import sqlite3 import textwrap from console_icons import aprs_display, profile_from_environment from app_widgets import AdaptivePanels,PanelSpec,Canvas,SelectList,Columns,Column,TextInput from offline_map import Image,Plane,ContextPlane,ReprojectedPlane,raster_size from map_terrain import Renderer from paint import ink def map_spacing(value): number,unit=(value/1000,'km') if value>=1000 else (value,'m') text=format(number,'.2f' if unit=='km' or number<1 else '.1f').rstrip('0').rstrip('.') return text+' '+unit class Context: def __init__(self): self.detail=None;self.target=None;self.revision=0 self.map_catalog=None;self.map_revision=None;self.map_error=None;self.refresh_catalog=None;self.close_catalog=None;self.select_station=None def select(self,detail,target): if detail!=self.detail or target!=self.target: self.detail=detail;self.target=target;self.revision+=1 def catalog(self,snapshot,error=None): self.map_catalog=snapshot;self.map_error=error self.map_revision=snapshot['revision'] if snapshot is not None else ('unavailable',error) class Directory: def __init__(self,db,sources,context,*,self_calls=None): self.db=Path(db).expanduser();self.context=context;self.rows=();self.signature=None;self.error=None;self.next_check=0 spec=importlib.util.spec_from_file_location('pocket_directory_projection',Path(sources)/'n810-directory-projection.py') self.model=importlib.util.module_from_spec(spec);spec.loader.exec_module(self.model) self.map_cache=self.model.StationMapCache(self.db,self_calls=self_calls) self.self_calls=self.map_cache.self_calls;self.counts={} context.refresh_catalog=self.update;context.close_catalog=self.close;context.select_station=self.select def close(self):self.map_cache.close() def set_self_calls(self,values): self.map_cache.set_self_calls(values);self.self_calls=self.map_cache.self_calls self.signature=None;self.next_check=0;self.update(True) def update(self,force=False): now=time.monotonic() if not force and now=width-12: if self.choose():self.open_map() return True if button==0 and row==2 and self.layout.tabbed: self.layout.select('list' if column<10 else 'details');return True for key,(x,y,w,h) in rects.items(): if not(x<=columny: if self.list.pointer_at(column-x,row-y-1,w,max(1,h-1)):self.choose();self.scroll=0 return True return False def selected_entities(self): from entity_actions import EntityRef call=(self.context.target or {}).get('call') return (EntityRef('station',call),) if call else () def entities_at(self,column,row): from entity_actions import EntityRef self.sync();call=None for key,(x,y,w,h) in self.pane_rects().items(): if not(x<=columny: index=self.list.offset+row-y-1 if self.list.has_scrollbar(w) and column==x+w-1:return () if 0<=index=width-10:self.filter_open=False;return True if row==1:self.filter_focus=1;return True if 3<=row2000 else None return True def update_tracks(self,packets): seen=set();changed=False for packet in packets[-200:]: if packet.get('direction')!='radio_to_host':continue raw=packet.get('raw');stamp=packet.get('time') if not isinstance(raw,str) or not isinstance(stamp,str):continue token=(stamp,raw);seen.add(token) if token in self._track_seen:continue match=re.fullmatch(r'(\S+)>(\S+) ctl=[0-9a-f]+ pid=f0 (.*)',raw) if not match:continue call,route,payload=match.groups() position=self._decode_position(payload,route.split(',')[0]).get('position') if not position:continue try: parsed=datetime.datetime.fromisoformat(stamp) observed=parsed.timestamp() if parsed.tzinfo is not None else None except ValueError:observed=None if self.tracks.add(call,*position,stamp=stamp,observed_at=observed):changed=True self._track_seen=seen if changed:self._track_revision+=1 return changed def toggle_follow(self): call=(self.context.target or {}).get('call') if not call:return if self.tracks.call==call: if self.tracks.paused:self.tracks.resume() else:self.tracks.stop() else:self.tracks.follow(call) def focus_selection(self): self.tracks.pause() position=(self.context.target or {}).get('position') if position:self.center=tuple(position);self.span=min(self.span,80.) @staticmethod def distance_label(span): return f'{span*1000:.0f} m' if span<1 else f'{span:.4g} km' def scale_label(self): displayed=self._image_view[1] if self._image is not None and self._image_view else self.span label=self.distance_label(displayed)+' wide' if displayed!=self.span:label+=' · '+self.distance_label(self.span)+' requested' return label def map_controls(self): x=0;items=[] for label,key in (('[ - ]','-'),('[ + ]','+'),('[ Key l ]','l'),('[←]','left'),('[↑]','up'),('[↓]','down'),('[→]','right')): if x+len(label)>self.width:break items.append((x,len(label),label,key));x+=len(label)+1 return tuple(items) def zoom_step(self,inward): anchor,step,previous=getattr(self,'_zoom_steps',(self.span,0,self.span)) if previous!=self.span:anchor,step=self.span,0 step+=1 if inward else -1 span=max(getattr(self,'minimum_span',.25),min(2000.,anchor*.8**step)) self._zoom_steps=(anchor,step,span) if .251:self.map_notice=f'{len(calls)} overlapping stations · click again to cycle' return True if button&32: if self._pan_drag is None:return False self._pan_to(column,row);return True if button&64: if not (0<=column=width-12:self.open_directory();return True if button==0 and row==0 and width-24<=column>shift)&255 for shift in (16,8,0)) overlay[y*image.width+x]=(glyph,ink(*color,background=bg)) hits.append((x,y,1,station['call'])) if display and display['overlay'] and x+1>shift)&255)*.55) for shift in (16,8,0)) overlay[index]=(char,ink(*color,background=bg)) labels+=1;occupied.update(places);hits.append((x+2,y,len(label),station['call'])) for point in points[:-1]: x,y=map(round,view.project(point['lon'],point['lat'])) if 0<=x>s)&255 for s in (16,8,0)) overlay[y*image.width+x]=(':',ink(170,208,196,background=bg)) if position: x,y=map(round,view.project(position[1],position[0])) if 0<=x>s)&255 for s in (16,8,0)) overlay[y*image.width+x+n]=(char,ink(255,232,150,background=bg)) if self.legend: definitions=[] for station in rows: symbol=station['symbol'] if symbol: display=self.display_symbol(symbol['table'],symbol['code']);entry=display['glyph']+(display['overlay'] or '')+' '+symbol['table']+symbol['code']+' '+display['name'] if entry not in definitions:definitions.append(entry) legend=('Water blue · land green/brown · peaks grey/white · Gold: selected · l hide', ' · '.join(definitions[:4]) or '● No advertised symbol · unknown is not absence') for row,text in enumerate(legend): y=max(0,image.height-len(legend))+row for x,char in enumerate(text[:image.width]):overlay[y*image.width+x]=(char,ink(230,232,240,background=(18,22,30))) hits=[hit for hit in hits if hit[1]