-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevbrowser.go
More file actions
executable file
·264 lines (210 loc) · 6.21 KB
/
devbrowser.go
File metadata and controls
executable file
·264 lines (210 loc) · 6.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package devbrowser
import (
"context"
"errors"
"sync"
"time"
"github.com/tinywasm/devbrowser/chromedp"
)
type Store interface {
Get(key string) (string, error)
Set(key, value string) error
}
type UserInterface interface {
RefreshUI()
ReturnFocus() error
}
type DevBrowser struct {
UI UserInterface
Width int // ej "800" default "1024"
Height int //ej: "600" default "768"
Position string //ej: "1930,0" (when you have second monitor) default: "0,0"
Headless bool // true para modo headless (sin UI), false muestra el navegador
AutoStart bool // true if browser should auto-open on startup
MonitorWidth int // Detected monitor availability width
MonitorHeight int // Detected monitor availability height
SizeConfigured bool // Track if size was loaded from storage
ViewportMode string // Current emulation mode ("mobile", "tablet", "desktop", "off", "")
FirstCall bool // Internal flag to track if OpenBrowser was called for the first time
OpenedOnce bool // Internal flag to track if browser was actually opened at least once
LastPort string
LastHttps bool
IsOpenFlag bool // Indica si el navegador está abierto
DB Store // Key-value store para configuración y estado
// chromedp fields
Ctx context.Context
Cancel context.CancelFunc
ReadyChan chan bool
ErrChan chan error
ExitChan chan bool
Log func(message ...any) // For logging output (Loggable interface)
// Console log capture
ConsoleLogs []string
LogsMutex sync.Mutex
// Network log capture
NetworkLogs []NetworkLogEntry
NetworkMutex sync.Mutex
// JS error capture
JsErrors []JSError
ErrorsMutex sync.Mutex
// Operation busy flag (atomic) to prevent race conditions and UI blocking
// 0 = idle, 1 = busy
Busy int32
TestMode bool // Skip opening browser in tests
// Cache configuration
CacheEnabled bool // Disabled by default for development
Mu sync.Mutex
}
// Option configures the DevBrowser
type Option func(*DevBrowser)
// WithCache configures whether the browser cache is enabled
func WithCache(enabled bool) Option {
return func(b *DevBrowser) {
b.CacheEnabled = enabled
}
}
type JSError struct {
Message string
Source string // File/URL where error occurred
LineNumber int
ColumnNumber int
StackTrace string
Timestamp time.Time
}
type NetworkLogEntry struct {
URL string
Method string
Status int
Type string // xhr, fetch, document, script, image, etc.
Duration int64 // milliseconds
Failed bool
ErrorText string
}
/*
devbrowser.New creates a new DevBrowser instance.
type serverConfig interface {
GetServerPort() string
}
type userInterface interface {
RefreshUI()
ReturnFocus() error
}
example : New(userInterface, st, exitChan, WithCache(true))
*/
func New(ui UserInterface, st Store, exitChan chan bool, opts ...Option) *DevBrowser {
// Initialize clipboard for cross-platform support
// err := clipboard.Init()
// if err != nil {
// // Can't log yet, no logger injected
// }
browser := &DevBrowser{
UI: ui,
DB: st,
Width: 1024, // Default width
Height: 768, // Default height
Position: "0,0",
FirstCall: true,
ReadyChan: make(chan bool),
ErrChan: make(chan error),
ExitChan: exitChan,
CacheEnabled: false, // Default: Cache disabled for development
}
// Apply options
for _, opt := range opts {
opt(browser)
}
// Load all configuration from store
browser.LoadConfig()
//id := atomic.AddInt32(&instanceCounter, 1)
// Logger not set yet, so we can't log this via b.Logger consistently
// But let's try just in case it's injected early or for future ref inspection
// We'll use fmt temporarily for this one-time struct init check if needed,
// but user dislikes fmt. Let's rely on AutoStart logs primarily.
// If we really need New log, we might need fmt. But user said no fmt.
// We'll skip logging in New for now unless critical, but we'll keep the counter.
// actually, let's just use fmt for the New call since it is before logger init usually
//fmt.Printf("DEBUG: DevBrowser New Instance #%d created\n", id)
return browser
}
func (h *DevBrowser) BrowserStartUrlChanged(fieldName string, oldValue, newValue string) error {
if !h.IsOpenFlag {
return nil
}
return h.RestartBrowser()
}
func (h *DevBrowser) RestartBrowser() error {
this := errors.New("RestartBrowser")
err := h.CloseBrowser()
if err != nil {
return errors.Join(this, err)
}
h.OpenBrowser(h.LastPort, h.LastHttps)
return nil
}
func (b *DevBrowser) NavigateToURL(url string) error {
if b.Ctx == nil {
return errors.New("context not initialized")
}
if err := chromedp.Run(b.Ctx, chromedp.Navigate(url)); err != nil {
return err
}
return nil
}
func (b *DevBrowser) Reload() error {
if b.Ctx != nil && b.IsOpenFlag {
b.Logger("Reload")
if err := chromedp.Run(b.Ctx, chromedp.Reload()); err != nil {
return errors.New("Reload " + err.Error())
}
}
return nil
}
func (b *DevBrowser) SetLog(f func(message ...any)) {
b.Log = f
}
func (b *DevBrowser) GetLog() func(message ...any) {
return b.Log
}
func (b *DevBrowser) Logger(messages ...any) {
if b.Log != nil {
b.Log(messages...)
}
}
// SetHeadless configura si el navegador debe ejecutarse en modo headless (sin UI).
// Por defecto es false (muestra la ventana del navegador).
// Debe llamarse antes de OpenBrowser().
func (b *DevBrowser) SetHeadless(headless bool) {
b.Headless = headless
}
func (b *DevBrowser) SetTestMode(testMode bool) {
b.TestMode = testMode
}
// monitorBrowserClose monitors the browser context and updates state when browser is closed manually
func (b *DevBrowser) monitorBrowserClose() {
b.Mu.Lock()
ctx := b.Ctx
b.Mu.Unlock()
if ctx == nil {
return
}
// Wait for context to be done (browser closed)
<-ctx.Done()
b.Mu.Lock()
defer b.Mu.Unlock()
// Only handle if browser was marked as open (manual close by user)
if b.IsOpenFlag {
b.Logger("Browser closed by user")
b.IsOpenFlag = false
b.Ctx = nil
b.Cancel = nil
if b.UI != nil {
b.UI.RefreshUI()
}
}
}
func (b *DevBrowser) IsOpen() bool {
return b.IsOpenFlag
}
func (b *DevBrowser) InitializeConsoleCapture() error {
return b.initializeConsoleCapture()
}