void _errorReceived(VideoPlayer player, string message) { using (WindowProvider.of(this.widget.context).getScope()) { this.cancelTimer(); this.setState(() => { this._isFailure = true; this._isLoaded = true; }); } }
void t_Tick() { using (WindowProvider.of(this._context).getScope()) { this.setState(() => { this._lastSecond -= 1; }); if (this._lastSecond < 1) { this.pushCallback(); } } }
static void _handleMethodCall(string method, List <JSONNode> args) { if (GlobalContext.context != null) { using (WindowProvider.of(context: GlobalContext.context).getScope()) { switch (method) { case "OnReceiveQRCode": { string qrCode = args[0]; if (qrCode.StartsWith("http://") || qrCode.StartsWith("https://")) { var uri = new Uri(uriString: qrCode); if (uri.AbsoluteUri.StartsWith("https://connect")) { var token = HttpUtility.ParseQueryString(query: uri.Query).Get("token"); if (token.isNotEmpty()) { var isLoggedIn = StoreProvider.store.getState().loginState.isLoggedIn; if (isLoggedIn) { checkToken(token: token); } else { qrCodeToken = token; StoreProvider.store.dispatcher.dispatch(new MainNavigatorPushToAction { routeName = MainNavigatorRoutes.Login }); } } else { CustomDialogUtils.showToast("暂不支持该二维码类型", Icons.sentiment_dissatisfied); } } else { CustomDialogUtils.showToast("暂不支持该二维码类型", Icons.sentiment_dissatisfied); } } else if (!qrCode.Equals("pop")) { CustomDialogUtils.showToast("暂不支持该二维码类型", Icons.sentiment_dissatisfied); } StatusBarManager.hideStatusBar(false); StatusBarManager.statusBarStyle(isLight: StoreProvider.store.getState().loginState .isLoggedIn); removeListener(); } break; } } } }
static void _handleMethodCall(string method, List <JSONNode> args) { if (context != null) { using (WindowProvider.of(context).getScope()) { switch (method) { case "OnOpenNotification": { //点击应用通知栏 var node = args[0]; var dict = JSON.Parse(node); var type = dict["type"]; var subType = dict["subtype"]; var id = dict["id"]; if (type == "project") { if (subType == "article") { StoreProvider.store.dispatcher.dispatch( new MainNavigatorPushToArticleDetailAction { articleId = id }); } } else if (type == "event") { var eventType = EventType.offline; if (subType == "online") { eventType = EventType.online; } StoreProvider.store.dispatcher.dispatch( new MainNavigatorPushToEventDetailAction { eventId = id, eventType = eventType }); } } break; case "OnReceiveNotification": { //接收到推送 EventBus.publish(EventBusConstant.refreshNotifications, new List <object>()); } break; case "OnReceiveMessage": { //接收到应用内消息 } break; } } } }
private void OnPathChanged(string path) { if (!mounted) { return; } using (WindowProvider.of(context).getScope()) { setState(() => _currentLastSegment = LastSegment(path)); } }
/// <summary> /// The initState. /// </summary> public override void initState() { base.initState(); var specifiedChanged = MMMServices.Instance.SpecifiedMmdObjects.ObserveCountChanged(true); var folderChanged = MMMServices.Instance.WatchedFolders.ObserveCountChanged(true); observeCountChanged = specifiedChanged.Merge(folderChanged) .Subscribe(x => { using (WindowProvider.of(GameObject.Find("Panel")).getScope()) { setState(() => { // Add specified pmx chip var specified = MMMServices.Instance.SpecifiedMmdObjects .Select(f => new CustomElevation( child: new Chip( label: new Text(f.FileName), deleteIcon: new Icon(Icons.delete), onDeleted: () => MMMServices.Instance.SpecifiedMmdObjects.Remove(f), backgroundColor: Colors.white, deleteIconColor: Colors.red, shape: new RoundedRectangleBorder(borderRadius: BorderRadius.circular(17)) ), height: 30, padding: EdgeInsets.symmetric(horizontal: 6) )) .ToList(); // Add folder chip var folders = MMMServices.Instance.WatchedFolders .Select(f => new CustomElevation( child: new Chip( label: new Text(f.Split('\\').Last()), deleteIcon: new Icon(Icons.delete), onDeleted: () => MMMServices.Instance.WatchedFolders.Remove(f), backgroundColor: Colors.white, deleteIconColor: Colors.red, shape: new RoundedRectangleBorder(borderRadius: BorderRadius.circular(17)) ), height: 30, padding: EdgeInsets.symmetric(horizontal: 6) )) .ToList(); chips.Clear(); chips.AddRange(specified); chips.AddRange(folders); }); } }); }
void _handleStateChanged(State state) { if (Window.hasInstance) { this._innerStateChanged(state); } else { using (WindowProvider.of(this.context).getScope()) { this._innerStateChanged(state); } } }
public override void initState() { base.initState(); _mmdObject = widget.MMDObject; _mmdObject.PreviewPath.ObserveEveryValueChanged(x => x.Value) .Subscribe(_ => { using (WindowProvider.of(GameObject.Find("Panel")).getScope()) { _mmdObject.PreviewPath = _mmdObject.PreviewPath; } }); }
void OnApplicationQuit() { if (Application.isEditor) { return; } using (WindowProvider.of(GlobalContext.context).getScope()) { if (AnalyticsManager.foucsTime.isNotEmpty()) { AnalyticsManager.AnalyticsActiveTime((DateTime.UtcNow - DateTime.Parse(AnalyticsManager.foucsTime)) .Milliseconds); } } }
private void OnPathChanged(string path) { if (!mounted) { return; } using (WindowProvider.of(context).getScope()) { setState(() => { _overwriteUnknown = false; _currentPath = path; }); } }
private void ShowContextMenu(BuildContext context) { if (!GameObject.Find("Panel").GetComponent <UIClickProperty>().IsMRBClicked) { return; } using (WindowProvider.of(GameObject.Find("Panel")).getScope()) { PopupMenuUtils.showMenu <MenuItem>( context, RelativeRect.fromLTRB(Input.mousePosition.x, Screen.height - Input.mousePosition.y, Screen.width - Input.mousePosition.x, Input.mousePosition.y), new List <PopupMenuEntry <MenuItem> > { new PopupMenuItem <MenuItem>( value: MenuItem.LoadPreview, child: new Text("Load Preview") ) }, initialValue: MenuItem.LoadPreview ).Then(x => { try { var token = (MenuItem)x; switch (token) { case MenuItem.LoadPreview: var builder = GameObject.Find("MMDRenderer") .GetComponent <PreviewBuilder.PreviewBuilder>(); builder.StartRender(_mmdObject); break; default: throw new ArgumentOutOfRangeException(); } } catch { // ignored } }); } }
public void Update() { using (WindowProvider.of(context: GlobalContext.context).getScope()) { lock (this._executionQueue) { while (this._executionQueue.Count > 0) { this._executionQueue.Dequeue().Invoke(); } } var delta = Time.deltaTime; while (this._delayCalls.Count > 0) { var call = this._delayCalls[0]; var delay = call.remainInterval; if (delay > delta) { call.remainInterval -= delta; break; } delta -= call.remainInterval; var callback = call.callback; this._delayCalls.RemoveAt(0); callback?.Invoke(); } if (Application.internetReachability != this.m_InternetState) { this.m_InternetState = Application.internetReachability; //force reconnect if the connection state changes to online if (this.m_InternetState == NetworkReachability.ReachableViaCarrierDataNetwork || this.m_InternetState == NetworkReachability.ReachableViaLocalAreaNetwork) { SocketApi.OnNetworkConnected(); } else { SocketApi.OnNetworkDisconnected(); } } } }
public override Widget build(BuildContext context) { return(new Column( children: new List <Widget>() { new FlatButton(child: new Text("Click To Get Time"), onPressed: () => { UnityWebRequest www = UnityWebRequest.Get("http://worldclockapi.com/api/json/est/now"); var asyncOperation = www.SendWebRequest(); asyncOperation.completed += operation => { var timeData = JsonUtility.FromJson <TimeData>(www.downloadHandler.text); using (WindowProvider.of(this.widget.gameObjOfUIWidgetsPanel).getScope()) { this.setState(() => { this._fileTime = timeData.currentFileTime; }); } }; }), new Text($"current file time: {this._fileTime}") })); }
public void Select(string channelId, bool toDiscover = false) { using (WindowProvider.of(context).getScope()) { MentionPopup.currentState?.StopMention(); Sender.currentState?.Clear(); if (Window.NewMessages.isNotEmpty()) { Window.NewMessages.ForEach(msg => { Window.Messages[msg.channelId].Insert(0, msg); }); Window.NewMessages.Clear(); } IsShowDiscovery = channelId == string.Empty && MediaQuery.of(context).size.width >= 750 || toDiscover; SelectedChannelId = channelId; IsShowChannelInfo = false; ShowingChannelBriefId = null; setState(); } }
static void _handleMethodCall(string method, List <JSONNode> args) { if (GlobalContext.context != null) { using (WindowProvider.of(GlobalContext.context).getScope()) { switch (method) { case "init": { Screen.orientation = ScreenOrientation.AutoRotation; break; } case "popPage": { Screen.orientation = ScreenOrientation.Portrait; break; } } } } }
public override void initState() { base.initState(); var request = UnityWebRequest.Get( widget.Url ); request.SetRequestHeader("Cookie", $"LS={Window.loginSession}"); var asyncOperation = request.SendWebRequest(); asyncOperation.completed += operation => { if (mounted) { using (WindowProvider.of(context).getScope()) { } } }; }
static void _handleMethodCall(string method, List <JSONNode> args) { if (GlobalContext.context != null) { using (WindowProvider.of(GlobalContext.context).getScope()) { switch (method) { case "PopPage": { StoreProvider.store.dispatcher.dispatch(new MainNavigatorPopAction()); break; } case "Share": { EventBus.publish(EventBusConstant.shareAction, null); break; } case "BuyLincese": { Application.OpenURL(Config.unityStoreUrl); break; } case "UpdateLincese": { Application.OpenURL(Config.unityLearnPremiumUrl); break; } case "LandscapeLeft": { Screen.orientation = ScreenOrientation.LandscapeLeft; break; } case "Portrait": { Screen.orientation = ScreenOrientation.Portrait; break; } } } } }
private void Load() { _loading = true; var version = DocApp.of(context).version; var url = $"{Configuration.Instance.cdnPrefix}/{version.unityVersion}/{version.parsedVersion}/manual/json/{widget._title.Replace('-', '_')}.json"; var request = UnityWebRequest.Get(url); var asyncOperation = request.SendWebRequest(); asyncOperation.completed += operation => { if (!mounted) { return; } using (WindowProvider.of(context).getScope()) { if (request.responseCode == 404) { DocApp.of(context).ForceUnknown(); } else { var content = DownloadHandlerBuffer.GetContent(request); var model = JsonConvert.DeserializeObject <ManualModel>(content); setState(() => { _tokens = model.tokens; _prevLink = model.prev; _nextLink = model.next; _breadcrumbs = model.breadcrumbs; _imageMetas = model.imageMetas; _loading = false; }); } } }; }
void _handleMethodCall(string method, List <JSONNode> args) { using (WindowProvider.of(this.context).getScope()) { switch (method) { case "callback": { var node = args[0]; var dict = JSON.Parse(node); var type = dict["type"]; if (type == "code") { var code = dict["code"]; if (this.codeCallBack != null) { this.codeCallBack(code); } } } break; } } }
private void OnSelectionChanged() { var g = Selection.activeGameObject; var gs = g?.GetComponent <SkinnedMeshRenderer>(); var gsc = g?.GetComponentInChildren <SkinnedMeshRenderer>(); var gm = g?.GetComponent <MeshRenderer>(); var gmc = g?.GetComponentInChildren <MeshRenderer>(); using (WindowProvider.of(context).getScope()) { setState(() => { if (gs == gsc == gm == gmc == null) { Current = null; } else { Current = g; } }); } }
void _setScreenOrientation() { this.cancelTimer(); using (WindowProvider.of(this.widget.context).getScope()) { if (!this._isFullScreen) { VideoPlayerManager.instance.lockPortrait = true; Screen.orientation = ScreenOrientation.LandscapeLeft; this._isFullScreen = true; } else { VideoPlayerManager.instance.lockLandscape = true; Screen.orientation = ScreenOrientation.Portrait; this._isFullScreen = false; } if (this.widget.fullScreenCallback != null) { this.widget.fullScreenCallback(this._isFullScreen); } } }
void _handleMethodCall(string method, List <JSONNode> args) { using (WindowProvider.of(context: this.context).getScope()) { switch (method) { case "callback": { if (args.isEmpty()) { return; } var node = args[0]; var dict = JSON.Parse(aJSON: node); var type = dict["type"]; if (type == "code") { var code = dict["code"]; if (this.codeCallBack != null) { this.codeCallBack(obj: code); } } } break; case "openUrl": { if (args.isEmpty()) { return; } openUrl(args.first()); } break; } } }
public override void initState() { base.initState(); if (!Application.isEditor) { this._webViewObject = WebViewManager.instance.getWebView(); this._webViewObject.Init( ua: "", enableWKWebView: true, transparent: true, started: start => { using (WindowProvider.of(this.context).getScope()) { this.startProgress(); } }, ld: ld => { using (WindowProvider.of(this.context).getScope()) { this.stopProgress(); } } ); this._webViewObject.LoadURL(this.widget.url); this._webViewObject.ClearCookies(); if (HttpManager.getCookie().isNotEmpty()) { #if UNITY_IOS this._webViewObject.AddCustomHeader("Cookie", HttpManager.getCookie()); #endif } this._webViewObject.SetVisibility(true); } this._progress = 0; this._onClose = false; }
public override void initState() { base.initState(); _currentLastSegment = LastSegment(ObservableUtil.currentPath.value); ObservableUtil.currentPath.OnChanged += OnPathChanged; var version = DocApp.of(context).version; var request = UnityWebRequest.Get($"{Configuration.Instance.cdnPrefix}/{version.unityVersion}/{version.parsedVersion}/{widget._type.TocFileName()}"); var asyncOperation = request.SendWebRequest(); asyncOperation.completed += operation => { if (!mounted) { return; } var content = DownloadHandlerBuffer.GetContent(request); using (WindowProvider.of(context).getScope()) { setState(() => _menu = JsonConvert.DeserializeObject <Models.Json.Menu>(content)); } }; }
private void DoSearch() { _keyword = Uri.UnescapeDataString(widget._keyword); _page = widget._page; _filterType = widget._filterType; if (_keyword == string.Empty) { return; } _searching = true; var url = $"{Configuration.Instance.apiHost}/api/documentation/search/v/2018.1/t/{_filterType}?query={_keyword}&page={_page}&pageSize=10"; var request = UnityWebRequest.Get(url); var asyncOperation = request.SendWebRequest(); asyncOperation.completed += operation => { if (!mounted) { return; } using (WindowProvider.of(context).getScope()) { var content = DownloadHandlerBuffer.GetContent(request); var results = SearchResults.FromJson(JsonValue.Parse(content)); setState(() => { _results = results; _searching = false; }); } }; }
static void _handleMethodCall(string method, List <JSONNode> args) { if (GlobalContext.context != null) { using (WindowProvider.of(GlobalContext.context).getScope()) { switch (method) { case "OnOpenNotification": { if (args.isEmpty()) { return; } //点击应用通知栏 var node = args.first(); var dict = JSON.Parse(node); var type = dict["type"]; var subType = dict["subtype"]; string id = dict["id"] ?? ""; if (id.isEmpty()) { id = dict["channelId"] ?? ""; } AnalyticsManager.AnalyticsWakeApp("OnOpenNotification", id, type, subType); AnalyticsManager.ClickNotification(type, subType, id); pushPage(type, subType, id, true); break; } case "OnReceiveNotification": { //接收到推送 if (args.isEmpty()) { return; } var node = args.first(); var dict = JSON.Parse(node); var type = dict["type"] ?? ""; if (type != "messenger") { EventBus.publish(EventBusConstant.newNotifications, new List <object>()); } break; } case "OnReceiveMessage": { //接收到应用内消息 break; } case "OnOpenUrl": { if (args.isEmpty()) { return; } AnalyticsManager.AnalyticsWakeApp("OnOpenUrl", args.first()); openUrl(args.first()); break; } case "OnOpenUniversalLinks": { if (args.isEmpty()) { return; } AnalyticsManager.AnalyticsWakeApp("OnOpenUniversalLinks", args.first()); openUniversalLink(args.first()); break; } case "CompletedCallback": { if (args.isEmpty()) { return; } var node = args.first(); var dict = JSON.Parse(node); var isPush = (bool)dict["push"]; if (isPush) { StoreProvider.store.dispatcher.dispatch(new MainNavigatorReplaceToAction { routeName = MainNavigatorRoutes.Main }); } else { if (SplashManager.isExistSplash()) { StoreProvider.store.dispatcher.dispatch(new MainNavigatorPushReplaceSplashAction()); } else { StoreProvider.store.dispatcher.dispatch(new MainNavigatorPushReplaceMainAction()); } } break; } case "SaveImageSuccess": { CustomDialogUtils.showToast("保存成功", iconData: Icons.sentiment_satisfied); break; } case "SaveImageError": { CustomDialogUtils.showToast("保存失败,请检查权限", iconData: Icons.sentiment_dissatisfied); break; } } } } }
VideoPlayer _videoPlayer(string url) { var player = VideoPlayerManager.instance.getPlayer(); var audioSource = VideoPlayerManager.instance.getAudioSource(); player.url = url; player.renderMode = VideoRenderMode.RenderTexture; player.source = VideoSource.Url; player.audioOutputMode = VideoAudioOutputMode.AudioSource; player.SetTargetAudioSource(0, audioSource); player.playOnAwake = false; player.IsAudioTrackEnabled(0); player.targetTexture = this._texture; player.isLooping = false; player.sendFrameReadyEvents = true; player.aspectRatio = VideoAspectRatio.Stretch; player.prepareCompleted += this.prepareCompleted; player.frameReady += (source, frameIndex) => { using (WindowProvider.of(this.widget.context).getScope()) { _pauseAudioSession(); Texture.textureFrameAvailable(); if (this._relative * source.frameCount < frameIndex || frameIndex == 0) { this._isLoaded = true; if (!this._isHiddenBar && !this._isReadyHiddenBar) { this._isReadyHiddenBar = true; this._hiddenBar(); } } this._relative = (float)frameIndex / source.frameCount; this._isFailure = false; if (this._playState == PlayState.play) { this._player.Play(); } if (frameIndex == 0) { Promise.Delayed(TimeSpan.FromMilliseconds(200)).Then(() => { if (this.mounted) { this.setState(() => {}); } }); } else { this.setState(() => { }); } } }; player.loopPointReached += _player => { using (WindowProvider.of(this.widget.context).getScope()) { this._relative = 0.0f; this._playState = PlayState.stop; _player.Stop(); _player.frame = 0; this.cancelTimer(); this._isHiddenBar = false; this._isReadyHiddenBar = false; this.setState(() => { }); } }; player.errorReceived += this._errorReceived; player.Prepare(); player.Pause(); return(player); }
static void _handleMethodCall(string method, List <JSONNode> args) { if (GlobalContext.context != null) { using (WindowProvider.of(GlobalContext.context).getScope()) { switch (method) { case "OnOpenNotification": { if (args.isEmpty()) { return; } //点击应用通知栏 var node = args.first(); var dict = JSON.Parse(node); var type = dict["type"]; var subType = dict["subtype"]; string id = dict["id"] ?? ""; if (id.isEmpty()) { id = dict["channelId"] ?? ""; } AnalyticsManager.AnalyticsWakeApp("OnOpenNotification", id, type, subType); AnalyticsManager.ClickNotification(type, subType, id); pushPage(type, subType, id, true); break; } case "OnReceiveNotification": { //接收到推送 if (args.isEmpty()) { return; } var node = args.first(); var dict = JSON.Parse(node); var type = dict["type"] ?? ""; if (type != "messenger") { StoreProvider.store.dispatcher.dispatch(new UpdateNewNotificationAction { notification = "" }); } var id = dict["id"] ?? ""; if (CTemporaryValue.currentPageModelId.isEmpty() || id != CTemporaryValue.currentPageModelId) { playMessageSound(); } break; } case "OnReceiveMessage": { //接收到应用内消息 break; } case "OnOpenUrl": { if (args.isEmpty()) { return; } AnalyticsManager.AnalyticsWakeApp("OnOpenUrl", args.first()); openUrlScheme(args.first()); break; } case "OnOpenUniversalLinks": { if (args.isEmpty()) { return; } AnalyticsManager.AnalyticsWakeApp("OnOpenUniversalLinks", args.first()); openUniversalLink(args.first()); break; } case "CompletedCallback": { if (args.isEmpty()) { return; } clearIconBadge(); var node = args.first(); var dict = JSON.Parse(node); var isPush = (bool)dict["push"]; if (isPush) { StoreProvider.store.dispatcher.dispatch(new MainNavigatorReplaceToAction { routeName = MainNavigatorRoutes.Main }); } else { if (VersionManager.needForceUpdate()) { SplashManager.hiddenAndroidSpalsh(); } else { if (SplashManager.isExistSplash()) { SplashManager.hiddenAndroidSpalsh(); StoreProvider.store.dispatcher.dispatch( new MainNavigatorPushReplaceSplashAction()); } else { StoreProvider.store.dispatcher.dispatch( new MainNavigatorPushReplaceMainAction()); } } } break; } case "RegisterToken": { if (args.isEmpty()) { return; } var node = args.first(); var dict = JSON.Parse(node); var token = (string)dict["token"]; hmsToken = token; registerHmsToken(StoreProvider.store.getState().loginState.isLoggedIn ? StoreProvider.store.getState().loginState.loginInfo.userId : ""); break; } case "SaveImageSuccess": { CustomDialogUtils.showToast("保存成功", iconData: Icons.sentiment_satisfied); break; } case "SaveImageError": { CustomDialogUtils.showToast("保存失败,请检查权限", iconData: Icons.sentiment_dissatisfied); break; } } } } }
public override Widget build(BuildContext context) { var screenWidth = MediaQuery.of(context).size.width; var windowChildren = new List <Widget> { new Scroller( child: ListView.builder( controller: m_ScrollController, reverse: true, itemCount: m_HasMoreOld ? widget.messages[widget.channel.id].Count + 1 : widget.messages[widget.channel.id].Count, itemBuilder: (ctx, index) => { if (!m_Initialized) { return(new Container()); } if (index == widget.messages[widget.channel.id].Count) { return(new LoadTrigger( () => { var lastMessageId = widget.messages[widget.channel.id].last().id; Get( $"/api/connectapp/v1/channels/{widget.channel.id}/messages?before={lastMessageId}", (GetMessagesResponse getMessagesResponse) => { if (mounted) { using (WindowProvider.of(context) .getScope()) { setState(() => { widget.messages[widget.channel.id] .AddRange( getMessagesResponse.items .Where( item => item.id != lastMessageId ) ); m_MsgsUnreads = 0; m_HasMoreUnreads = true; if (m_PreviousLastMsgId == null) { m_HasMoreUnreads = false; } else { foreach (var m in widget.messages[widget.channel.id]) { if (string.Compare(m.id, m_PreviousLastMsgId) > 0) { ++m_MsgsUnreads; } else { m_HasMoreUnreads = false; break; } } } m_HasMoreOld = getMessagesResponse.hasMore; }); } } }); } )); } var currentMessage = widget.messages[widget.channel.id][index]; var msgTime = ExtractTimeFromSnowflakeId(currentMessage.id.IsNullOrEmpty() ? currentMessage.nonce : currentMessage.id); bool showTime; var isNew = false; if (index == widget.messages[widget.channel.id].Count - 1) { showTime = true; } else { var nextMessage = widget.messages[widget.channel.id][index + 1]; showTime = msgTime - ExtractTimeFromSnowflakeId( nextMessage.id.IsNullOrEmpty() ? nextMessage.nonce : nextMessage.id) > TimeSpan.FromMinutes(5); if (nextMessage.id != null && nextMessage.id == m_PreviousLastMsgId) { isNew = true; } } Action onBuild = null; if (currentMessage.id == m_PreviousLastMsgId) { onBuild = () => { SchedulerBinding.instance.addPostFrameCallback(value => { setState(() => { m_MsgsUnreads = 0; m_HasMoreUnreads = false; }); }); }; } return(new Message( widget.messages[widget.channel.id][index], widget.users, showTime, m_PreviousLastMsgId != widget.channel.lastMessage.id && isNew, msgTime, onBuild )); } ) ), }; if (Window.reconnecting) { windowChildren.Add( new Positioned( left: 0, top: 0, right: 0, child: new Container( color: new Color(0xfffde1df), height: 48, alignment: Alignment.center, child: new Text( "网络未连接,正在连接中", style: new TextStyle( fontSize: 16, color: new Color(0xfff44336), fontFamily: "PingFang" ) ) ) ) ); } var newMsgsCount = Window.NewMessages.Count(msg => msg.author.id != Window.currentUserId); if (newMsgsCount != 0) { windowChildren.Add( new Positioned( bottom: 24, child: new GestureDetector( onTap: () => { Window.NewMessages.ForEach(msg => { Window.Messages[msg.channelId].Insert(0, msg); }); Window.NewMessages.Clear(); setState(); m_ScrollController.animateTo( 0, new TimeSpan(0, 0, 0, 0, 480), Curves.easeInOut ); }, child: new Container( height: 40, padding: EdgeInsets.symmetric(horizontal: 16), decoration: new BoxDecoration( borderRadius: BorderRadius.all(20), boxShadow: new List <BoxShadow> { new BoxShadow( offset: new Offset(0, 1), blurRadius: 6, color: new Color(0x19000000) ), }, color: new Color(0xffffffff) ), child: new Row( mainAxisAlignment: MainAxisAlignment.center, children: new List <Widget> { new Text( $"{newMsgsCount}条新消息未读", style: new TextStyle( color: new Color(0xff2196f3), fontSize: 14, fontFamily: "PingFang" ) ), } ) ) ) ) ); } if (m_MsgsUnreads > 0) { var text = $"{m_MsgsUnreads}"; if (m_HasMoreUnreads) { text += "+"; } text += "条新消息"; windowChildren.Add( new Positioned( top: 24, child: new GestureDetector( onTap: () => { var totalHeight = 0.0f; for (var index = 0; index < widget.messages[widget.channel.id].Count; ++index) { var message = widget.messages[widget.channel.id][index]; if (string.Compare(message.id, m_PreviousLastMsgId) > 0) { var showTime = true; var msgTime = ExtractTimeFromSnowflakeId(message.id.IsNullOrEmpty() ? message.nonce : message.id); if (index != widget.messages[widget.channel.id].Count - 1) { var nextMessage = widget.messages[widget.channel.id][index + 1]; showTime = msgTime - ExtractTimeFromSnowflakeId( nextMessage.id.IsNullOrEmpty() ? nextMessage.nonce : nextMessage.id) > TimeSpan.FromMinutes(5); } var layoutWidth = screenWidth * 0.7f; if (screenWidth >= 750) { layoutWidth -= 286.5f; } else { layoutWidth -= 24f; } totalHeight += CalculateMessageHeight( message, showTime, layoutWidth ); } else { break; } } if (m_HasMoreUnreads) { totalHeight += 40; } else { totalHeight += 36; } m_ScrollController.animateTo( totalHeight - MediaQuery.of(context).size.height + 184, new TimeSpan(0, 0, 0, 0, 480), Curves.easeInOut ); if (!m_HasMoreUnreads) { setState(() => { m_MsgsUnreads = 0; m_HasMoreUnreads = false; }); } }, child: new Container( height: 40, padding: EdgeInsets.symmetric(horizontal: 16), decoration: new BoxDecoration( borderRadius: BorderRadius.all(20), boxShadow: new List <BoxShadow> { new BoxShadow( offset: new Offset(0, 1), blurRadius: 6, color: new Color(0x19000000) ), }, color: new Color(0xffffffff) ), child: new Row( mainAxisAlignment: MainAxisAlignment.center, children: new List <Widget> { new Text( text, style: new TextStyle( color: new Color(0xff2196f3), fontSize: 14, fontFamily: "PingFang" ) ), new Container( margin: EdgeInsets.only(left: 4), child: Transform.rotate( child: new Icon( IconFont.IconFontArrowUp, size: 24, color: new Color(0xff2196f3) ) ) ) } ) ) ) ) ); } var rootState = HomePage.of(context); var children = new List <Widget> { new Container( color: new Color(0xffffffff), child: new Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: new List <Widget> { new ChattingWindowHeader( widget.channel, () => { if (screenWidth < 750) { m_AnimationController.reverse(); } else { HomePage.of(context).Select(string.Empty); } }), new Expanded( child: new Stack( alignment: Alignment.center, children: windowChildren ) ), new Sender( m_SenderFocusNode, widget.users), } ) ), }; if (!m_Initialized) { children.Add( new Container( alignment: Alignment.center, child: new Loading(size: 56) ) ); } Widget all = new GestureDetector( onTap: () => { FocusScope.of(context).requestFocus(m_EmptyFocusNode); }, child: new Stack( children: children ) ); if (screenWidth < 750) { all = Transform.translate( offset: new Offset((1 - m_AnimationController.value) * screenWidth, 0), child: all ); } return(all); }
public override void initState() { base.initState(); m_HasMoreOld = true; m_EmptyFocusNode = new FocusNode(); m_SenderFocusNode = new FocusNode(); m_ScrollController = new ScrollController(); m_AnimationController = new AnimationController( vsync: this, duration: new TimeSpan(0, 0, 0, 0, milliseconds: 240) ); m_AnimationController.addListener(() => setState()); m_AnimationController.addStatusListener(AnimationStatusListener); SchedulerBinding.instance.addPostFrameCallback(value => { if (MediaQuery.of(context).size.width < 750) { m_AnimationController.forward(); } }); m_ScrollController.addListener(() => { if (m_ScrollController.offset < 50f && Window.NewMessages.isNotEmpty()) { var message = Window.NewMessages[0]; Window.NewMessages.RemoveAt(0); var showTime = true; if (!widget.messages[message.channelId].isEmpty()) { var preMsg = widget.messages[message.channelId].first(); var preTime = ExtractTimeFromSnowflakeId(preMsg.id ?? preMsg.nonce); var curTime = ExtractTimeFromSnowflakeId(message.id ?? message.nonce); showTime = curTime - preTime > TimeSpan.FromMinutes(5); } var height = CalculateMessageHeight( message, showTime, MediaQuery.of(context).size.width * 0.7f - 286.5f); Window.Messages[message.channelId].Insert(0, message); m_ScrollController.jumpTo(m_ScrollController.offset + height); HomePage.currentState.setState(); } }); if (!widget.messages.ContainsKey(widget.channel.id) || widget.messages[widget.channel.id].isEmpty()) { m_Initialized = false; widget.messages[widget.channel.id] = new List <Models.Message>(); if (widget.pullFlags.ContainsKey(widget.channel.id) && widget.pullFlags[widget.channel.id]) { widget.pullFlags[widget.channel.id] = false; } SchedulerBinding.instance.addPostFrameCallback(value => { Promise.All(new List <IPromise> { Get <GetMembersResponse>( $"/api/connectapp/v1/channels/{widget.channel.id}/members" ).Then(response => { if (!widget.members.ContainsKey(widget.channel.id)) { widget.members[widget.channel.id] = new List <ChannelMember>(); } response.list.ForEach(member => { if (!widget.users.ContainsKey(member.user.id)) { widget.users.Add(member.user.id, member.user); } if (widget.members[widget.channel.id].All(m => m.user.id != member.user.id)) { widget.members[widget.channel.id].Add(member); } }); widget.hasMoreMembers[widget.channel.id] = response.total > widget.members[widget.channel.id].Count; }).Catch(exception => { }), Utils.Get <GetMessagesResponse>( $"/api/connectapp/v1/channels/{widget.channel.id}/messages" ).Then(getMessagesResponse => { if (mounted) { m_HasMoreOld = getMessagesResponse.hasMore; m_Initialized = true; } widget.messages[widget.channel.id] = getMessagesResponse.items; m_HasMoreUnreads = true; if (m_PreviousLastMsgId == null) { m_HasMoreUnreads = false; } else { foreach (var m in widget.messages[widget.channel.id]) { if (string.Compare(m.id, m_PreviousLastMsgId) > 0) { ++m_MsgsUnreads; } else { m_HasMoreUnreads = false; break; } } } }).Catch(exception => { }), }).Then(() => { if (mounted) { using (WindowProvider.of(context).getScope()) { setState(); FocusScope.of(context).requestFocus(m_SenderFocusNode); } } }); }); } else { PullIfNeeded(); m_Initialized = true; m_HasMoreUnreads = true; if (m_PreviousLastMsgId == null) { m_HasMoreUnreads = false; } else { foreach (var m in widget.messages[widget.channel.id]) { if (string.Compare(m.id, m_PreviousLastMsgId) > 0) { ++m_MsgsUnreads; } else { m_HasMoreUnreads = false; break; } } } SchedulerBinding.instance.addPostFrameCallback(value => { using (WindowProvider.of(context).getScope()) { FocusScope.of(context).requestFocus(m_SenderFocusNode); } }); } SchedulerBinding.instance.addPostFrameCallback(value => { var rootState = HomePage.of(context); rootState.Ack(widget.channel.id); }); }