1/*
2Copyright 2016 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package term
18
19import (
20	"time"
21
22	"k8s.io/apimachinery/pkg/util/runtime"
23	"k8s.io/client-go/tools/remotecommand"
24)
25
26// monitorResizeEvents spawns a goroutine that periodically gets the terminal size and tries to send
27// it to the resizeEvents channel if the size has changed. The goroutine stops when the stop channel
28// is closed.
29func monitorResizeEvents(fd uintptr, resizeEvents chan<- remotecommand.TerminalSize, stop chan struct{}) {
30	go func() {
31		defer runtime.HandleCrash()
32
33		size := GetSize(fd)
34		if size == nil {
35			return
36		}
37		lastSize := *size
38
39		for {
40			// see if we need to stop running
41			select {
42			case <-stop:
43				return
44			default:
45			}
46
47			size := GetSize(fd)
48			if size == nil {
49				return
50			}
51
52			if size.Height != lastSize.Height || size.Width != lastSize.Width {
53				lastSize.Height = size.Height
54				lastSize.Width = size.Width
55				resizeEvents <- *size
56			}
57
58			// sleep to avoid hot looping
59			time.Sleep(250 * time.Millisecond)
60		}
61	}()
62}
63