File: main.bs

package info (click to toggle)
storm-lang 0.7.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 51,836 kB
  • sloc: ansic: 261,420; cpp: 138,870; sh: 14,877; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (649 lines) | stat: -rw-r--r-- 16,492 bytes parent folder | download | duplicates (2)
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use ui;
use layout;
use graphics;
use core:geometry;
use core:io;
use progvis:net;
use progvis:program;
use lang:bs:macro;

/**
 * Examples directory.
 */
Url? examplesDir() on Ui {
	var x = parsePath("/usr/share/doc/progvis-examples/examples/");
	if (x.exists())
		return x;
	null;
}

/**
 * Main window.
 */
class MainWin extends Frame {
	private MainPainter painter;

	// Currently open file(s).
	private Url[] currentFiles;

	// Current behavior.
	private Behavior behavior;

	// Host to connect to when going online.
	private Str onlineUrl;

	// Current client connection, if any.
	private Client? client;

	// The 'online' menu so that we can enable/disable items as we please.
	// The first one is the "sign in" item.
	private PopupMenu onlineMenu;

	// Menu element for selecting the memory model.
	private Menu:Check[] memOptions;

	// Menu element for selecting whether or not to report memory leaks.
	private Menu:Check reportLeaks;

	// Currently selected memory option.
	private Nat selectedMemOption;

	// Settings.
	private Settings settings;

	init() {
		init("Progvis", Size(800, 800)) {
			settings = Settings:load();
			onlineUrl = "storm-lang.org";
			reportLeaks(mnemonic("Report _memory leaks"));
		}

		applySettings();

		PopupMenu fileMenu;
		fileMenu
			<< Menu:Text(mnemonic("_Open program..."), ctrlChord(Key:o), &this.onOpen())
			<< Menu:Text(mnemonic("_Reload program"), KeyChord(Key:r, Modifiers:ctrl + Modifiers:shift), &this.onReload())
			<< Menu:Text(mnemonic("Open in _editor"), ctrlChord(Key:e), &this.onOpenEditor());

		if (examplesDir())
			fileMenu
				<< Menu:Separator()
				<< Menu:Text("Open example...", &this.onOpenExample());

		fileMenu
			<< Menu:Separator()
			<< Menu:Text("Save screenshot...", ctrlChord(Key:s), &this.onSaveScreenshot)
			<< Menu:Separator()
			<< Menu:Text(mnemonic("_Settings..."), &this.onSettings());

		memOptions
			<< Menu:Check(mnemonic("_Disabled"))
			<< Menu:Check(mnemonic("Only _statements"))
			<< Menu:Check(mnemonic("_Full"));

		setMemoryCheck(2);

		PopupMenu memCheck;
		for (x in memOptions) {
			memCheck << x;
			var me = this;
			x.onClick = (Bool v) => me.onMemoryChange(x, v);
		}

		reportLeaks.onClick = &this.setReportLeaks;
		setReportLeaks(true);

		PopupMenu runMenu;
		runMenu
			<< Menu:Text(mnemonic("_Restart program"), ctrlChord(Key:r), &this.onRestart())
			<< Menu:Text(mnemonic("_Spawn new thread"), ctrlChord(Key:n), &this.onSpawnThread())
			<< Menu:Submenu(mnemonic("Report _data races"), memCheck)
			<< reportLeaks
			<< Menu:Separator()
			<< Menu:Text(mnemonic("_Look for errors"), ctrlChord(Key:l), &this.onFindErrors())
			<< Menu:Separator()
			<< Menu:Text(mnemonic("S_top all threads"), ctrlChord(Key:q), &this.onStopAll())
			<< Menu:Text(mnemonic("Start _all threads (slow)"), ctrlChord(Key:a), &this.onRunSlow())
			<< Menu:Text(mnemonic("Start all threads (_fast)"), ctrlChord(Key:f), &this.onRunFast());

		onlineMenu
			<< Menu:Text(mnemonic("_Connect"), &this.connect())
			<< Menu:Text(mnemonic("_Disconnect"), &this.disconnect())
			<< Menu:Text(mnemonic("_Highscores..."), &this.onOnlineStatus())
			<< Menu:Text(mnemonic("_Problems..."), ctrlChord(Key:p), &this.onOnlineProblems())
			<< Menu:Text("Submit problem...", &this.onOnlineSubmit())
			<< Menu:Text("Sign out", &this.logout());

		for (Nat i = 1; i < onlineMenu.count; i++)
			onlineMenu[i].enabled = false;

		PopupMenu helpMenu;
		helpMenu << Menu:Text(mnemonic("_About..."), &this.onAbout());

		MenuBar m;
		m
			<< Menu:Submenu(mnemonic("_File"), fileMenu)
			<< Menu:Submenu(mnemonic("_Run"), runMenu)
			// << Menu:Submenu(mnemonic("_Online"), onlineMenu)
			<< Menu:Submenu(mnemonic("_Help"), helpMenu);

		menu = m;

		painter(painter);
		create();
	}

	// Mostly for testing.
	void open(Url file) {
		open([file]);
	}

	// Called when the frame is closed.
	void close() : override {
		behavior.onDispose();
		painter.cleanup();
		super:close();
	}

	void applySettings() {
		painter.setZoom(settings.zoom);
		painter.repaint();
	}

	// For debug mode.
	assign onlineHost(Str to) {
		onlineUrl = to;
	}

	// Connect in the background.
	public void connect() {
		if (client.empty) {
			painter.showMessage("Connecting...");
			onlineMenu[0].enabled = false;
			(spawn bgConnect()).detach();
		}
	}

	// Function executed in the background to connect.
	private void bgConnect() {
		try {
			Client c = Client:connect(onlineUrl, settings.onlineId);
			this.client = c;

			for (Nat i = 1; i < onlineMenu.count; i++)
				onlineMenu[i].enabled = true;

			// This is only for testing.
			// if (onlineUrl == "localhost") {
			// 	painter.hideMessage();
			// 	onOnlineProblems();
			// 	return;
			// }

			painter.showMessage("Signed in as: ${c.username}");
			sleep(2 s);
		} catch (SignInRedirect redirect) {
			showMessage(this, "Sign in", "You need to sign in before using the online features. Click OK to continue.");
			try {
				core:sys:open(redirect.to);
			} catch (Exception e) {
				print("Trying to open: " + redirect.to.format);
				print(e.toS);
				showMessage(this, "Could not start web browser", "Failed to start a web browser to complete the sign in process. Make sure one is installed and try again.");
			}
			onlineMenu[0].enabled = true;
		} catch (ServerError error) {
			showMessage(this, "Error", "The server returned an error: ${error.message}");
			onlineMenu[0].enabled = true;
		} catch (Exception error) {
			print(error.toS);
			showMessage(this, "Error", "Error connecting. Check that your version of Progvis is up to date.");
			onlineMenu[0].enabled = true;
		}

		painter.hideMessage();
	}

	// For testing, to ensure that we can terminate the server cleanly.
	public void disconnect() {
		if (c = client) {
			c.close();
		}
		client = null;

		for (Nat i = 1; i < onlineMenu.count; i++)
			onlineMenu[i].enabled = false;
		onlineMenu[0].enabled = true;

		// Reset the behavior so that we don't try to use the client anymore.
		updateBehavior(DefaultBehavior(this));
	}

	private void logout() {
		if (c = client) {
			c.query(LogoutRequest());
			disconnect();
		}
	}

	Bool onMouseMove(Point pt) : override {
		painter.mouseMoved(pt);
		true;
	}

	void onMouseEnter() : override {}

	void onMouseLeave() : override {
		painter.mouseLeave();
	}

	Bool onClick(Bool down, Point pt, MouseButton button) {
		painter.mouseClicked(pt, down, button);
		true;
	}

	// Used to transition between behaviors. Typically set through "open", but some behaviors need
	// to switch during a simulation.
	public void updateBehavior(Behavior b) {
		behavior.onDispose();
		behavior = b;
		painter.updateBehavior(b);
		onNewBehavior();
		repaint();
	}

	// Set the default behavior again.
	public void resetBehavior() {
		updateBehavior(DefaultBehavior(this));
	}

	// Called when a new behavior has been set.
	private void onNewBehavior() {
		if (!behavior.allowTrackMemory()) {
			setMemoryCheck(2);
			for (x in memOptions)
				x.enabled = false;
		} else {
			for (i, x in memOptions) {
				x.enabled = true;
			}
		}

		if (!behavior.allowNoLeaks) {
			setReportLeaks(true);
			reportLeaks.enabled = false;
		} else {
			reportLeaks.enabled = true;
		}
	}

	private void onOpen() {
		FilePicker picker = createPicker();
		if (!picker.show(this))
			return;

		open(picker.results);
	}

	private void onOpenExample() {
		unless (folder = examplesDir())
			return;

		FilePicker picker = createPicker().defaultFolder(folder);
		if (!picker.show(this))
			return;

		open(picker.results);
	}

	// Create a file picker.
	private FilePicker createPicker() {
		FileTypes ft("Source code");
		for (k in Program:supportedFiles)
			ft.add("${k}-source", [k]);

		return FilePicker:open(ft).okLabel("Open").multiselect();
	}

	public void onReload() {
		if (currentFiles.empty) {
			showMessage(this, "Error", "You need to open a file before you can reload it.");
		} else if (msg = behavior.allowReload()) {
			showMessage(this, "Error", msg);
		} else {
			try {
				painter.open(currentFiles, behavior);
			} catch (core:lang:CodeError error) {
				CompileErrorDialog dlg(error.messageText, error.pos);
				dlg.show(this);
			} catch (Exception error) {
				// Print the stack trace in the terminal to make it easier to debug.
				print("Error:\n${error}");
				showMessage(this, "Error opening code", "Unable to open the selected files:\n${error.message}");
			}
		}
	}

	public void onOpenEditor() {
		if (currentFiles.empty()) {
			showMessage(this, "No files open", "You have no files open currently.");
		} else {
			openEditor(currentFiles[0]);
		}
	}

	// Open an editor for the specified file.
	public void openEditor(Url file) {
		try {
			settings.open(file);
		} catch (Exception e) {
			showMessage(this, "Failed to launch editor", "Failed to launch the editor: ${e}. Is your configuration correct?");
		}
	}

	private void onOnlineStatus() {
		if (c = client) {
			StatusDlg(c).show(this);
		}
	}

	private void onOnlineProblems() {
		if (c = client) {
			problems:ProblemsDlg dlg(c, settings);
			dlg.show(this);
			if (action = dlg.action) {
				open(action.files, "Solving: " + action.problem.title, action.behavior(this, c));
			}
		}
	}

	private void onOnlineSubmit() {
		unless (c = client)
			return;

		problems:UploadDlg(c).show(this);
	}

	// Get source for the current file.
	public Str currentSource() {
		if (currentFiles.count < 1 | !painter.hasProgram)
			throw InternalError("Failed to acquire source for the current file.");
		if (text = painter.sourceFor(currentFiles[0]))
			return text;
		throw InternalError("Failed to acquire source for the current file.");
	}

	// Get all source code, as files in a memory listing.
	public Url[] allCurrentSource() {
		MemoryProtocol memory;
		Url[] result;
		for (f in currentFiles) {
			if (text = painter.sourceFor(f)) {
				MemOStream out;
				Utf8Output tOut(out);
				tOut.write(text);
				tOut.flush();
				result << memory.put(f.name, out.buffer);
			}
		}
		result;
	}

	private void onSettings() {
		SettingsDlg(settings, &this.applySettings).show(this);
	}

	public void clearClient() {
		client = null;
	}

	public void onRestart() {
		painter.restart();
	}

	private void onSpawnThread() {
		if (error = behavior.allowSpawnThread) {
			showMessage(this, "Error", error);
			return;
		}
		painter.spawnThread();
	}

	private void onMemoryChange(Menu:Check check, Bool value) {
		if (!value) {
			Bool any = false;
			for (i, x in memOptions)
				any |= x.checked;

			if (!any)
				check.checked = true;
			return;
		}

		Nat selected = 0;
		for (i, x in memOptions)
			if (x is check)
				selected = i;

		setMemoryCheck(selected);
	}

	private void setMemoryCheck(Nat item) {
		selectedMemOption = item;

		for (i, x in memOptions)
			memOptions[i].checked = i == item;

		var v = if (item == 0) {
			data:MemoryChecks:sequential;
		} else if (item == 1) {
			data:MemoryChecks:statements;
		} else {
			data:MemoryChecks:barriers;
		};

		painter.checkMemory(v);
	}

	private void setReportLeaks(Bool enable) {
		if (reportLeaks.checked != enable)
			reportLeaks.checked = enable;

		painter.checkLeaks(enable);
	}

	private void onFindErrors() {
		if (msg = behavior.allowModelCheck) {
			showMessage(this, "Can not check for errors", msg);
			return;
		}

		// Note: 'allCurrentSource' picks the current version of the source, even if changed in the file system.
		Url[] source = allCurrentSource();
		if (source.empty) {
			showMessage(this, "No files open", "You have no files open currently.");
		} else if (result = check:findErrorsUi(this, source, settings.checks)) {
			onRestart();
			updateBehavior(ReplayBehavior(this, result.sequence));
		}
	}

	private void onStopAll() {
		painter.stopThreads();
	}

	private void onRunSlow() {
		painter.resumeThreads(1 s);
	}

	private void onRunFast() {
		painter.resumeThreads(500 ms);
	}

	private void onAbout() {
		var license = named{PROGVIS};
		var version = named{PROGVIS_VERSION};
		showLicenseDialog(this, ProgramInfo("Progvis", "Filip Strömbäck", version.version, license));
	}

	// Apply an action as if the user clicked something. The "step" received here is the same format
	// that the Behavior class receives in its "onUserAction".
	public Bool applyAction(Str step) {
		painter.applyAction(step);
	}

	// Open one or more files, shows nice messages on error.
	void open(Url[] files) {
		open(files, join(files, ", ", (x) => x.name).toS, DefaultBehavior(this));
	}

	private void open(Url[] files, Str title, Behavior behavior) {
		currentFiles = files;
		this.text = "Progvis - " + title;

		// Set it to default first, so that in case of failure we will behave as "normal".
		this.behavior.onDispose();
		this.behavior = DefaultBehavior(this);
		onNewBehavior();

		try {
			painter.cleanup();
			painter.open(files, behavior);
			this.behavior = behavior;
			onNewBehavior();
		} catch (core:lang:CodeError error) {
			CompileErrorDialog dlg(error.messageText, error.pos);
			dlg.show(this);
		} catch (Exception error) {
			// Print the stack trace in the terminal to make it easier to debug.
			print("Error:\n${error}");
			showMessage(this, "Error opening code", "Unable to open the selected files:\n${error.message}");
		}
	}

	// Called when an error is triggered from a program.
	private void onError(Nat threadId, Exception e) {
		showMessage(this, "Thread ${threadId} crashed", "Thread ${threadId} crashed with the following message:\n${e.message}");
	}

	// Called when a concurrency error is encountered.
	private void onConcurrencyError(Str[] messages) {
		StrBuf msg;
		msg << "Concurrency issues were encountered:\n";
		for (m in messages)
			msg << m << "\n";
		showMessage(this, "Concurrency issues", msg.toS);
	}

	// Save screenshot.
	private void onSaveScreenshot() {
		var sc = settings.screenshot;
		Url file = if (dir = sc.output) {
			Nat suffix = 0;
			Url file = dir;
			do {
				file = dir / "progvis_${suffix,f03}.png";
			} while (file.exists) {
				suffix++;
			}
			file;
		} else {
			FileTypes ft("Image files");
			for (fmt in supportedImageFormats)
				ft.add(fmt.name, fmt.extensions);
			FilePicker p = FilePicker:save(ft, null);
			if (!p.show(this))
				return;

			p.results[0];
		};

		try {
			if (sc.width == 0 | sc.height == 0) {
				painter.saveScreenshot(file, pos.size, sc.customScale);
			} else {
				painter.saveScreenshot(file, Size(sc.width.float, sc.height.float), sc.customScale);
			}
		} catch (Exception e) {
			showMessage(this, "Failed to save screenshot", e.message);
		}
	}
}


void main() on Compiler {
	named{progvis}.compile();

	MainWin win;

	{
		Url[] files;
		for (arg in core:argv) {
			Url file = parsePath(arg).makeAbsolute(cwdUrl);
			if (file.exists) {
				files << file;
			} else {
				print("WARNING: ${file} does not refer to a file.");
			}
		}

		if (files.any)
			win.open(files);
	}

	win.waitForClose();
}

void debug() on Compiler {
	// named{progvis}.compile();

	if (url = examplesDir()) {
		// var result = progvis:check:check([url / "test" / "busywait.c"]);
		// print(result.toS);
		// return;

		MainWin win;
		// win.open(url / "assert.c");
		// win.open(url / "atomics.c");
		// win.open(url / "test" / "atomic_stack.c");
		// win.open(url / "pointers" / "string.c");
		// win.open(url / "pointers" / "locals.c");
		// win.open(url / "pointers" / "ptr.c");
		// win.open(url / "concurrency" / "lock_sema.c");
		// win.open(url / "concurrency" / "bank" / "bank_good.c");
		// win.open(url / "test" / "error.c");
		// win.open(url / "test" / "multi_locks.c");
		// win.open(url / "test" / "step_error.c");
		// win.open(url / "test" / "livelock.c");
		// win.open(url / "test" / "alloc_in_nostep.c");
		// win.open(url / "test" / "globals.cpp");
		// win.open(url / "test" / "staticarrays.c");
		// win.open(url / "test" / "sizeof.c");
		// win.open(url / "test" / "complex-leaks.c");
		// win.open(url / "test" / "simple-leaks.c");
		// win.open(url / "test" / "thread_id.c");
		// win.open(url / "test" / "nested_atomics.c");
		// win.open(url / "test" / "restore_globals.c");
		// win.open(url / "test" / "busywait.c");
		win.open(url / "test" / "atomic_busywait.c");
		win.waitForClose();
	}
}

// Debug the online capabilities with a local server.
void debugServer() {
	named{progvis}.compile();

	spawn simpleServer();

	MainWin win;
	win.onlineHost = "localhost";
	sleep(100 ms);
	win.connect();
	win.waitForClose();
	win.disconnect();

	// Wait for the other UThread to realize that we have disconnected.
	sleep(500 ms);
}