feat: add typed data and views with scoped device power

This commit is contained in:
Codex
2026-10-25 14:35:24 +08:00
parent 5b99a7e9fc
commit ca60398dea
65 changed files with 4238 additions and 231 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="11" android:versionName="0.1.55">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="12" android:versionName="0.1.56">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
+1 -1
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="11" android:versionName="0.1.55">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="12" android:versionName="0.1.56">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
@@ -8,7 +8,7 @@ import javax.net.ssl.HttpsURLConnection;
final class DisplayApi {
static JSONObject call(String path,String token,JSONObject body)throws Exception{
HttpsURLConnection c=(HttpsURLConnection)new URL("https://zhao.ucvl.cn"+path).openConnection();
HttpsURLConnection c=(HttpsURLConnection)new URL(ServerEndpoint.api(path)).openConnection();
c.setInstanceFollowRedirects(false);c.setConnectTimeout(10000);c.setReadTimeout(10000);
if(token!=null&&!token.isEmpty())c.setRequestProperty("Authorization","Bearer "+token);
try{
@@ -21,7 +21,7 @@ public class LocationActivity extends Activity {
final int[] sampleUnits={1,60,3600,86400};
final int[] uploadIntervals={10,60,300,3600,7200,10800,14400,18000,86400,172800,259200,0};
TextView historyStatus,historyNotice;Dialog historyDialog;LocationMapView historyMap;Button historyMore;JSONArray historyPoints=new JSONArray();int historyRequest=0;boolean historyAcknowledged=false;
VoicePanel voice;Button settingsButton;PhoneLayout phone;PhoneStyle style;Dialog detailDialog;
VoicePanel voice;Button settingsButton;PhoneLayout phone;PhoneHomePanel phoneHome;PhoneStyle style;Dialog detailDialog;
LinearLayout pairSection,recipientSection,sampleSection,uploadSection,historySection,permissionSection,consentSection;
LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false,bindingRejected=false;
int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError="";
@@ -83,24 +83,26 @@ public class LocationActivity extends Activity {
button("打开手机系统定位设置",permissionSection).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)));
sharing.setOnCheckedChangeListener((v,checked)->{if(rendering)return;if(checked)confirmSharing();else{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);}render();});
map=new LocationMapView(this);phone.mapSlot.addView(map,0,new FrameLayout.LayoutParams(-1,-1));phone.fit.setOnClickListener(v->map.reset());reload.setOnClickListener(v->loadFamily());
voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));phone.pages[1].addView(voice.page(),new LinearLayout.LayoutParams(-1,0,1));phone.voiceSettings.addView(voice.dock.receiverCard);
voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));phone.pages[PhoneLayout.COMMUNICATION].addView(voice.page(),new LinearLayout.LayoutParams(-1,0,1));phone.voiceSettings.addView(voice.dock.receiverCard);
phone.voiceSettings.addView(style.label("仅接收你允许的家人或设备。聊天记录长期保存在家庭网盘,关闭接收不会删除历史。",12,PhoneStyle.MUTED));
Button soundSettings=style.button("麦克风与声音权限",false);phone.voiceSettings.addView(soundSettings);soundSettings.setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,android.net.Uri.parse("package:"+getPackageName()))));
try{phone.pages[2].addView(style.label("赵府智家 · "+getPackageManager().getPackageInfo(getPackageName(),0).versionName,12,PhoneStyle.MUTED));}catch(Exception ignored){}
phone.onTab=i->{voice.finish(false);voice.communication(i==1);if(i==2&&!settingsReady)loadSettings();};
settingsButton.setOnClickListener(v->selectTab(2));phone.check.setOnClickListener(v->{selectTab(2);if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);});
phone.pairNow.setOnClickListener(v->{selectTab(2);showDetail("配对我的手机",pairSection);});
try{phone.pages[PhoneLayout.MINE].addView(style.label("赵府智家 · "+getPackageManager().getPackageInfo(getPackageName(),0).versionName,12,PhoneStyle.MUTED));}catch(Exception ignored){}
phoneHome=new PhoneHomePanel(this,phone,()->prefs.getString("token",""),()->!pairingRequired(),this::selectTab);
phone.onTab=this::tabChanged;
settingsButton.setOnClickListener(v->selectTab(PhoneLayout.MINE));phone.check.setOnClickListener(v->{selectTab(PhoneLayout.MINE);if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);});
phone.pairNow.setOnClickListener(v->{selectTab(PhoneLayout.MINE);showDetail("配对我的手机",pairSection);});
phone.profile.setOnClickListener(v->showDetail("配对与设备",pairSection));phone.pairing.setOnClickListener(v->showDetail("配对与设备",pairSection));
phone.myCheck.setOnClickListener(v->{if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);});phone.permissions.setOnClickListener(v->showDetail("定位权限与系统设置",permissionSection));
phone.viewers.setOnClickListener(v->{if(!settingsReady)loadSettings();showDetail("允许谁查看",recipientSection);});
phone.expiry.setOnClickListener(v->new AlertDialog.Builder(this).setTitle("共享有效期").setMessage(prefs.getLong("expires",0)>0?"本手机配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(prefs.getLong("expires",0)))+"。到期后停止新位置共享;可随时手动关闭。续期或重新配对请联系家庭管理员。":"配对后显示有效期。").setPositiveButton("知道了",null).show());
phone.sampling.setOnClickListener(v->showDetail("共享模式与采集频率",sampleSection));phone.upload.setOnClickListener(v->showDetail("集中上传与离线暂存",uploadSection));phone.history.setOnClickListener(v->showDetail("我的历史轨迹",historySection));
selectTab(paired()?0:2);render();
selectTab(paired()?PhoneLayout.LOCATION:PhoneLayout.MINE);render();
}
boolean paired(){return !prefs.getString("token","").isEmpty();}
boolean pairingRequired(){long expires=prefs.getLong("expires",0);return !paired()||bindingRejected||expires>0&&expires<=System.currentTimeMillis();}
LinearLayout section(){LinearLayout v=style.column();settings.addView(v);return v;}
void selectTab(int tab){voice.finish(false);phone.select(tab);voice.communication(tab==1);if(tab==2&&!settingsReady)loadSettings();}
void selectTab(int tab){phone.select(tab);tabChanged(tab);}
void tabChanged(int tab){voice.finish(false);voice.communication(tab==PhoneLayout.COMMUNICATION);if(phoneHome!=null)phoneHome.contextChanged();if(tab==PhoneLayout.MINE&&!settingsReady)loadSettings();}
void showDetail(String title,LinearLayout content){
if(detailDialog!=null)detailDialog.dismiss();voice.finish(false);if(content.getParent()!=null)((android.view.ViewGroup)content.getParent()).removeView(content);
LinearLayout frame=style.column();frame.setBackgroundColor(PhoneStyle.PAPER);
@@ -118,9 +120,10 @@ public class LocationActivity extends Activity {
new AlertDialog.Builder(this).setTitle("开启我的位置共享").setMessage((realtimeMode()?"实时共享:持续定位与汇报。\n":"定时共享:采集完即释放定位。\n")+"允许 "+total+" 个对象查看 · 采集"+periodLabel(samplePeriodSeconds())+" · 上传"+periodLabel(uploadPeriod())+"。\n可随时关闭。频率与名单将在此次开启时生效。").setView(consentSection).setNegativeButton("暂不开启",null).setPositiveButton("开启共享",(d,w)->start()).setOnDismissListener(d->{if(consentSection.getParent()!=null)((android.view.ViewGroup)consentSection.getParent()).removeView(consentSection);settings.addView(consentSection);render();}).show();
}
String periodLabel(int seconds){return "每 "+(seconds%86400==0?seconds/86400+" 天":seconds%3600==0?seconds/3600+" 小时":seconds%60==0?seconds/60+" 分钟":seconds+" 秒");}
public void onBackPressed(){if(phone.tab!=0){selectTab(0);return;}super.onBackPressed();}
public void onBackPressed(){if(phone.tab!=PhoneLayout.LOCATION){selectTab(PhoneLayout.LOCATION);return;}super.onBackPressed();}
void render(){
if(phoneHome!=null)phoneHome.contextChanged();
permissionStatus.setText(locationPermissionText());
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false),busy=pairing||LocationService.busy;
homeContent.setVisibility(paired?View.VISIBLE:View.GONE);shareControls.setVisibility(paired?View.VISIBLE:View.GONE);voice.setVisibility(paired?View.VISIBLE:View.GONE);phone.pairIntro.setVisibility(paired?View.GONE:View.VISIBLE);
@@ -156,7 +159,7 @@ public class LocationActivity extends Activity {
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response);
LocationSchedule.cancel(this);stopService(new Intent(this,LocationService.class));prefs.edit().putString("memberName",response.getString("memberName")).putString("token",response.getString("token")).putString("home",response.getString("home")).putLong("expires",(long)(response.getDouble("expires")*1000)).putBoolean("active",false).putString("status","已配对;共享关闭,可查看获授权家人").apply();refreshQueueStats();
runOnUiThread(()->{if(isDestroyed())return;pairing=false;bindingRejected=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;if(detailDialog!=null)detailDialog.dismiss();selectTab(0);voice.rebound();loadSettings();loadFamily();});
runOnUiThread(()->{if(isDestroyed())return;pairing=false;bindingRejected=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;if(detailDialog!=null)detailDialog.dismiss();selectTab(PhoneLayout.LOCATION);voice.rebound();loadSettings();loadFamily();});
}catch(Exception e){runOnUiThread(()->{if(!isDestroyed())Toast.makeText(this,"配对未成功,请检查手机配对码或安装新版 App",1).show();});}finally{pairing=false;runOnUiThread(()->{if(!isDestroyed())render();});}},"location-pair").start();
}
void loadFamily(){
@@ -165,7 +168,7 @@ public class LocationActivity extends Activity {
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list"));
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=sortPositions(response.optJSONArray("items"));map.setItems(list);familyList.removeAllViews();viewStatus.setText(list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"按采集时间从新到旧 · 点击在地图上闪烁定位");
for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?("sampling".equals(row.optString("scheduleReason"))?"等待下次采集":"等待下次上传"):("stale".equals(row.optString("status"))?"更新中断 · 已隐藏旧位置":"等待定位")):new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA).format(new Date((long)(pos.optDouble("at")*1000)))+" 采集 · 约 "+Math.round(pos.optDouble("accuracy"))+" 米";phone.family(row.optString("name"),detail,pos!=null,()->{if(pos!=null){phone.scrolls[0].smoothScrollTo(0,0);map.focus(pos);}else Toast.makeText(this,"当前没有可显示的位置",0).show();},()->history(row.optString("id")));}
for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?("sampling".equals(row.optString("scheduleReason"))?"等待下次采集":"等待下次上传"):("stale".equals(row.optString("status"))?"更新中断 · 已隐藏旧位置":"等待定位")):new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA).format(new Date((long)(pos.optDouble("at")*1000)))+" 采集 · 约 "+Math.round(pos.optDouble("accuracy"))+" 米";phone.family(row.optString("name"),detail,pos!=null,()->{if(pos!=null){phone.scrolls[PhoneLayout.LOCATION].smoothScrollTo(0,0);map.focus(pos);}else Toast.makeText(this,"当前没有可显示的位置",0).show();},()->history(row.optString("id")));}
});
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){bindingRejected=true;boolean wasSharing=prefs.getBoolean("active",false);prefs.edit().putBoolean("active",false).apply();if(wasSharing||LocationService.busy)startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settingsReady=false;settingsError="手机配对已失效,请在「我的」重新配对";}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
@@ -251,7 +254,7 @@ public class LocationActivity extends Activity {
}).show();
}
public void onRequestPermissionsResult(int request,String[] permissions,int[] results){super.onRequestPermissionsResult(request,permissions,results);if(request==47||request==48){render();return;}if(request==45){if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0){if(visible)start();else pendingStart=true;}else Toast.makeText(this,"未授权定位,不采集自己的位置;仍可查看获授权家人",1).show();render();}}
public void onResume(){super.onResume();visible=true;map.resumeMap();voice.active(true);lastList=0;refreshQueueStats();if(!LocationService.busy&&(prefs.getBoolean("reportPending",false)||prefs.getBoolean("stopPending",false)))syncNow();if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
public void onPause(){visible=false;if(historyDialog!=null)historyDialog.dismiss();voice.active(false);generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.pauseMap();if(familyList!=null)familyList.removeAllViews();super.onPause();}
public void onDestroy(){if(detailDialog!=null)detailDialog.dismiss();if(map!=null)map.close();if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
public void onResume(){super.onResume();visible=true;map.resumeMap();voice.active(true);phoneHome.active(true);lastList=0;refreshQueueStats();if(!LocationService.busy&&(prefs.getBoolean("reportPending",false)||prefs.getBoolean("stopPending",false)))syncNow();if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
public void onPause(){visible=false;if(phoneHome!=null)phoneHome.active(false);if(historyDialog!=null)historyDialog.dismiss();voice.active(false);generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.pauseMap();if(familyList!=null)familyList.removeAllViews();super.onPause();}
public void onDestroy(){if(phoneHome!=null)phoneHome.close();if(detailDialog!=null)detailDialog.dismiss();if(map!=null)map.close();if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
}
@@ -2,7 +2,6 @@ package cn.ucvl.zhaodisplay;
import android.content.Context;
import android.webkit.*;
import android.net.Uri;
import android.view.MotionEvent;
import org.json.*;
import java.io.ByteArrayInputStream;
@@ -19,14 +18,13 @@ final class LocationMapView extends WebView {
setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){return true;}
public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request){
Uri uri=request.getUrl();String path=uri.getPath();
if(!"https".equals(uri.getScheme())||!"zhao.ucvl.cn".equals(uri.getHost())||(uri.getPort()!=-1&&uri.getPort()!=443)||path==null||!(path.startsWith("/maps/")||path.startsWith("/ui/assets/")))return new WebResourceResponse("text/plain","UTF-8",new ByteArrayInputStream(new byte[0]));
if(!ServerEndpoint.mapResource(request.getUrl().toString()))return new WebResourceResponse("text/plain","UTF-8",new ByteArrayInputStream(new byte[0]));
return null;
}
public void onPageFinished(WebView view,String url){if(!closed&&url.startsWith("https://zhao.ucvl.cn/maps/phone")){ready=true;push();}}
public void onPageFinished(WebView view,String url){if(!closed&&ServerEndpoint.mapPage(url)){ready=true;push();}}
public void onReceivedError(WebView view,WebResourceRequest request,WebResourceError error){if(request.isForMainFrame())ready=false;}
});
loadUrl("https://zhao.ucvl.cn/maps/phone");
loadUrl(ServerEndpoint.MAP_PHONE);
}
void run(String expression){if(ready&&!closed)evaluateJavascript("if(window.ZhaoMap){"+expression+"}",null);}
void push(){run("window.ZhaoMap.setItems(JSON.parse("+JSONObject.quote(items.toString())+"));window.ZhaoMap.setTrack(JSON.parse("+JSONObject.quote(track.toString())+"));");}
@@ -42,7 +42,7 @@ public class MainActivity extends Activity {
web.getSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW);
web.setWebViewClient(new WebViewClient(){
@Override public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){
return !"https".equals(request.getUrl().getScheme()) || !"zhao.ucvl.cn".equals(request.getUrl().getHost()) || !request.getUrl().getPath().startsWith("/tv");
return !ServerEndpoint.tvNavigation(request.getUrl().toString());
}
});
LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL);
@@ -58,7 +58,7 @@ public class MainActivity extends Activity {
if(code!=null&&code.matches("[0-9]{8}")){intent.removeExtra("pairing_code");pair(code);return;}
String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
// A changed fragment alone does not reload an existing WebView document.
web.loadUrl("https://zhao.ucvl.cn/tv?client=android&load="+System.currentTimeMillis()+(token.isEmpty()?"":"#display="+token));
web.loadUrl(ServerEndpoint.TV+"?client=android&load="+System.currentTimeMillis()+(token.isEmpty()?"":"#display="+token));
if(!token.isEmpty())startForegroundService(new Intent(this,MonitorService.class));
else pairDialog();
}
@@ -68,7 +68,7 @@ public class MonitorService extends Service {
JSONObject post(String path,JSONObject body)throws Exception{
String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
if(token.isEmpty())throw new IOException("Not paired");
HttpsURLConnection c=(HttpsURLConnection)new URL("https://zhao.ucvl.cn"+path).openConnection();
HttpsURLConnection c=(HttpsURLConnection)new URL(ServerEndpoint.api(path)).openConnection();
c.setInstanceFollowRedirects(false);c.setConnectTimeout(10000);c.setReadTimeout(10000);c.setRequestMethod("POST");c.setDoOutput(true);
c.setRequestProperty("Authorization","Bearer "+token);c.setRequestProperty("Content-Type","application/json");
byte[] bytes=body.toString().getBytes(StandardCharsets.UTF_8);c.setFixedLengthStreamingMode(bytes.length);
@@ -0,0 +1,144 @@
package cn.ucvl.zhaodisplay;
import android.app.*;
import android.os.*;
import android.view.View;
import android.widget.*;
import org.json.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.*;
/** Native household/device pages. The server is the sole source of catalog and control grants. */
final class PhoneHomePanel {
final Activity app;final PhoneLayout phone;final PhoneStyle s;final Supplier<String> token;final BooleanSupplier pairingValid;final IntConsumer navigate;
final LinearLayout households,devices;final TextView householdStatus,deviceStatus,selection;
final Button householdRefresh,deviceRefresh;final Handler ui=new Handler();final PhoneHomeSession session=new PhoneHomeSession();
final List<DeviceCard> cards=new ArrayList<>();JSONArray families=new JSONArray(),catalog=new JSONArray();
String selectedFamily="",selectedName="",boundToken="",message="请先在「我的」配对本人的手机。";
boolean foreground=false,busy=false;long lastCatalog=0,lastStatus=0;AlertDialog confirmation;
final Runnable tick=new Runnable(){public void run(){if(!foreground)return;contextChanged();if(homePage()&&valid()){
for(DeviceCard card:cards)card.update();
long elapsed=SystemClock.elapsedRealtime();
if(!busy&&confirmation==null&&elapsed-lastCatalog>=30000)loadCatalog();
else if(!busy&&confirmation==null&&phone.tab==PhoneLayout.DEVICES&&elapsed-lastStatus>=10000)loadStatus();
}ui.postDelayed(this,1000);}};
PhoneHomePanel(Activity app,PhoneLayout phone,Supplier<String> token,BooleanSupplier pairingValid,IntConsumer navigate){
this.app=app;this.phone=phone;this.s=phone.s;this.token=token;this.pairingValid=pairingValid;this.navigate=navigate;
LinearLayout familyPage=phone.pages[PhoneLayout.HOUSEHOLDS],devicePage=phone.pages[PhoneLayout.DEVICES];
householdRefresh=heading(familyPage,"家庭","刷新家庭与设备授权");
familyPage.addView(s.label("选择家庭或办公地点,查看明确授权给你的设备。",14,PhoneStyle.MUTED));s.gap(familyPage,14);
householdStatus=s.label(message,14,PhoneStyle.MUTED);familyPage.addView(householdStatus);s.gap(familyPage,14);households=s.column();familyPage.addView(households);
deviceRefresh=heading(devicePage,"设备","刷新设备状态与授权");
selection=s.label("尚未选择家庭",16,PhoneStyle.MUTED);devicePage.addView(selection);s.gap(devicePage,12);
Button choose=s.button("切换家庭",false);devicePage.addView(choose,new LinearLayout.LayoutParams(-1,-2));choose.setOnClickListener(v->navigate.accept(PhoneLayout.HOUSEHOLDS));s.gap(devicePage,14);
deviceStatus=s.label(message,14,PhoneStyle.MUTED);devicePage.addView(deviceStatus);s.gap(devicePage,14);devices=s.column();devicePage.addView(devices);
householdRefresh.setOnClickListener(v->loadCatalog());deviceRefresh.setOnClickListener(v->loadCatalog());render();
}
Button heading(LinearLayout parent,String title,String description){LinearLayout line=s.line();line.addView(s.bold(title,28),new LinearLayout.LayoutParams(0,-2,1));Button refresh=s.iconButton("refresh",description);line.addView(refresh,new LinearLayout.LayoutParams(s.dp(48),s.dp(48)));parent.addView(line);s.gap(parent,12);return refresh;}
boolean homePage(){return phone.tab==PhoneLayout.HOUSEHOLDS||phone.tab==PhoneLayout.DEVICES;}
boolean valid(){return !app.isDestroyed()&&pairingValid.getAsBoolean()&&!token.get().isEmpty();}
boolean current(PhoneHomeSession.Ticket ticket){return !app.isDestroyed()&&pairingValid.getAsBoolean()&&session.accepts(ticket,token.get());}
void active(boolean active){foreground=active;ui.removeCallbacks(tick);contextChanged();if(active)ui.post(tick);}
void contextChanged(){
boolean enabled=foreground&&homePage()&&valid();
String identity=token.get();if(!boundToken.equals(identity)){boundToken=identity;selectedFamily="";selectedName="";}
if(session.bind(identity,enabled,phone.tab)){
if(confirmation!=null){confirmation.dismiss();confirmation=null;}
busy=false;families=new JSONArray();catalog=new JSONArray();cards.clear();lastCatalog=0;lastStatus=0;
message=valid()?"正在读取设备授权…":"请先在「我的」配对本人的手机。";render();
if(enabled)loadCatalog();
}
}
void close(){foreground=false;ui.removeCallbacksAndMessages(null);session.bind("",false,-1);if(confirmation!=null){confirmation.dismiss();confirmation=null;}families=new JSONArray();catalog=new JSONArray();cards.clear();}
void loadCatalog(){
if(busy||!foreground||!homePage()||!valid())return;
busy=true;message="正在刷新家庭与设备授权…";status();PhoneHomeSession.Ticket ticket=session.begin();lastCatalog=SystemClock.elapsedRealtime();
new Thread(()->{try{
if(!current(ticket))return;
JSONObject result=DisplayApi.call("/api/phone/home",ticket.token,new JSONObject().put("action","catalog"));
// Missing catalog arrays must not preserve cached permissions.
JSONArray receivedFamilies=result.getJSONArray("households"),receivedDevices=result.getJSONArray("devices");
app.runOnUiThread(()->{if(!current(ticket))return;busy=false;families=receivedFamilies;catalog=receivedDevices;
if(!hasFamily(selectedFamily))selectedFamily=result.optString("activeId");
if(!hasFamily(selectedFamily))selectedFamily=firstFamilyId();
selectedName=familyName(selectedFamily);lastStatus=SystemClock.elapsedRealtime();message="只显示已授权给你的设备;查看和控制权限分别授予。";render();
});
}catch(Exception e){app.runOnUiThread(()->failed(ticket,e,false));}},"phone-home-catalog").start();
}
void loadStatus(){
if(busy||!foreground||!homePage()||!valid()||cards.isEmpty())return;
List<String> ids=new ArrayList<>();for(DeviceCard c:cards)if(c.row.optJSONObject("power")!=null)ids.add(c.id);if(ids.isEmpty()){lastStatus=SystemClock.elapsedRealtime();return;}
busy=true;PhoneHomeSession.Ticket ticket=session.begin();lastStatus=SystemClock.elapsedRealtime();status();
new Thread(()->{try{
Map<String,JSONObject> states=new HashMap<>();for(String id:ids){if(!current(ticket))return;JSONObject response=DisplayApi.call("/api/phone/home",ticket.token,new JSONObject().put("action","status").put("deviceId",id));states.put(id,response.getJSONObject("power"));}
app.runOnUiThread(()->{if(!current(ticket))return;busy=false;for(DeviceCard c:cards){JSONObject p=states.get(c.id);if(p!=null)c.apply(p);}status();});
}catch(Exception e){app.runOnUiThread(()->failed(ticket,e,false));}},"phone-home-status").start();
}
void failed(PhoneHomeSession.Ticket ticket,Exception error,boolean command){
if(!current(ticket))return;busy=false;families=new JSONArray();catalog=new JSONArray();cards.clear();selectedName="";
int status=error instanceof DisplayApi.ApiError?((DisplayApi.ApiError)error).status:0;
message=status==401?"手机配对已过期或解除,请到「我的」重新配对。":status==403?"设备授权已失效或无权访问,请联系家庭管理员。":command?"暂时无法确认操作结果。请刷新状态后再决定,勿重复提交。":"暂时无法读取设备状态,已隐藏旧授权。请检查网络并刷新。";
lastCatalog=SystemClock.elapsedRealtime();render();
}
boolean hasFamily(String id){for(int i=0;i<families.length();i++){JSONObject f=families.optJSONObject(i);if(f!=null&&f.optString("id").equals(id))return true;}return false;}
String firstFamilyId(){for(int i=0;i<families.length();i++){JSONObject f=families.optJSONObject(i);if(f!=null&&!f.optString("id").isEmpty())return f.optString("id");}return "";}
String familyName(String id){for(int i=0;i<families.length();i++){JSONObject f=families.optJSONObject(i);if(f!=null&&f.optString("id").equals(id))return f.optString("name","家庭");}return "尚未选择家庭";}
int deviceCount(String family){int count=0;for(int i=0;i<catalog.length();i++){JSONObject row=catalog.optJSONObject(i);if(row!=null&&family.equals(row.optString("familyId")))count++;}return count;}
void render(){
households.removeAllViews();devices.removeAllViews();cards.clear();selection.setText(selectedName.isEmpty()?"尚未选择家庭":selectedName);
for(int i=0;i<families.length();i++){
JSONObject family=families.optJSONObject(i);if(family==null||family.optString("id").isEmpty())continue;String id=family.optString("id"),name=family.optString("name","家庭");
LinearLayout card=s.column();s.card(card);card.addView(s.bold(name,20));s.gap(card,8);String kind=family.optString("kind");card.addView(s.label(("office".equals(kind)?"办公地点":"家庭")+" · "+deviceCount(id)+" 台获授权设备",14,PhoneStyle.MUTED));s.gap(card,14);
Button open=s.button("查看设备",true);open.setContentDescription("查看 "+name+" 的获授权设备");card.addView(open,new LinearLayout.LayoutParams(-1,-2));open.setOnClickListener(v->{selectedFamily=id;selectedName=name;navigate.accept(PhoneLayout.DEVICES);});
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(-1,-2);lp.bottomMargin=s.dp(14);households.addView(card,lp);
}
for(int i=0;i<catalog.length();i++){JSONObject row=catalog.optJSONObject(i);if(row==null||row.optString("id").isEmpty()||!selectedFamily.equals(row.optString("familyId")))continue;DeviceCard c=new DeviceCard(row);cards.add(c);LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(-1,-2);lp.bottomMargin=s.dp(16);devices.addView(c.view,lp);}
status();
}
void status(){
householdStatus.setText(message);deviceStatus.setText(!busy&&families.length()>0&&cards.isEmpty()?"本家庭暂无获授权设备。请联系管理员为本人授予设备查看或控制权限。":message);
boolean refresh=foreground&&homePage()&&valid()&&!busy;householdRefresh.setEnabled(refresh);deviceRefresh.setEnabled(refresh);for(DeviceCard card:cards)card.update();
}
static PhonePowerModel model(JSONObject power){
if(power==null)return new PhonePowerModel(-1,0,"unknown",0,false,false,false);
return new PhonePowerModel(power.isNull("run")?-1:power.optInt("run",-1),power.optInt("op",-1),power.optString("state","unknown"),power.optLong("checkedAt",0),power.optBoolean("canStart",false),power.optBoolean("canShutdown",false),power.optBoolean("managed",false));
}
String time(long seconds){return seconds>0?new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA).format(new Date(seconds*1000)):"尚未检查";}
String resultLabel(String status){switch(status){case "pending":case "queued":return "等待处理";case "scheduled":return "已安排关机";case "succeeded":case "success":return "已完成";case "failed":return "失败";case "blocked":return "已阻止";case "timeout":case "timed_out":return "已超时";default:return status.isEmpty()?"无":status;}}
final class DeviceCard {
final JSONObject row;final String id,name;JSONObject power;PhonePowerModel state;final LinearLayout view;final TextView run,operation,checked,result;final Button start,shutdown;
DeviceCard(JSONObject row){
this.row=row;id=row.optString("id");name=row.optString("name","设备");power=row.optJSONObject("power");state=model(power);view=s.column();s.card(view);view.addView(s.bold(name,21));s.gap(view,8);
String location=row.optString("familyName"),site=row.optString("siteName");if(!site.isEmpty())location+=(location.isEmpty()?"":" · ")+site;view.addView(s.label(location.isEmpty()?"位置未填写":location,14,PhoneStyle.MUTED));s.gap(view,14);
run=s.bold("",18);view.addView(run);s.gap(view,8);operation=s.label("",14,PhoneStyle.MUTED);view.addView(operation);s.gap(view,12);
start=s.button("开机",true);shutdown=s.button("关机",false);start.setContentDescription("开机 "+name);shutdown.setContentDescription("关机 "+name);view.addView(start,new LinearLayout.LayoutParams(-1,-2));s.gap(view,8);view.addView(shutdown,new LinearLayout.LayoutParams(-1,-2));
start.setOnClickListener(v->request(this,1));shutdown.setOnClickListener(v->request(this,2));s.gap(view,14);checked=s.label("",12,PhoneStyle.MUTED);view.addView(checked);s.gap(view,8);result=s.label("",13,PhoneStyle.MUTED);view.addView(result);update();
}
void apply(JSONObject p){power=p;state=model(p);try{row.put("power",p);}catch(JSONException ignored){}update();}
void update(){
long now=System.currentTimeMillis()/1000;int observed=state.run(now);run.setText("RUN "+(observed<0?"— · 未知":observed==1?"1 · 在线":"0 · 不可达"));run.setTextColor(observed==1?PhoneStyle.GREEN:PhoneStyle.MUTED);
operation.setText("OP "+(state.op>=0&&state.op<=2?state.op:"—")+" · "+(!state.managed?"未提供电源管理":state.op==1?"正在开机":state.op==2?"正在关机":observed<0?"等待有效状态":busy?"正在刷新或提交":"空闲"));
boolean enabled=foreground&&homePage()&&valid();start.setEnabled(enabled&&state.may(1,now,busy));shutdown.setEnabled(enabled&&state.may(2,now,busy));
checked.setText("检查时间:"+time(state.checkedAt)+(observed==0?"\n不可达不代表已物理关机。":""));JSONObject last=power==null?null:power.optJSONObject("last");
result.setText(last==null?"最近结果:尚无操作记录":"最近结果:"+resultLabel(last.optString("status"))+" · "+last.optString("result","无详情")+"\n"+time(last.optLong("at")));
}
}
void request(DeviceCard card,int operation){
if(!foreground||phone.tab!=PhoneLayout.DEVICES||!valid()||!cards.contains(card)||!card.state.may(operation,System.currentTimeMillis()/1000,busy))return;
if(operation==1){send(card,operation);return;}
PhoneHomeSession.Ticket ticket=session.begin();
confirmation=new AlertDialog.Builder(app).setTitle("关闭 "+card.name+"?").setMessage("将请求设备正常关机,不会强制关闭应用。请先保存工作;应用阻止关机时,设备可能保持在线。是否继续?").setNegativeButton("取消",null).setPositiveButton("确认关机",(d,w)->{if(current(ticket))send(card,2);}).create();
confirmation.setOnDismissListener(d->confirmation=null);confirmation.show();
}
void send(DeviceCard card,int operation){
if(!foreground||phone.tab!=PhoneLayout.DEVICES||!valid()||!cards.contains(card)||!card.state.may(operation,System.currentTimeMillis()/1000,busy))return;
busy=true;message="正在提交操作,请等待结果…";status();PhoneHomeSession.Ticket ticket=session.begin();String requestId=UUID.randomUUID().toString().replace("-","");
new Thread(()->{try{
if(!current(ticket))return;
JSONObject response=DisplayApi.call("/api/phone/home",ticket.token,new JSONObject().put("action","command").put("deviceId",card.id).put("op",operation).put("requestId",requestId).put("confirm",true));JSONObject power=response.getJSONObject("power");
app.runOnUiThread(()->{if(!current(ticket))return;busy=false;card.apply(power);lastStatus=SystemClock.elapsedRealtime();message="已收到操作结果;设备运行状态以实际检查为准。";status();});
}catch(Exception e){app.runOnUiThread(()->failed(ticket,e,true));}},"phone-home-command").start();
}
}
@@ -0,0 +1,19 @@
package cn.ucvl.zhaodisplay;
/** Invalidates asynchronous home API results on identity, lifecycle, page and request changes. */
final class PhoneHomeSession {
static final class Ticket {final String token;final long generation,request;Ticket(String token,long generation,long request){this.token=token;this.generation=generation;this.request=request;}}
private String token="";private boolean active;private int page=-1;private long generation,request;
synchronized boolean bind(String token,boolean active,int page){
if(token==null)token="";
if(this.token.equals(token)&&this.active==active&&this.page==page)return false;
this.token=token;this.active=active;this.page=page;generation++;return true;
}
synchronized Ticket begin(){
if(!active||token.isEmpty())throw new IllegalStateException("No active phone pairing");
return new Ticket(token,generation,++request);
}
synchronized boolean accepts(Ticket ticket,String currentToken){
return ticket!=null&&active&&!token.isEmpty()&&token.equals(currentToken)&&token.equals(ticket.token)&&generation==ticket.generation&&request==ticket.request;
}
}
@@ -6,49 +6,51 @@ import android.view.*;
import android.widget.*;
import java.util.function.IntConsumer;
/** Three persistent phone pages. All members, permissions and statuses are supplied by the controller. */
/** Five persistent phone pages. All members, permissions and statuses are supplied by the controller. */
final class PhoneLayout extends LinearLayout {
final PhoneStyle s;final ScrollView[] scrolls=new ScrollView[3];final LinearLayout[] pages=new LinearLayout[3];
static final int LOCATION=0,HOUSEHOLDS=1,DEVICES=2,COMMUNICATION=3,MINE=4,PAGE_COUNT=5;
private static final String[] NAMES={"位置","家庭","设备","沟通","我的"},ICONS={"location","family","display","mic","person"};
final PhoneStyle s;final ScrollView[] scrolls=new ScrollView[PAGE_COUNT];final LinearLayout[] pages=new LinearLayout[PAGE_COUNT];
final LinearLayout nav,homeContent,familyList,mineContent,pairIntro,shareCard,profile,voiceSettings;
final FrameLayout mapSlot;final TextView homeName,identity,avatar,homeStatus,myStatus,viewStatus,pairSummary;
final Button settingsButton,check,refresh,fit,pairNow,myCheck;final Switch sharing;
final PhoneStyle.Row viewers,expiry,sampling,upload,history,pairing,permissions;
final TextView[] navLabels=new TextView[3];final ImageView[] navIcons=new ImageView[3];int tab=0;IntConsumer onTab;
final TextView[] navLabels=new TextView[PAGE_COUNT];final ImageView[] navIcons=new ImageView[PAGE_COUNT];int tab=0;IntConsumer onTab;
PhoneLayout(Activity app){
super(app);s=new PhoneStyle(app);setOrientation(VERTICAL);setBackgroundColor(PhoneStyle.PAPER);
FrameLayout content=new FrameLayout(app);addView(content,new LayoutParams(-1,0,1));
for(int i=0;i<3;i++){scrolls[i]=new ScrollView(app);scrolls[i].setFillViewport(true);scrolls[i].setClipToPadding(false);pages[i]=s.column();pages[i].setPadding(s.dp(18),s.dp(18),s.dp(18),s.dp(16));scrolls[i].addView(pages[i]);content.addView(scrolls[i],new FrameLayout.LayoutParams(-1,-1));}
for(int i=0;i<PAGE_COUNT;i++){scrolls[i]=new ScrollView(app);scrolls[i].setFillViewport(true);scrolls[i].setClipToPadding(false);pages[i]=s.column();pages[i].setPadding(s.dp(18),s.dp(18),s.dp(18),s.dp(16));scrolls[i].addView(pages[i]);content.addView(scrolls[i],new FrameLayout.LayoutParams(-1,-1));}
// Keep recipient and microphone visible while only the conversation scrolls.
scrolls[1].removeView(pages[1]);content.removeView(scrolls[1]);content.addView(pages[1],new FrameLayout.LayoutParams(-1,-1));
LinearLayout heading=s.line();TextView title=s.bold("位置",28);heading.addView(title,new LayoutParams(0,-2,1));settingsButton=s.iconButton("settings","打开我的设置");heading.addView(settingsButton,new LayoutParams(s.dp(48),s.dp(48)));pages[0].addView(heading);
homeName=s.label("配对后查看家人",16,PhoneStyle.MUTED);pages[0].addView(homeName);s.gap(pages[0],16);
scrolls[COMMUNICATION].removeView(pages[COMMUNICATION]);content.removeView(scrolls[COMMUNICATION]);content.addView(pages[COMMUNICATION],new FrameLayout.LayoutParams(-1,-1));
LinearLayout heading=s.line();TextView title=s.bold("位置",28);heading.addView(title,new LayoutParams(0,-2,1));settingsButton=s.iconButton("settings","打开我的设置");heading.addView(settingsButton,new LayoutParams(s.dp(48),s.dp(48)));pages[LOCATION].addView(heading);
homeName=s.label("配对后查看家人",16,PhoneStyle.MUTED);pages[LOCATION].addView(homeName);s.gap(pages[LOCATION],16);
LinearLayout banner=s.line();banner.setPadding(s.dp(12),s.dp(10),s.dp(10),s.dp(10));banner.setBackground(s.bordered(PhoneStyle.WARNING,PhoneStyle.WARNING_BORDER,8));
homeStatus=s.label("尚未配对本人",14,PhoneStyle.WARNING_INK);homeStatus.setPadding(0,0,s.dp(8),0);banner.addView(homeStatus,new LayoutParams(0,-2,1));check=s.button("检查",false);banner.addView(check);pages[0].addView(banner);s.gap(pages[0],16);
homeContent=s.column();pages[0].addView(homeContent);
homeStatus=s.label("尚未配对本人",14,PhoneStyle.WARNING_INK);homeStatus.setPadding(0,0,s.dp(8),0);banner.addView(homeStatus,new LayoutParams(0,-2,1));check=s.button("检查",false);banner.addView(check);pages[LOCATION].addView(banner);s.gap(pages[LOCATION],16);
homeContent=s.column();pages[LOCATION].addView(homeContent);
mapSlot=new FrameLayout(app);mapSlot.setBackground(s.bordered(PhoneStyle.PALE,PhoneStyle.LINE,8));mapSlot.setClipToOutline(true);homeContent.addView(mapSlot,new LayoutParams(-1,s.dp(330)));
fit=s.iconButton("location","在地图上查看全部家人");FrameLayout.LayoutParams fitParams=new FrameLayout.LayoutParams(s.dp(48),s.dp(48),Gravity.RIGHT|Gravity.CENTER_VERTICAL);fitParams.setMargins(0,0,s.dp(12),0);mapSlot.addView(fit,fitParams);
TextView privacy=s.label("仅显示已授权的位置",11,PhoneStyle.GREEN);privacy.setPadding(s.dp(10),s.dp(7),s.dp(10),s.dp(7));privacy.setBackground(s.shape(PhoneStyle.CARD,20));FrameLayout.LayoutParams pp=new FrameLayout.LayoutParams(-2,-2,Gravity.LEFT|Gravity.TOP);pp.setMargins(s.dp(10),s.dp(12),s.dp(64),0);mapSlot.addView(privacy,pp);
s.gap(homeContent,14);LinearLayout recent=s.column();s.card(recent);homeContent.addView(recent);LinearLayout recentHead=s.line();recentHead.addView(s.bold("位置列表",17),new LayoutParams(0,-2,1));refresh=s.iconButton("refresh","刷新家人位置");recentHead.addView(refresh,new LayoutParams(s.dp(48),s.dp(48)));recent.addView(recentHead);
viewStatus=s.label("正在读取家人授权…",13,PhoneStyle.MUTED);viewStatus.setPadding(0,s.dp(8),0,s.dp(12));recent.addView(viewStatus);familyList=s.column();s.divided(familyList);recent.addView(familyList);s.gap(homeContent,10);
pairIntro=s.column();s.card(pairIntro);pages[0].addView(pairIntro);pairIntro.addView(s.bold("与家人连接",23));s.gap(pairIntro,12);pairIntro.addView(s.label("使用手机配对码关联自己的成员档案,无需注册。配对后就能查看已授权给你的家人。",16,PhoneStyle.MUTED));s.gap(pairIntro,20);pairNow=s.button("去配对我的手机",true);pairIntro.addView(pairNow);
pairIntro=s.column();s.card(pairIntro);pages[LOCATION].addView(pairIntro);pairIntro.addView(s.bold("与家人连接",23));s.gap(pairIntro,12);pairIntro.addView(s.label("使用手机配对码关联自己的成员档案,无需注册。配对后就能查看已授权给你的家人。",16,PhoneStyle.MUTED));s.gap(pairIntro,20);pairNow=s.button("去配对我的手机",true);pairIntro.addView(pairNow);
// The voice page is populated with the same production VoiceSurface used by the controller.
pages[1].setPadding(0,0,0,s.dp(8));
pages[2].addView(s.bold("我的",27));s.gap(pages[2],20);
profile=s.line();avatar=s.avatar("我",54);profile.addView(avatar);LinearLayout words=s.column();words.setPadding(s.dp(14),0,0,0);identity=s.bold("尚未配对本人",19);pairSummary=s.label("无需注册 · 使用手机配对码",13,PhoneStyle.MUTED);words.addView(identity);s.gap(words,5);words.addView(pairSummary);profile.addView(words,new LayoutParams(0,-2,1));TextView chevron=s.label("›",28,PhoneStyle.MUTED);profile.addView(chevron);profile.setMinimumHeight(s.dp(64));profile.setFocusable(true);profile.setClickable(true);pages[2].addView(profile);s.gap(pages[2],18);
mineContent=s.column();pages[2].addView(mineContent);
pages[COMMUNICATION].setPadding(0,0,0,s.dp(8));
pages[MINE].addView(s.bold("我的",27));s.gap(pages[MINE],20);
profile=s.line();avatar=s.avatar("我",54);profile.addView(avatar);LinearLayout words=s.column();words.setPadding(s.dp(14),0,0,0);identity=s.bold("尚未配对本人",19);pairSummary=s.label("无需注册 · 使用手机配对码",13,PhoneStyle.MUTED);words.addView(identity);s.gap(words,5);words.addView(pairSummary);profile.addView(words,new LayoutParams(0,-2,1));TextView chevron=s.label("›",28,PhoneStyle.MUTED);profile.addView(chevron);profile.setMinimumHeight(s.dp(64));profile.setFocusable(true);profile.setClickable(true);pages[MINE].addView(profile);s.gap(pages[MINE],18);
mineContent=s.column();pages[MINE].addView(mineContent);
shareCard=s.column();s.card(shareCard);mineContent.addView(shareCard);sharing=new Switch(app);sharing.setText("共享我的位置");sharing.setTextSize(19);sharing.setTypeface(null,Typeface.BOLD);sharing.setTextColor(PhoneStyle.INK);sharing.setMinHeight(s.dp(50));sharing.setThumbTintList(new android.content.res.ColorStateList(new int[][]{new int[]{android.R.attr.state_checked},new int[]{}},new int[]{PhoneStyle.GREEN,0xffb5bcb6}));shareCard.addView(sharing);
LinearLayout state=s.line();state.setPadding(s.dp(10),s.dp(6),s.dp(4),s.dp(6));state.setBackground(s.bordered(PhoneStyle.WARNING,PhoneStyle.WARNING_BORDER,6));myStatus=s.label("共享关闭",13,PhoneStyle.WARNING_INK);state.addView(myStatus,new LayoutParams(0,-2,1));myCheck=s.button("检查权限",false);state.addView(myCheck);shareCard.addView(state);s.gap(shareCard,10);shareCard.addView(s.label("查看家人位置,无需开启自己的共享。",12,PhoneStyle.MUTED));
section(mineContent,"允许谁查看");LinearLayout access=s.column();s.card(access);mineContent.addView(access);viewers=s.row("family","查看人名单","读取中");access.addView(viewers);expiry=s.row("clock","共享有效期","跟随本机配对有效期");access.addView(expiry);
section(mineContent,"定位与轨迹");LinearLayout location=s.column();s.card(location);mineContent.addView(location);sampling=s.row("location","共享模式与采集频率","定时采集 · 每 1 分钟");upload=s.row("cloud","集中上传周期","每 5 分钟");history=s.row("track","我的历史轨迹","每天、每周、每月、每年、一生");permissions=s.row("shield","定位权限与系统设置","本人开启共享后才采集");for(View row:new View[]{sampling,upload,history,permissions})location.addView(row);
section(mineContent,"沟通与声音");voiceSettings=s.column();s.card(voiceSettings);mineContent.addView(voiceSettings);
section(pages[2],"设备与系统");LinearLayout device=s.column();s.card(device);pages[2].addView(device);pairing=s.row("phone","配对与设备","查看或更换手机配对");device.addView(pairing);
section(pages[MINE],"设备与系统");LinearLayout device=s.column();s.card(device);pages[MINE].addView(device);pairing=s.row("phone","配对与设备","查看或更换手机配对");device.addView(pairing);
s.card(profile);s.divided(access);s.divided(location);s.divided(device);
nav=s.line();nav.setBackground(s.bordered(PhoneStyle.CARD,PhoneStyle.LINE,0));nav.setPadding(s.dp(8),s.dp(6),s.dp(8),s.dp(6));addView(nav,new LayoutParams(-1,-2));String[] names={"位置","沟通","我的"},icons={"location","mic","person"};
for(int i=0;i<3;i++){final int index=i;LinearLayout item=s.column();item.setGravity(Gravity.CENTER);item.setMinimumHeight(s.dp(64));item.setPadding(0,s.dp(6),0,s.dp(6));navIcons[i]=new ImageView(app);item.addView(navIcons[i],new LayoutParams(s.dp(25),s.dp(25)));s.gap(item,5);navLabels[i]=s.label(names[i],12,PhoneStyle.MUTED);navLabels[i].setGravity(Gravity.CENTER);item.addView(navLabels[i]);item.setContentDescription(names[i]);item.setFocusable(true);item.setClickable(true);item.setOnClickListener(v->{select(index);if(onTab!=null)onTab.accept(index);});nav.addView(item,new LayoutParams(0,-2,1));}
select(0);
nav=s.line();nav.setBackground(s.bordered(PhoneStyle.CARD,PhoneStyle.LINE,0));nav.setPadding(s.dp(8),s.dp(6),s.dp(8),s.dp(6));addView(nav,new LayoutParams(-1,-2));
for(int i=0;i<PAGE_COUNT;i++){final int index=i;LinearLayout item=s.column();item.setGravity(Gravity.CENTER);item.setMinimumHeight(s.dp(64));item.setPadding(0,s.dp(6),0,s.dp(6));navIcons[i]=new ImageView(app);item.addView(navIcons[i],new LayoutParams(s.dp(25),s.dp(25)));s.gap(item,5);navLabels[i]=s.label(NAMES[i],12,PhoneStyle.MUTED);navLabels[i].setGravity(Gravity.CENTER);item.addView(navLabels[i]);item.setContentDescription(NAMES[i]);item.setFocusable(true);item.setClickable(true);item.setOnClickListener(v->{select(index);if(onTab!=null)onTab.accept(index);});nav.addView(item,new LayoutParams(0,-2,1));}
select(LOCATION);
}
void section(LinearLayout parent,String title){s.gap(parent,22);parent.addView(s.bold(title,17));s.gap(parent,10);}
void select(int next){tab=next;pages[1].setVisibility(next==1?VISIBLE:GONE);for(int i=0;i<3;i++){scrolls[i].setVisibility(i==next?VISIBLE:GONE);nav.getChildAt(i).setSelected(i==next);nav.getChildAt(i).setBackground(s.shape(i==next?PhoneStyle.PALE:PhoneStyle.CARD,6));navLabels[i].setTextColor(i==next?PhoneStyle.GREEN:PhoneStyle.MUTED);navLabels[i].setTypeface(null,i==next?Typeface.BOLD:Typeface.NORMAL);navIcons[i].setImageDrawable(new PhoneStyle.Icon(new String[]{"location","mic","person"}[i],i==next?PhoneStyle.GREEN:PhoneStyle.MUTED,s.dp(25)));}}
void select(int next){if(next<0||next>=PAGE_COUNT)throw new IllegalArgumentException("Invalid phone page");tab=next;pages[COMMUNICATION].setVisibility(next==COMMUNICATION?VISIBLE:GONE);for(int i=0;i<PAGE_COUNT;i++){scrolls[i].setVisibility(i==next?VISIBLE:GONE);nav.getChildAt(i).setSelected(i==next);nav.getChildAt(i).setBackground(s.shape(i==next?PhoneStyle.PALE:PhoneStyle.CARD,6));navLabels[i].setTextColor(i==next?PhoneStyle.GREEN:PhoneStyle.MUTED);navLabels[i].setTypeface(null,i==next?Typeface.BOLD:Typeface.NORMAL);navIcons[i].setImageDrawable(new PhoneStyle.Icon(ICONS[i],i==next?PhoneStyle.GREEN:PhoneStyle.MUTED,s.dp(25)));}}
void family(String name,String detail,boolean position,Runnable focus,Runnable history){
LinearLayout row=s.line();row.setPadding(0,s.dp(10),0,s.dp(10));TextView avatar=s.avatar(name,42);row.addView(avatar);LinearLayout words=s.column();words.setPadding(s.dp(12),0,s.dp(6),0);TextView title=s.bold(name,17);words.addView(title);s.gap(words,5);words.addView(s.label(detail,12,PhoneStyle.MUTED));words.setMinimumHeight(s.dp(48));words.setFocusable(true);words.setClickable(true);words.setOnClickListener(v->focus.run());words.setContentDescription(name+","+detail+(position?",在地图上查看":""));row.addView(words,new LayoutParams(0,-2,1));Button more=s.button("轨迹",false);more.setContentDescription("查看 "+name+" 的已授权历史轨迹");more.setOnClickListener(v->history.run());row.addView(more);familyList.addView(row);
}
@@ -0,0 +1,18 @@
package cn.ucvl.zhaodisplay;
/** Observed RUN and explicit server capabilities; OP never predicts physical state. */
final class PhonePowerModel {
final int measuredRun,op;final String state;final long checkedAt;final boolean canStart,canShutdown,managed;
PhonePowerModel(int run,int op,String state,long checkedAt,boolean canStart,boolean canShutdown,boolean managed){this.measuredRun=run;this.op=op;this.state=state;this.checkedAt=checkedAt;this.canStart=canStart;this.canShutdown=canShutdown;this.managed=managed;}
int run(long now){
if(checkedAt<=0||now<checkedAt-5||now-checkedAt>45||op<0||op>2)return -1;
if(measuredRun==1&&"online".equals(state))return 1;
if(measuredRun==0&&"offline".equals(state))return 0;
return -1;
}
boolean may(int operation,long now,boolean submitting){
if(!managed||submitting||op!=0)return false;
int observed=run(now);
return operation==1?observed==0&&canStart:operation==2&&observed==1&&canShutdown;
}
}
@@ -0,0 +1,31 @@
package cn.ucvl.zhaodisplay;
import java.net.URI;
import java.net.URISyntaxException;
/** One official HTTPS origin and purpose-specific route allowlists. */
final class ServerEndpoint {
static final String HOST="home.ucvl.cn",BASE="https://"+HOST,MAP_PHONE=BASE+"/maps/phone",TV=BASE+"/tv";
static String api(String path){
if(path==null||!path.startsWith("/api/"))throw new IllegalArgumentException("Expected first-party API path");
String url=BASE+path;URI uri=trusted(url);
if(uri==null||uri.getFragment()!=null)throw new IllegalArgumentException("Invalid API path");
return url;
}
static boolean mapResource(String url){URI uri=trusted(url);return uri!=null&&(uri.getPath().startsWith("/maps/")||uri.getPath().startsWith("/ui/assets/"));}
static boolean mapPage(String url){URI uri=trusted(url);return uri!=null&&"/maps/phone".equals(uri.getPath());}
static boolean tvNavigation(String url){URI uri=trusted(url);return uri!=null&&("/tv".equals(uri.getPath())||uri.getPath().startsWith("/tv/"));}
private static URI trusted(String url){
if(url==null)return null;
try{
URI uri=new URI(url);
if(!"https".equalsIgnoreCase(uri.getScheme())||!HOST.equalsIgnoreCase(uri.getHost())||uri.getRawUserInfo()!=null||(uri.getPort()!=-1&&uri.getPort()!=443))return null;
String path=uri.getRawPath();
// These registered routes use plain ASCII paths. Do not let encoded separators or
// dot segments be interpreted differently by WebView, proxies and the server.
if(path==null||!path.startsWith("/")||path.contains("%")||path.contains("\\")||path.contains("//"))return null;
for(String segment:path.split("/"))if(segment.equals(".")||segment.equals(".."))return null;
return uri;
}catch(URISyntaxException error){return null;}
}
}
@@ -0,0 +1,46 @@
package cn.ucvl.zhaodisplay;
/** Pure Java checks: no transport, credentials, Android runtime or physical power operations. */
public class PhonePowerModelTest {
static int assertions;
static void check(boolean condition,String description){assertions++;if(!condition)throw new AssertionError(description);}
static PhonePowerModel power(int run,int op,String state,long at,boolean start,boolean shutdown,boolean managed){return new PhonePowerModel(run,op,state,at,start,shutdown,managed);}
public static void main(String[] args){
PhonePowerModel online=power(1,0,"online",1000,false,true,true);
check(online.run(1045)==1,"fresh online RUN remains observed at TTL boundary");
check(online.may(2,1045,false),"fresh explicitly allowed shutdown");
check(!online.may(1,1000,false),"online cannot be started even when caller chooses OP1");
check(online.run(1046)==-1,"stale RUN must become unknown");
check(!online.may(2,1046,false),"stale permission cannot enable shutdown");
PhonePowerModel offline=power(0,0,"offline",1000,true,false,true);
check(offline.run(1000)==0&&offline.may(1,1000,false),"fresh offline asset allows granted start");
check(!offline.may(2,1000,false),"offline cannot be shut down");
check(!power(0,0,"offline",1000,false,false,true).may(1,1000,false),"view grant is not control grant");
check(!power(1,0,"online",1000,true,true,false).may(2,1000,false),"unmanaged assets cannot receive power commands");
check(!online.may(2,1000,true),"in flight request blocks repeated taps");
for(int op:new int[]{1,2}){
PhonePowerModel pending=power(1,op,"online",1000,true,true,true);
check(pending.run(1000)==1,"OP must not infer RUN");
check(!pending.may(1,1000,false)&&!pending.may(2,1000,false),"server pending OP blocks further commands");
}
for(PhonePowerModel invalid:new PhonePowerModel[]{power(-1,0,"unknown",1000,true,true,true),power(0,0,"online",1000,true,true,true),power(1,0,"offline",1000,true,true,true),power(1,0,"online",0,true,true,true),power(1,0,"online",1100,true,true,true),power(1,7,"online",1000,true,true,true)}){
check(invalid.run(1000)==-1,"unknown, inconsistent or invalid server state fails closed");
check(!invalid.may(1,1000,false)&&!invalid.may(2,1000,false),"invalid state disables both actions");
}
check(!online.may(0,1000,false)&&!online.may(3,1000,false),"only OP1 and OP2 are executable");
PhoneHomeSession session=new PhoneHomeSession();
session.bind("paired-a",true,1);PhoneHomeSession.Ticket first=session.begin();
check(session.accepts(first,"paired-a"),"current paired foreground request accepted");
check(!session.accepts(first,"paired-b"),"token supplier change rejects callback before next render");
session.bind("paired-a",true,1);check(session.accepts(first,"paired-a"),"same context refresh retains request");
PhoneHomeSession.Ticket newer=session.begin();check(!session.accepts(first,"paired-a")&&session.accepts(newer,"paired-a"),"newer request supersedes old response");
session.bind("paired-a",true,2);check(!session.accepts(newer,"paired-a"),"tab switch invalidates callbacks");
PhoneHomeSession.Ticket tab=session.begin();session.bind("paired-a",false,2);check(!session.accepts(tab,"paired-a"),"pause invalidates callbacks");
session.bind("paired-a",true,2);check(!session.accepts(tab,"paired-a"),"resume cannot revive pre-pause response");
PhoneHomeSession.Ticket rebound=session.begin();session.bind("paired-b",true,2);check(!session.accepts(rebound,"paired-a")&&!session.accepts(rebound,"paired-b"),"re-pair invalidates old identity");
session.bind("",true,2);try{session.begin();throw new AssertionError("unpaired request allowed");}catch(IllegalStateException expected){assertions++;}
session.bind("paired-b",false,2);try{session.begin();throw new AssertionError("background request allowed");}catch(IllegalStateException expected){assertions++;}
System.out.println("Phone power/session: "+assertions+" assertions passed");
}
}
@@ -0,0 +1,28 @@
package cn.ucvl.zhaodisplay;
/** Executes real URL construction and WebView allowlists without network or Android runtime. */
public class ServerEndpointTest {
static int assertions;
static void check(boolean condition,String message){assertions++;if(!condition)throw new AssertionError(message);}
public static void main(String[] args){
check(ServerEndpoint.api("/api/phone/home").equals("https://home.ucvl.cn/api/phone/home"),"phone API uses the official domain");
check(ServerEndpoint.api("/api/display/heartbeat").equals("https://home.ucvl.cn/api/display/heartbeat"),"display heartbeat shares the same endpoint");
check(ServerEndpoint.MAP_PHONE.equals("https://home.ucvl.cn/maps/phone"),"first-party map entry uses official origin");
check(ServerEndpoint.tvNavigation(ServerEndpoint.TV+"?client=android&load=42#display=fixture"),"display pairing fragment stays on official TV origin");
check(ServerEndpoint.tvNavigation("https://home.ucvl.cn:443/tv/child"),"explicit HTTPS default port and TV child allowed");
for(String url:new String[]{"https://home.ucvl.cn/maps/phone","https://home.ucvl.cn:443/maps/tile?z=1&x=1&y=0","https://home.ucvl.cn/ui/assets/map-abc.js"})check(ServerEndpoint.mapResource(url),"allow only first-party map resources: "+url);
check(ServerEndpoint.mapPage("https://home.ucvl.cn/maps/phone?theme=day"),"ready callback accepts exact map document with query");
check(!ServerEndpoint.mapPage("https://home.ucvl.cn/maps/phone-evil"),"map ready is not a prefix match");
check(!ServerEndpoint.mapPage("https://home.ucvl.cn/maps/tile"),"tile cannot mark map document ready");
for(String url:new String[]{null,"","http://home.ucvl.cn/maps/phone","https://zhao.ucvl.cn/maps/phone","https://home.ucvl.cn.evil.invalid/maps/phone","https://evil.invalid@home.ucvl.cn/maps/phone","https://home.ucvl.cn@evil.invalid/maps/phone","https://home.ucvl.cn:444/maps/phone","https://home.ucvl.cn./maps/phone","//home.ucvl.cn/maps/phone","file:///maps/phone","javascript:alert(1)","https://home.ucvl.cn/maps/../api/private","https://home.ucvl.cn/maps/%2e%2e/api/private","https://home.ucvl.cn/maps/%252e%252e/api/private","https://home.ucvl.cn/maps/%2f..%2fapi/private","https://home.ucvl.cn/maps\\phone","https://home.ucvl.cn/maps//phone"}){
check(!ServerEndpoint.mapResource(url),"reject unsafe map resource: "+url);
check(!ServerEndpoint.mapPage(url),"reject unsafe map completion URL: "+url);
}
for(String url:new String[]{"https://home.ucvl.cn/api/phone/home","https://home.ucvl.cn/maps","https://home.ucvl.cn/ui/assets-evil/map.js","https://home.ucvl.cn/ui/private"})check(!ServerEndpoint.mapResource(url),"reject unrelated first-party path: "+url);
for(String url:new String[]{"https://home.ucvl.cn/tv-evil","https://home.ucvl.cn/tv/../api","https://home.ucvl.cn:8443/tv","https://evil.invalid/tv","https://zhao.ucvl.cn/tv","https://home.ucvl.cn/maps/phone","https://user@home.ucvl.cn/tv","http://home.ucvl.cn/tv"})check(!ServerEndpoint.tvNavigation(url),"reject unsafe TV navigation: "+url);
for(String path:new String[]{null,"","api/voice","//evil.invalid/api/voice","https://evil.invalid/api/voice","/maps/phone","/api/../tv","/api/%2e%2e/tv","/api/voice#token"}){
try{ServerEndpoint.api(path);throw new AssertionError("unsafe API path accepted: "+path);}catch(IllegalArgumentException expected){assertions++;}
}
System.out.println("Server endpoint allowlist: "+assertions+" assertions passed");
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ if($LASTEXITCODE){throw 'Test resource linking failed'}
$queueSource=Get-Content -LiteralPath "$source\src\cn\ucvl\zhaodisplay\LocationQueue.java" -Raw -Encoding UTF8
$queueSource=$queueSource.Replace('LocationQueue','StoredLocationQueue').Replace('location-outbox.db','storage-check.db')
[IO.File]::WriteAllText("$stage\StoredLocationQueue.java",$queueSource,(New-Object Text.UTF8Encoding($false)))
$sources=@("$stage\StoredLocationQueue.java","$source\src\cn\ucvl\zhaodisplay\LocationService.java","$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceChat.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName)
$sources=@("$stage\StoredLocationQueue.java","$source\src\cn\ucvl\zhaodisplay\LocationService.java","$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneHomePanel.java","$source\src\cn\ucvl\zhaodisplay\PhonePowerModel.java","$source\src\cn\ucvl\zhaodisplay\PhoneHomeSession.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceChat.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName)
& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$stage\classes" @sources
if($LASTEXITCODE){throw 'Test Java compile failed'}
& "$jdk\bin\jar.exe" cf "$stage\classes.jar" -C "$stage\classes" .
@@ -6,6 +6,7 @@ final class DisplayApi {
static class ApiError extends Exception {final int status;ApiError(int status){this.status=status;}}
static JSONObject call(String path,String token,JSONObject body)throws Exception{
if(expired)throw new ApiError(401);if(offline)throw new ApiError(503);String action=body.optString("action");
if(path.equals("/api/phone/home"))return HomeFixture.call(token,body);
if(path.equals("/api/voice")){
if(action.equals("history")){boolean old=body.optLong("before")>0;JSONArray items=new JSONArray();for(int i=0;i<3;i++)items.put(new JSONObject().put("id","chat-"+i).put("seq",i+1).put("mine",i%2==0).put("senderName",i%2==0?"示例成员的手机":"家庭显示终端").put("at",1792387200+i*60-(old?86400:0)).put("seconds",i+3.6).put("delivery",i==2?"queued":"played").put("archive",i==2?"pending":"cloud"));return new JSONObject().put("items",items).put("before",old?0:12);}
return new JSONObject("{\"enabled\":false,\"allowed\":[],\"candidates\":[{\"id\":\"phone:demo\",\"name\":\"示例家人的手机\"}],\"targets\":[{\"id\":\"display:demo\",\"archiveKey\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}],\"conversations\":[],\"sent\":[],\"inbox\":[]}");
@@ -0,0 +1,36 @@
package cn.ucvl.zhaodisplay;
import org.json.*;
/** Entirely synthetic grants and machines. Test APK has no Internet permission. */
final class HomeFixture {
static volatile String mode="";static volatile int commands;static volatile JSONObject lastCommand;
static volatile boolean holdNextCatalog=false,held=false,release=false;
static JSONObject power(String id)throws Exception{
long now=System.currentTimeMillis()/1000;boolean offline=id.equals("demo-offline"),unknown=mode.equals("devices-unknown");
int op=mode.equals("devices-pending")?2:0;
JSONObject p=new JSONObject().put("run",unknown?JSONObject.NULL:offline?0:1).put("op",op).put("state",unknown?"unknown":offline?"offline":"online").put("checkedAt",now-(mode.equals("devices-stale")?90:0)).put("canStart",offline&&!unknown&&op==0).put("canShutdown",!offline&&!unknown&&op==0&&!mode.equals("devices-view-only")).put("managed",true);
p.put("last",op==0?JSONObject.NULL:new JSONObject().put("id","bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb").put("op",2).put("status","pending").put("result","等待设备确认").put("at",now));return p;
}
static JSONObject device(String id,String name,String family)throws Exception{return new JSONObject().put("id",id).put("source","managed").put("name",name).put("deviceType","computer").put("familyId",family).put("familyName",family.equals("demo-home")?"演示家庭":"演示工作室").put("siteName","演示书房").put("power",power(id));}
static JSONObject call(String token,JSONObject body)throws Exception{
if(token==null||token.isEmpty())throw new AssertionError("phone home requires the pairing bearer token");
if(mode.equals("devices-denied"))throw new DisplayApi.ApiError(403);
String action=body.getString("action");
if(action.equals("catalog")){
JSONArray families=new JSONArray().put(new JSONObject().put("id","demo-home").put("name","演示家庭").put("kind","family"));
JSONArray devices=new JSONArray();
if(!mode.equals("devices-empty")&&!token.equals("rebound-token")){families.put(new JSONObject().put("id","demo-office").put("name","演示工作室").put("kind","office"));devices.put(device("demo-online","演示笔记本","demo-home")).put(device("demo-offline","演示工作电脑","demo-office"));}
JSONObject result=new JSONObject().put("households",families).put("devices",devices).put("activeId","demo-home");
if(holdNextCatalog){holdNextCatalog=false;held=true;long until=System.currentTimeMillis()+5000;while(!release&&System.currentTimeMillis()<until)Thread.sleep(10);held=false;}
return result;
}
if(action.equals("status"))return new JSONObject().put("power",power(body.getString("deviceId")));
if(action.equals("command")){
if(!body.optBoolean("confirm")||!body.optString("requestId").matches("[0-9a-f]{32}"))throw new AssertionError("command must carry explicit confirm and a unique request id");
int op=body.optInt("op");if(op!=1&&op!=2)throw new AssertionError("only discrete power operations");
commands++;lastCommand=body;JSONObject p=power(body.getString("deviceId"));p.put("op",op).put("canStart",false).put("canShutdown",false).put("last",new JSONObject().put("id",body.getString("requestId")).put("op",op).put("status","pending").put("result","已提交演示请求").put("at",System.currentTimeMillis()/1000));return new JSONObject().put("power",p);
}
throw new AssertionError("unexpected home action "+action);
}
}
@@ -0,0 +1,57 @@
package cn.ucvl.zhaodisplay;
import android.app.AlertDialog;
import android.os.Handler;
import android.view.*;
import android.widget.*;
/** Exercises production navigation and native power cards through isolated API responses. */
final class HomePanelChecks {
static Button button(View root,String text){if(root instanceof Button&&((Button)root).getText().toString().equals(text))return (Button)root;if(root instanceof ViewGroup){ViewGroup group=(ViewGroup)root;for(int i=0;i<group.getChildCount();i++){Button b=button(group.getChildAt(i),text);if(b!=null)return b;}}return null;}
static boolean text(View root,String value){if(root instanceof TextView&&((TextView)root).getText().toString().contains(value))return true;if(root instanceof ViewGroup){ViewGroup group=(ViewGroup)root;for(int i=0;i<group.getChildCount();i++)if(text(group.getChildAt(i),value))return true;}return false;}
static void later(Runnable action){new Handler().postDelayed(action,500);}
static void run(PhonePreviewActivity a,Runnable done){
a.selectTab(PhoneLayout.HOUSEHOLDS);
later(()->{
PhoneHomePanel panel=a.phoneHome;
if(a.mode.equals("devices-denied")){a.check(panel.devices.getChildCount()==0,"denied grant clears device cards");a.selectTab(PhoneLayout.DEVICES);later(()->{a.check(text(a.phone.pages[PhoneLayout.DEVICES],"授权"),"denied access is explicit");done.run();});return;}
a.check(text(panel.households,"演示家庭"),"paired household remains visible");
if(a.mode.equals("devices-empty")){a.check(panel.devices.getChildCount()==0,"pairing alone grants no devices");a.selectTab(PhoneLayout.DEVICES);later(()->{a.check(text(a.phone.pages[PhoneLayout.DEVICES],"管理员"),"empty grant tells user to contact administrator");done.run();});return;}
a.check(panel.households.getChildCount()==2,"only API-authorized households shown");
if(a.mode.startsWith("households")){done.run();return;}
button(panel.households,"查看设备").performClick();
later(()->{
a.check(a.phone.tab==PhoneLayout.DEVICES,"household selection opens device page");
a.check(panel.devices.getChildCount()==1&&text(panel.devices,"演示笔记本")&&!text(panel.devices,"演示工作电脑"),"family selection scopes visible devices");
a.check(text(panel.devices,"演示书房")&&text(panel.devices,"RUN")&&text(panel.devices,"OP")&&text(panel.devices,"检查时间")&&text(panel.devices,"最近结果"),"managed card exposes location and measured state details");
Button start=button(panel.devices,"开机"),stop=button(panel.devices,"关机");
a.check(!start.isEnabled(),"online device start disabled");
boolean blocked=a.mode.equals("devices-stale")||a.mode.equals("devices-unknown")||a.mode.equals("devices-pending")||a.mode.equals("devices-view-only");
a.check(stop.isEnabled()!=blocked,"shutdown follows freshness, pending OP and explicit grant");
if(a.mode.equals("devices-stale")||a.mode.equals("devices-unknown"))a.check(text(panel.devices,"未知"),"stale/unknown RUN never presented as online");
a.check(start.getHeight()>=a.style.dp(48)&&stop.getHeight()>=a.style.dp(48),"power controls preserve touch targets on narrow/large text views");
a.check(stop.getWidth()>a.style.dp(150),"stacked controls retain usable width");
if(a.mode.equals("devices-token")||a.mode.equals("devices-lifecycle")){
HomeFixture.release=false;HomeFixture.holdNextCatalog=true;panel.deviceRefresh.performClick();
later(()->{a.check(HomeFixture.held,"catalog response is delayed at the network boundary");
if(a.mode.equals("devices-token")){a.prefs.edit().putString("token","rebound-token").commit();panel.contextChanged();}else panel.active(false);
HomeFixture.release=true;later(()->{a.check(panel.devices.getChildCount()==0,"old identity/lifecycle callback cannot restore device grants");
if(a.mode.equals("devices-lifecycle")){panel.active(true);later(()->{a.check(panel.devices.getChildCount()==1,"resume reloads authorized current catalog");done.run();});}else done.run();
});
});return;
}
if(a.mode.equals("devices-revoked")){
HomeFixture.mode="devices-denied";panel.deviceRefresh.performClick();later(()->{a.check(panel.devices.getChildCount()==0&&text(a.phone.pages[PhoneLayout.DEVICES],"授权"),"revocation clears previously visible controls");done.run();});return;
}
if(a.mode.equals("devices-command")){
int before=HomeFixture.commands;stop.performClick();a.check(panel.confirmation!=null&&panel.confirmation.isShowing(),"shutdown has native confirmation");a.check(HomeFixture.commands==before,"opening confirmation never dispatches");panel.confirmation.getButton(AlertDialog.BUTTON_NEGATIVE).performClick();a.check(HomeFixture.commands==before,"cancel leaves machine untouched");stop.performClick();panel.confirmation.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
later(()->{a.check(HomeFixture.commands==before+1&&HomeFixture.lastCommand.optInt("op")==2,"confirmed shutdown dispatches exactly once");a.check(!button(panel.devices,"关机").isEnabled(),"pending command disables repeat");done.run();});return;
}
if(a.mode.equals("devices-offline")){
a.selectTab(PhoneLayout.HOUSEHOLDS);later(()->{button((ViewGroup)panel.households.getChildAt(1),"查看设备").performClick();later(()->{a.check(text(panel.devices,"RUN 0")&&button(panel.devices,"开机").isEnabled()&&!button(panel.devices,"关机").isEnabled(),"offline explicit control grant enables only start");done.run();});});return;
}
done.run();
});
});
}
}
@@ -11,14 +11,14 @@ public class PhonePreviewActivity extends LocationActivity {
protected void attachBaseContext(android.content.Context base){android.content.res.Configuration c=new android.content.res.Configuration(base.getResources().getConfiguration());c.densityDpi=420;super.attachBaseContext(base.createConfigurationContext(c));}
public void onCreate(Bundle state){
mode=getIntent().getStringExtra("mode");if(mode==null)mode="family";
if(mode.equals("large")||mode.equals("settings-large")||mode.equals("voice-large")){android.content.res.Configuration cfg=new android.content.res.Configuration(getResources().getConfiguration());cfg.fontScale=1.35f;getResources().updateConfiguration(cfg,getResources().getDisplayMetrics());}
DisplayApi.offline="offline".equals(mode);DisplayApi.expired="expired".equals(mode);
if(mode.equals("large")||mode.equals("settings-large")||mode.equals("voice-large")||mode.equals("devices-large")){android.content.res.Configuration cfg=new android.content.res.Configuration(getResources().getConfiguration());cfg.fontScale=1.35f;getResources().updateConfiguration(cfg,getResources().getDisplayMetrics());}
HomeFixture.mode=mode;DisplayApi.offline="offline".equals(mode);DisplayApi.expired="expired".equals(mode);
getSharedPreferences("location",0).edit().clear().putString("token","unpaired".equals(mode)?"":"synthetic-token").putString("memberName","示例成员").putString("home","我的家 · 演示家庭").putLong("expires",System.currentTimeMillis()+86400000L).putString("status","共享关闭 · 可以查看已授权的家人").apply();
super.onCreate(state);
// Limit the actual Activity layout to a phone viewport without changing display configuration.
((android.view.ViewGroup)phone.getParent()).removeView(phone);FrameLayout outer=new FrameLayout(this);outer.setBackgroundColor(PhoneStyle.PAPER);
int width="narrow".equals(mode)||"large".equals(mode)||"voice-large".equals(mode)?320:390;outer.addView(phone,new FrameLayout.LayoutParams(style.dp(width),style.dp("narrow".equals(mode)?640:844),Gravity.TOP|Gravity.CENTER_HORIZONTAL));previewRoot=phone;setContentView(outer);
new Handler().postDelayed(()->{try{exercise();if(mode.equals("history"))exerciseHistory();else if(mode.equals("cycles"))LocationCycleChecks.run(this,this::save);else if(mode.equals("storage")){QueueStorageChecks.run(this);save();}else save();}catch(Exception e){throw new RuntimeException(e);}},1800);
int width="narrow".equals(mode)||"large".equals(mode)||"voice-large".equals(mode)||"devices-narrow".equals(mode)||"devices-large".equals(mode)?320:390;outer.addView(phone,new FrameLayout.LayoutParams(style.dp(width),style.dp("narrow".equals(mode)?640:844),Gravity.TOP|Gravity.CENTER_HORIZONTAL));previewRoot=phone;setContentView(outer);
new Handler().postDelayed(()->{try{exercise();if(mode.startsWith("devices")||mode.startsWith("households"))HomePanelChecks.run(this,this::save);else if(mode.equals("history"))exerciseHistory();else if(mode.equals("cycles"))LocationCycleChecks.run(this,this::save);else if(mode.equals("storage")){QueueStorageChecks.run(this);save();}else save();}catch(Exception e){throw new RuntimeException(e);}},1800);
}
void check(boolean condition,String message){if(!condition)throw new AssertionError(message);}
void exercise()throws Exception{
@@ -28,32 +28,32 @@ public class PhonePreviewActivity extends LocationActivity {
check(map.items.optJSONObject(0).optString("id").equals("c")&&map.items.optJSONObject(2).optString("id").equals("b"),"collection time descending, missing fixes last");
((android.view.ViewGroup)familyList.getChildAt(0)).getChildAt(1).performClick();check(map.focused==map.items.optJSONObject(0).optJSONObject("position"),"row focuses the matching point");
check(voice.getParent()==null,"no voice dock on the position page");check(voice.dock.receiverCard.getParent()==phone.voiceSettings,"receiver controls belong to my settings");
phone.nav.getChildAt(2).performClick();check(phone.tab==2,"mine tab click");phone.sampling.performClick();check(detailDialog!=null&&detailDialog.isShowing(),"sampling opens full screen");detailDialog.dismiss();
phone.nav.getChildAt(PhoneLayout.MINE).performClick();check(phone.tab==PhoneLayout.MINE,"mine tab click");phone.sampling.performClick();check(detailDialog!=null&&detailDialog.isShowing(),"sampling opens full screen");detailDialog.dismiss();
check(sampleCadence.getParent()==sampleSection,"sample controls retain their owner");
phone.upload.performClick();check(detailDialog!=null,"upload detail");detailDialog.dismiss();
phone.nav.getChildAt(0).performClick();check(phone.tab==0,"family navigation");
phone.nav.getChildAt(PhoneLayout.LOCATION).performClick();check(phone.tab==PhoneLayout.LOCATION,"family navigation");
check(!prefs.getBoolean("active",false),"navigation never enables sharing");
}
if(mode.equals("modes")){
selectTab(2);sharingMode.setSelection(1);check(samplePeriodSeconds()==10&&uploadPeriod()==10,"realtime fixes both cadences to ten seconds");
selectTab(PhoneLayout.MINE);sharingMode.setSelection(1);check(samplePeriodSeconds()==10&&uploadPeriod()==10,"realtime fixes both cadences to ten seconds");
sharingMode.setSelection(0);check(samplePeriodSeconds()==300&&uploadPeriod()==7200,"scheduled controls retain independent cadences");
check(!prefs.getBoolean("active",false),"choosing a mode never enables sharing");
}
if(mode.equals("mine")||mode.equals("large"))selectTab(2);
if(mode.equals("mine")||mode.equals("large"))selectTab(PhoneLayout.MINE);
else if(mode.equals("voice")||mode.equals("voice-large")||mode.equals("recording")||mode.equals("cancel")||mode.equals("narrow")||mode.equals("history")){
selectTab(1);voice.ui.removeCallbacks(voice.visual);VoiceSurface v=voice.page();v.expand.setVisibility(View.GONE);v.destination(new JSONObject("{\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}"),true);v.recipient.setText("家庭显示终端");v.status.setText("界面验收 · 不录音、不发送语音");
selectTab(PhoneLayout.COMMUNICATION);voice.ui.removeCallbacks(voice.visual);VoiceSurface v=voice.page();v.expand.setVisibility(View.GONE);v.destination(new JSONObject("{\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}"),true);v.recipient.setText("家庭显示终端");v.status.setText("界面验收 · 不录音、不发送语音");
boolean recording=mode.equals("recording")||mode.equals("cancel");for(int i=0;i<31;i++)v.recording(recording,mode.equals("cancel"),8000,(int)(9000*Math.abs(Math.sin(i))),false,true);
}
else if(mode.equals("unpaired")){check(shareControls.getVisibility()==View.GONE,"unpaired share controls hidden");check(phone.tab==2,"unpaired starts on my page");}
else selectTab(0);
else if(mode.equals("unpaired")){check(shareControls.getVisibility()==View.GONE,"unpaired share controls hidden");check(phone.tab==PhoneLayout.MINE,"unpaired starts on my page");}
else selectTab(PhoneLayout.LOCATION);
if(mode.equals("expired")){check(pairingRequired(),"expired requires re-pairing");check(!sharing.isEnabled(),"expired cannot start sharing");phone.check.performClick();check(detailDialog!=null&&pairSection.getParent()!=settings,"status routes to pairing instead of OS permission settings");detailDialog.dismiss();}
if(mode.equals("offline")){check(familyList.getChildCount()==0,"offline stale positions removed");check(!sharing.isEnabled(),"offline cannot start sharing");}
check(phone.nav.getChildCount()==3,"exactly three tabs");check(phone.navLabels[0].getText().toString().equals("位置")&&phone.navLabels[1].getText().toString().equals("沟通"),"requested navigation names");
check(phone.nav.getChildCount()==5,"exactly five tabs");String[] names={"位置","家庭","设备","沟通","我的"};for(int i=0;i<names.length;i++)check(phone.navLabels[i].getText().toString().equals(names[i]),"requested navigation names");
check(voice.page().receiverCard.getParent()==null,"communication page does not duplicate settings");
check(phone.nav.getChildAt(phone.tab).isSelected(),"active Bootstrap navigation state");
Button disabled=style.button("测试",false);disabled.setEnabled(false);check(disabled.getCurrentTextColor()==0xff868e96,"disabled button has distinct text color");
if(mode.startsWith("settings")||mode.equals("upload-settings")||mode.equals("pair-settings")){
selectTab(2);boolean upload=mode.equals("upload-settings"),pair=mode.equals("pair-settings");showDetail(pair?"配对与设备":upload?"集中上传与离线暂存":"共享模式与采集频率",pair?pairSection:upload?uploadSection:sampleSection);
selectTab(PhoneLayout.MINE);boolean upload=mode.equals("upload-settings"),pair=mode.equals("pair-settings");showDetail(pair?"配对与设备":upload?"集中上传与离线暂存":"共享模式与采集频率",pair?pairSection:upload?uploadSection:sampleSection);
if(upload){cadence.setSelection(uploadIntervals.length-1);}else if(!pair){sampleCadence.setSelection(sampleIntervals.length-1);}
detailDialog.getWindow().setLayout(style.dp(mode.equals("settings-narrow")||mode.equals("settings-large")?320:390),style.dp(720));previewRoot=detailDialog.getWindow().getDecorView();
check(pair||((upload?cadence:sampleCadence).getAdapter() instanceof PhoneStyle.FormAdapter),"native Bootstrap select adapter installed");
@@ -63,5 +63,5 @@ public class PhonePreviewActivity extends LocationActivity {
void exerciseHistory(){
new Handler().postDelayed(()->{check(voice.nextBefore==12,"history initial page");voice.page().chat.older.performClick();new Handler().postDelayed(()->{check(voice.historyBefore==12&&voice.nextBefore==0,"older page loaded");check(!voice.page().chat.older.isEnabled(),"end of history disables older");voice.page().chat.latest.performClick();new Handler().postDelayed(()->{check(voice.historyBefore==0&&voice.nextBefore==12,"return to latest page");check(!voice.enabled,"reading history does not enable reception");save();},250);},250);},250);
}
void save(){previewRoot.postDelayed(()->{try{if(detailDialog==null)check(sampleSection.getParent()==settings&&uploadSection.getParent()==settings,"dismissed forms safely returned after queued dialog callbacks");else{EditText field=mode.equals("pair-settings")?code:mode.equals("upload-settings")?customAmount:sampleAmount;check(field.getHeight()>=style.dp(48),"form fields retain accessible touch height");check(field.getWidth()>style.dp(60),"custom amount retains usable width");if(!mode.equals("pair-settings")){LinearLayout period=mode.equals("upload-settings")?customPeriod:samplePeriod;View unit=mode.equals("upload-settings")?customUnit:sampleUnit;check(unit.getBottom()<=period.getHeight(),"unit selector is not clipped by baseline alignment");}}if(phone.tab==1){check(voice.page().chat.messages.getChildCount()==3,"real controller loads chat history");check(voice.nextBefore==12,"older history cursor available");check(voice.page().chat.scroll.getHeight()>=style.dp(90),"chat viewport="+voice.page().chat.scroll.getHeight()+", root="+voice.page().getHeight()+", chat="+voice.page().chat.getHeight()+", compose="+voice.page().compose.getHeight()+", compact="+voice.page().compact);check(voice.page().speak.getHeight()>=style.dp(110),"microphone remains a large target");}android.graphics.Bitmap b=android.graphics.Bitmap.createBitmap(previewRoot.getWidth(),previewRoot.getHeight(),android.graphics.Bitmap.Config.ARGB_8888);previewRoot.draw(new android.graphics.Canvas(b));try(java.io.FileOutputStream f=new java.io.FileOutputStream(new java.io.File(getExternalFilesDir(null),"preview.png"))){b.compress(android.graphics.Bitmap.CompressFormat.PNG,100,f);}b.recycle();try(java.io.FileWriter f=new java.io.FileWriter(new java.io.File(getExternalFilesDir(null),"checks.txt"))){f.write("PASS "+mode+" production navigation, chronological list, focus, chat visibility and settings ownership");}}catch(Exception e){throw new RuntimeException(e);}},600);}
void save(){previewRoot.postDelayed(()->{try{if(detailDialog==null)check(sampleSection.getParent()==settings&&uploadSection.getParent()==settings,"dismissed forms safely returned after queued dialog callbacks");else{EditText field=mode.equals("pair-settings")?code:mode.equals("upload-settings")?customAmount:sampleAmount;check(field.getHeight()>=style.dp(48),"form fields retain accessible touch height");check(field.getWidth()>style.dp(60),"custom amount retains usable width");if(!mode.equals("pair-settings")){LinearLayout period=mode.equals("upload-settings")?customPeriod:samplePeriod;View unit=mode.equals("upload-settings")?customUnit:sampleUnit;check(unit.getBottom()<=period.getHeight(),"unit selector is not clipped by baseline alignment");}}if(phone.tab==PhoneLayout.COMMUNICATION){check(voice.page().chat.messages.getChildCount()==3,"real controller loads chat history");check(voice.nextBefore==12,"older history cursor available");check(voice.page().chat.scroll.getHeight()>=style.dp(90),"chat viewport="+voice.page().chat.scroll.getHeight()+", root="+voice.page().getHeight()+", chat="+voice.page().chat.getHeight()+", compose="+voice.page().compose.getHeight()+", compact="+voice.page().compact);check(voice.page().speak.getHeight()>=style.dp(110),"microphone remains a large target");}android.graphics.Bitmap b=android.graphics.Bitmap.createBitmap(previewRoot.getWidth(),previewRoot.getHeight(),android.graphics.Bitmap.Config.ARGB_8888);previewRoot.draw(new android.graphics.Canvas(b));try(java.io.FileOutputStream f=new java.io.FileOutputStream(new java.io.File(getExternalFilesDir(null),"preview.png"))){b.compress(android.graphics.Bitmap.CompressFormat.PNG,100,f);}b.recycle();try(java.io.FileWriter f=new java.io.FileWriter(new java.io.File(getExternalFilesDir(null),"checks.txt"))){f.write("PASS "+mode+" production navigation, chronological list, focus, chat visibility and settings ownership");}}catch(Exception e){throw new RuntimeException(e);}},600);}
}
@@ -0,0 +1,14 @@
param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools')
$ErrorActionPreference='Stop'
$source=Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$stage=Join-Path $env:TEMP ('ZhaoPhoneModel-'+[guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $stage | Out-Null
$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1'
$files=@('PhonePowerModel','PhoneHomeSession','LocationCadence','VoiceGesture','ServerEndpoint') | ForEach-Object {Join-Path $source "src\cn\ucvl\zhaodisplay\$_.java"}
$tests=@('PhonePowerModelTest','LocationCadenceTest','VoiceGestureTest','ServerEndpointTest') | ForEach-Object {Join-Path $source "tests\$_.java"}
& "$jdk\bin\javac.exe" -encoding UTF-8 -d $stage @files @tests
if($LASTEXITCODE){throw 'Phone model Java compilation failed'}
foreach($test in @('PhonePowerModelTest','LocationCadenceTest','VoiceGestureTest','ServerEndpointTest')){
& "$jdk\bin\java.exe" -cp $stage "cn.ucvl.zhaodisplay.$test"
if($LASTEXITCODE){throw "$test failed"}
}