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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
|
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
* Copyright 2011 Pierre Ossman <ossman@cendio.se> for Cendio AB
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <rfb/LogWriter.h>
#include <rfb/CMsgWriter.h>
#include "DesktopWindow.h"
#include "OptionsDialog.h"
#include "i18n.h"
#include "parameters.h"
#include "vncviewer.h"
#include "CConn.h"
#include "Surface.h"
#include "Viewport.h"
#include <FL/Fl.H>
#include <FL/Fl_Image_Surface.H>
#include <FL/Fl_Scrollbar.H>
#include <FL/fl_draw.H>
#include <FL/x.H>
#ifdef WIN32
#include "win32.h"
#endif
#ifdef __APPLE__
#include "cocoa.h"
#endif
#define EDGE_SCROLL_SIZE 32
#define EDGE_SCROLL_SPEED 20
using namespace rfb;
static rfb::LogWriter vlog("DesktopWindow");
DesktopWindow::DesktopWindow(int w, int h, const char *name,
const rfb::PixelFormat& serverPF,
CConn* cc_)
: Fl_Window(w, h), cc(cc_), offscreen(NULL), overlay(NULL),
firstUpdate(true),
delayedFullscreen(false), delayedDesktopSize(false),
statsLastFrame(0), statsLastPixels(0), statsLastPosition(0),
statsGraph(NULL)
{
Fl_Group* group;
// Dummy group to prevent FLTK from moving our widgets around
group = new Fl_Group(0, 0, w, h);
group->resizable(NULL);
resizable(group);
viewport = new Viewport(w, h, serverPF, cc);
// Position will be adjusted later
hscroll = new Fl_Scrollbar(0, 0, 0, 0);
vscroll = new Fl_Scrollbar(0, 0, 0, 0);
hscroll->type(FL_HORIZONTAL);
hscroll->callback(handleScroll, this);
vscroll->callback(handleScroll, this);
group->end();
callback(handleClose, this);
setName(name);
OptionsDialog::addCallback(handleOptions, this);
// Hack. See below...
Fl::event_dispatch(&fltkHandle);
// Support for -geometry option. Note that although we do support
// negative coordinates, we do not support -XOFF-YOFF (ie
// coordinates relative to the right edge / bottom edge) at this
// time.
int geom_x = 0, geom_y = 0;
if (strcmp(geometry, "") != 0) {
int matched;
matched = sscanf(geometry.getValueStr(), "+%d+%d", &geom_x, &geom_y);
if (matched == 2) {
force_position(1);
} else {
int geom_w, geom_h;
matched = sscanf(geometry.getValueStr(), "%dx%d+%d+%d", &geom_w, &geom_h, &geom_x, &geom_y);
switch (matched) {
case 4:
force_position(1);
/* fall through */
case 2:
w = geom_w;
h = geom_h;
break;
default:
geom_x = geom_y = 0;
vlog.error(_("Invalid geometry specified!"));
}
}
}
#ifdef __APPLE__
// On OS X we can do the maximize thing properly before the
// window is showned. Other platforms handled further down...
if (maximize) {
int dummy;
Fl::screen_work_area(dummy, dummy, w, h, geom_x, geom_y);
}
#endif
if (force_position()) {
resize(geom_x, geom_y, w, h);
} else {
size(w, h);
}
if (fullScreen) {
// Hack: Window managers seem to be rather crappy at respecting
// fullscreen hints on initial windows. So on X11 we'll have to
// wait until after we've been mapped.
#if defined(WIN32) || defined(__APPLE__)
fullscreen_on();
#else
delayedFullscreen = true;
#endif
}
show();
// Full screen events are not sent out for a hidden window,
// so send a fake one here to set up things properly.
if (fullscreen_active())
handle(FL_FULLSCREEN);
// Unfortunately, current FLTK does not allow us to set the
// maximized property on Windows and X11 before showing the window.
// See STR #2083 and STR #2178
#ifndef __APPLE__
if (maximize) {
maximizeWindow();
}
#endif
// Adjust layout now that we're visible and know our final size
repositionWidgets();
if (delayedFullscreen) {
// Hack: Fullscreen requests may be ignored, so we need a timeout for
// when we should stop waiting. We also really need to wait for the
// resize, which can come after the fullscreen event.
Fl::add_timeout(0.5, handleFullscreenTimeout, this);
fullscreen_on();
}
// Throughput graph for debugging
if (vlog.getLevel() >= LogWriter::LEVEL_DEBUG) {
memset(&stats, 0, sizeof(stats));
Fl::add_timeout(0, handleStatsTimeout, this);
}
// Show hint about menu key
Fl::add_timeout(0.5, menuOverlay, this);
}
DesktopWindow::~DesktopWindow()
{
// Unregister all timeouts in case they get a change tro trigger
// again later when this object is already gone.
Fl::remove_timeout(handleGrab, this);
Fl::remove_timeout(handleResizeTimeout, this);
Fl::remove_timeout(handleFullscreenTimeout, this);
Fl::remove_timeout(handleEdgeScroll, this);
Fl::remove_timeout(handleStatsTimeout, this);
Fl::remove_timeout(menuOverlay, this);
Fl::remove_timeout(updateOverlay, this);
OptionsDialog::removeCallback(handleOptions);
delete overlay;
delete offscreen;
delete statsGraph;
// FLTK automatically deletes all child widgets, so we shouldn't touch
// them ourselves here
}
const rfb::PixelFormat &DesktopWindow::getPreferredPF()
{
return viewport->getPreferredPF();
}
void DesktopWindow::setName(const char *name)
{
CharArray windowNameStr;
windowNameStr.replaceBuf(new char[256]);
snprintf(windowNameStr.buf, 256, "%.240s - TigerVNC", name);
copy_label(windowNameStr.buf);
}
// Copy the areas of the framebuffer that have been changed (damaged)
// to the displayed window.
void DesktopWindow::updateWindow()
{
if (firstUpdate) {
if (cc->cp.supportsSetDesktopSize) {
// Hack: Wait until we're in the proper mode and position until
// resizing things, otherwise we might send the wrong thing.
if (delayedFullscreen)
delayedDesktopSize = true;
else
handleDesktopSize();
}
firstUpdate = false;
}
viewport->updateWindow();
}
void DesktopWindow::resizeFramebuffer(int new_w, int new_h)
{
if ((new_w == viewport->w()) && (new_h == viewport->h()))
return;
// If we're letting the viewport match the window perfectly, then
// keep things that way for the new size, otherwise just keep things
// like they are.
if (!fullscreen_active()) {
if ((w() == viewport->w()) && (h() == viewport->h()))
size(new_w, new_h);
else {
// Make sure the window isn't too big. We do this manually because
// we have to disable the window size restriction (and it isn't
// entirely trustworthy to begin with).
if ((w() > new_w) || (h() > new_h))
size(__rfbmin(w(), new_w), __rfbmin(h(), new_h));
}
}
viewport->size(new_w, new_h);
repositionWidgets();
}
void DesktopWindow::setCursor(int width, int height,
const rfb::Point& hotspot,
const rdr::U8* data)
{
viewport->setCursor(width, height, hotspot, data);
}
void DesktopWindow::draw()
{
bool redraw;
int X, Y, W, H;
// X11 needs an off screen buffer for compositing to avoid flicker,
// and alpha blending doesn't work for windows on Win32
#if !defined(__APPLE__)
// Adjust offscreen surface dimensions
if ((offscreen == NULL) ||
(offscreen->width() != w()) || (offscreen->height() != h())) {
delete offscreen;
offscreen = new Surface(w(), h());
}
#endif
// Active area inside scrollbars
W = w() - (vscroll->visible() ? vscroll->w() : 0);
H = h() - (hscroll->visible() ? hscroll->h() : 0);
// Full redraw?
redraw = (damage() & ~FL_DAMAGE_CHILD);
// Simplify the clip region to a simple rectangle in order to
// properly draw all the layers even if they only partially overlap
if (redraw)
X = Y = 0;
else
fl_clip_box(0, 0, W, H, X, Y, W, H);
fl_push_no_clip();
fl_push_clip(X, Y, W, H);
// Redraw background only on full redraws
if (redraw) {
if (offscreen)
offscreen->clear(40, 40, 40);
else
fl_rectf(0, 0, W, H, 40, 40, 40);
}
if (offscreen) {
viewport->draw(offscreen);
viewport->clear_damage();
} else {
if (redraw)
draw_child(*viewport);
else
update_child(*viewport);
}
// Debug graph (if active)
if (statsGraph) {
int ox, oy, ow, oh;
ox = X = w() - statsGraph->width() - 30;
oy = Y = h() - statsGraph->height() - 30;
ow = statsGraph->width();
oh = statsGraph->height();
fl_clip_box(ox, oy, ow, oh, ox, oy, ow, oh);
if (offscreen)
statsGraph->blend(offscreen, ox - X, oy - Y, ox, oy, ow, oh, 204);
else
statsGraph->blend(ox - X, oy - Y, ox, oy, ow, oh, 204);
}
// Overlay (if active)
if (overlay) {
int ox, oy, ow, oh;
ox = X = (w() - overlay->width()) / 2;
oy = Y = 50;
ow = overlay->width();
oh = overlay->height();
fl_clip_box(ox, oy, ow, oh, ox, oy, ow, oh);
if (offscreen)
overlay->blend(offscreen, ox - X, oy - Y, ox, oy, ow, oh, overlayAlpha);
else
overlay->blend(ox - X, oy - Y, ox, oy, ow, oh, overlayAlpha);
}
// Flush offscreen surface to screen
if (offscreen) {
fl_clip_box(0, 0, w(), h(), X, Y, W, H);
offscreen->draw(X, Y, X, Y, W, H);
}
fl_pop_clip();
fl_pop_clip();
// Finally the scrollbars
if (redraw) {
draw_child(*hscroll);
draw_child(*vscroll);
} else {
update_child(*hscroll);
update_child(*vscroll);
}
}
void DesktopWindow::resize(int x, int y, int w, int h)
{
bool resizing;
#if ! (defined(WIN32) || defined(__APPLE__))
// X11 window managers will treat a resize to cover the entire
// monitor as a request to go full screen. Make sure we avoid this.
if (!fullscreen_active()) {
bool resize_req;
// If there is no X11 window, then this must be a resize request,
// not a notification from the X server.
if (!shown())
resize_req = true;
else {
// Otherwise we need to get the real window coordinates to tell
// the difference
XWindowAttributes actual;
Window cr;
int wx, wy;
XGetWindowAttributes(fl_display, fl_xid(this), &actual);
XTranslateCoordinates(fl_display, fl_xid(this), actual.root,
0, 0, &wx, &wy, &cr);
// Actual resize request?
if ((wx != x) || (wy != y) ||
(actual.width != w) || (actual.height != h))
resize_req = true;
else
resize_req = false;
}
if (resize_req) {
for (int i = 0;i < Fl::screen_count();i++) {
int sx, sy, sw, sh;
Fl::screen_xywh(sx, sy, sw, sh, i);
if ((sx == x) && (sy == y) && (sw == w) && (sh == h)) {
vlog.info(_("Adjusting window size to avoid accidental full screen request"));
// Assume a panel of some form and adjust the height
y += 20;
h -= 40;
}
}
}
}
#endif
if ((this->w() != w) || (this->h() != h))
resizing = true;
else
resizing = false;
Fl_Window::resize(x, y, w, h);
if (resizing) {
// Try to get the remote size to match our window size, provided
// the following conditions are true:
//
// a) The user has this feature turned on
// b) The server supports it
// c) We're not still waiting for a chance to handle DesktopSize
// d) We're not still waiting for startup fullscreen to kick in
//
if (not firstUpdate and not delayedFullscreen and
::remoteResize and cc->cp.supportsSetDesktopSize) {
// We delay updating the remote desktop as we tend to get a flood
// of resize events as the user is dragging the window.
Fl::remove_timeout(handleResizeTimeout, this);
Fl::add_timeout(0.5, handleResizeTimeout, this);
}
repositionWidgets();
}
}
void DesktopWindow::menuOverlay(void* data)
{
DesktopWindow *self;
self = (DesktopWindow*)data;
self->setOverlay(_("Press %s to open the context menu"),
(const char*)menuKey);
}
void DesktopWindow::setOverlay(const char* text, ...)
{
va_list ap;
char textbuf[1024];
Fl_Image_Surface *surface;
Fl_RGB_Image* imageText;
Fl_RGB_Image* image;
unsigned char* buffer;
int x, y;
int w, h;
unsigned char* a;
const unsigned char* b;
delete overlay;
Fl::remove_timeout(updateOverlay, this);
va_start(ap, text);
vsnprintf(textbuf, sizeof(textbuf), text, ap);
textbuf[sizeof(textbuf)-1] = '\0';
va_end(ap);
#if !defined(WIN32) && !defined(__APPLE__)
// FLTK < 1.3.5 crashes if fl_gc is unset
if (!fl_gc)
fl_gc = XDefaultGC(fl_display, 0);
#endif
fl_font(FL_HELVETICA, FL_NORMAL_SIZE * 2);
w = 0;
fl_measure(textbuf, w, h);
// Margins
w += 80;
h += 40;
surface = new Fl_Image_Surface(w, h);
surface->set_current();
fl_rectf(0, 0, w, h, 0, 0, 0);
fl_font(FL_HELVETICA, FL_NORMAL_SIZE * 2);
fl_color(FL_WHITE);
fl_draw(textbuf, 40, 20 + fl_height() - fl_descent());
imageText = surface->image();
delete surface;
Fl_Display_Device::display_device()->set_current();
buffer = new unsigned char[w * h * 4];
image = new Fl_RGB_Image(buffer, w, h, 4);
a = buffer;
for (x = 0;x < image->w() * image->h();x++) {
a[0] = a[1] = a[2] = 0x40;
a[3] = 0xcc;
a += 4;
}
a = buffer;
b = (const unsigned char*)imageText->data()[0];
for (y = 0;y < h;y++) {
for (x = 0;x < w;x++) {
unsigned char alpha;
alpha = *b;
a[0] = (unsigned)a[0] * (255 - alpha) / 255 + alpha;
a[1] = (unsigned)a[1] * (255 - alpha) / 255 + alpha;
a[2] = (unsigned)a[2] * (255 - alpha) / 255 + alpha;
a[3] = 255 - (255 - a[3]) * (255 - alpha) / 255;
a += 4;
b += imageText->d();
}
if (imageText->ld() != 0)
b += imageText->ld() - w * imageText->d();
}
delete imageText;
x = (this->w() - image->w()) / 2;
y = 50;
w = image->w();
h = image->h();
overlay = new Surface(image);
overlayAlpha = 0;
gettimeofday(&overlayStart, NULL);
delete image;
Fl::add_timeout(1.0/60, updateOverlay, this);
}
void DesktopWindow::updateOverlay(void *data)
{
DesktopWindow *self;
unsigned elapsed;
self = (DesktopWindow*)data;
elapsed = msSince(&self->overlayStart);
if (elapsed < 500) {
self->overlayAlpha = (unsigned)255 * elapsed / 500;
Fl::add_timeout(1.0/60, updateOverlay, self);
} else if (elapsed < 3500) {
self->overlayAlpha = 255;
Fl::add_timeout(3.0, updateOverlay, self);
} else if (elapsed < 4000) {
self->overlayAlpha = (unsigned)255 * (4000 - elapsed) / 500;
Fl::add_timeout(1.0/60, updateOverlay, self);
} else {
delete self->overlay;
self->overlay = NULL;
}
self->damage(FL_DAMAGE_USER1);
}
int DesktopWindow::handle(int event)
{
switch (event) {
case FL_FULLSCREEN:
fullScreen.setParam(fullscreen_active());
// Update scroll bars
repositionWidgets();
if (!fullscreenSystemKeys)
break;
if (fullscreen_active())
grabKeyboard();
else
ungrabKeyboard();
break;
case FL_ENTER:
case FL_LEAVE:
case FL_DRAG:
case FL_MOVE:
if (fullscreen_active()) {
if (((viewport->x() < 0) && (Fl::event_x() < EDGE_SCROLL_SIZE)) ||
((viewport->x() + viewport->w() > w()) && (Fl::event_x() > w() - EDGE_SCROLL_SIZE)) ||
((viewport->y() < 0) && (Fl::event_y() < EDGE_SCROLL_SIZE)) ||
((viewport->y() + viewport->h() > h()) && (Fl::event_y() > h() - EDGE_SCROLL_SIZE))) {
if (!Fl::has_timeout(handleEdgeScroll, this))
Fl::add_timeout(0.1, handleEdgeScroll, this);
}
}
// Continue processing so that the viewport also gets mouse events
break;
}
return Fl_Window::handle(event);
}
int DesktopWindow::fltkHandle(int event, Fl_Window *win)
{
int ret;
ret = Fl::handle_(event, win);
// This is hackish and the result of the dodgy focus handling in FLTK.
// The basic problem is that FLTK's view of focus and the system's tend
// to differ, and as a result we do not see all the FL_FOCUS events we
// need. Fortunately we can grab them here...
DesktopWindow *dw = dynamic_cast<DesktopWindow*>(win);
if (dw && fullscreenSystemKeys) {
switch (event) {
case FL_FOCUS:
// FIXME: We reassert the keyboard grabbing on focus as FLTK there are
// some issues we need to work around:
// a) Fl::grab(0) on X11 will release the keyboard grab for us.
// b) Gaining focus on the system level causes FLTK to switch
// window level on OS X.
if (dw->fullscreen_active())
dw->grabKeyboard();
break;
case FL_UNFOCUS:
// FIXME: We need to relinquish control when the entire window loses
// focus as it is very tied to this specific window on some
// platforms and we want to be able to open subwindows.
dw->ungrabKeyboard();
break;
}
}
return ret;
}
void DesktopWindow::fullscreen_on()
{
if (not fullScreenAllMonitors)
fullscreen_screens(-1, -1, -1, -1);
else {
int top, bottom, left, right;
int top_y, bottom_y, left_x, right_x;
int sx, sy, sw, sh;
top = bottom = left = right = 0;
Fl::screen_xywh(sx, sy, sw, sh, 0);
top_y = sy;
bottom_y = sy + sh;
left_x = sx;
right_x = sx + sw;
for (int i = 1;i < Fl::screen_count();i++) {
Fl::screen_xywh(sx, sy, sw, sh, i);
if (sy < top_y) {
top = i;
top_y = sy;
}
if ((sy + sh) > bottom_y) {
bottom = i;
bottom_y = sy + sh;
}
if (sx < left_x) {
left = i;
left_x = sx;
}
if ((sx + sw) > right_x) {
right = i;
right_x = sx + sw;
}
}
fullscreen_screens(top, bottom, left, right);
}
fullscreen();
}
void DesktopWindow::grabKeyboard()
{
// Grabbing the keyboard is fairly safe as FLTK reroutes events to the
// correct widget regardless of which low level window got the system
// event.
// FIXME: Push this stuff into FLTK.
#if defined(WIN32)
int ret;
ret = win32_enable_lowlevel_keyboard(fl_xid(this));
if (ret != 0)
vlog.error(_("Failure grabbing keyboard"));
#elif defined(__APPLE__)
int ret;
ret = cocoa_capture_display(this, fullScreenAllMonitors);
if (ret != 0)
vlog.error(_("Failure grabbing keyboard"));
#else
int ret;
ret = XGrabKeyboard(fl_display, fl_xid(this), True,
GrabModeAsync, GrabModeAsync, CurrentTime);
if (ret) {
if (ret == AlreadyGrabbed) {
// It seems like we can race with the WM in some cases.
// Try again in a bit.
if (!Fl::has_timeout(handleGrab, this))
Fl::add_timeout(0.500, handleGrab, this);
} else {
vlog.error(_("Failure grabbing keyboard"));
}
}
// We also need to grab the pointer as some WMs like to grab buttons
// combined with modifies (e.g. Alt+Button0 in metacity).
ret = XGrabPointer(fl_display, fl_xid(this), True,
ButtonPressMask|ButtonReleaseMask|
ButtonMotionMask|PointerMotionMask,
GrabModeAsync, GrabModeAsync,
None, None, CurrentTime);
if (ret)
vlog.error(_("Failure grabbing mouse"));
#endif
}
void DesktopWindow::ungrabKeyboard()
{
Fl::remove_timeout(handleGrab, this);
#if defined(WIN32)
win32_disable_lowlevel_keyboard(fl_xid(this));
#elif defined(__APPLE__)
cocoa_release_display(this);
#else
// FLTK has a grab so lets not mess with it
if (Fl::grab())
return;
XUngrabPointer(fl_display, fl_event_time);
XUngrabKeyboard(fl_display, fl_event_time);
#endif
}
void DesktopWindow::handleGrab(void *data)
{
DesktopWindow *self = (DesktopWindow*)data;
assert(self);
if (!fullscreenSystemKeys)
return;
if (!self->fullscreen_active())
return;
self->grabKeyboard();
}
#define _NET_WM_STATE_ADD 1 /* add/set property */
void DesktopWindow::maximizeWindow()
{
#if defined(WIN32)
// We cannot use ShowWindow() in full screen mode as it will
// resize things implicitly. Fortunately modifying the style
// directly results in a maximized state once we leave full screen.
if (fullscreen_active()) {
WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
GetWindowInfo(fl_xid(this), &wi);
SetWindowLongPtr(fl_xid(this), GWL_STYLE, wi.dwStyle | WS_MAXIMIZE);
} else
ShowWindow(fl_xid(this), SW_MAXIMIZE);
#elif defined(__APPLE__)
// OS X is somewhat strange and does not really have a concept of a
// maximized window, so we can simply resize the window to the workarea.
// Note that we shouldn't do this whilst in full screen as that will
// incorrectly adjust things.
if (fullscreen_active())
return;
int X, Y, W, H;
Fl::screen_work_area(X, Y, W, H, this->x(), this->y());
size(W, H);
#else
// X11
fl_open_display();
Atom net_wm_state = XInternAtom (fl_display, "_NET_WM_STATE", 0);
Atom net_wm_state_maximized_vert = XInternAtom (fl_display, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
Atom net_wm_state_maximized_horz = XInternAtom (fl_display, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
XEvent e;
e.xany.type = ClientMessage;
e.xany.window = fl_xid(this);
e.xclient.message_type = net_wm_state;
e.xclient.format = 32;
e.xclient.data.l[0] = _NET_WM_STATE_ADD;
e.xclient.data.l[1] = net_wm_state_maximized_vert;
e.xclient.data.l[2] = net_wm_state_maximized_horz;
e.xclient.data.l[3] = 0;
e.xclient.data.l[4] = 0;
XSendEvent(fl_display, RootWindow(fl_display, fl_screen), 0, SubstructureNotifyMask | SubstructureRedirectMask, &e);
#endif
}
void DesktopWindow::handleDesktopSize()
{
if (strcmp(desktopSize, "") != 0) {
int width, height;
// An explicit size has been requested
if (sscanf(desktopSize, "%dx%d", &width, &height) != 2)
return;
remoteResize(width, height);
} else if (::remoteResize) {
// No explicit size, but remote resizing is on so make sure it
// matches whatever size the window ended up being
remoteResize(w(), h());
}
}
void DesktopWindow::handleResizeTimeout(void *data)
{
DesktopWindow *self = (DesktopWindow *)data;
assert(self);
self->remoteResize(self->w(), self->h());
}
void DesktopWindow::remoteResize(int width, int height)
{
ScreenSet layout;
ScreenSet::iterator iter;
if (!fullscreen_active() || (width > w()) || (height > h())) {
// In windowed mode (or the framebuffer is so large that we need
// to scroll) we just report a single virtual screen that covers
// the entire framebuffer.
layout = cc->cp.screenLayout;
// Not sure why we have no screens, but adding a new one should be
// safe as there is nothing to conflict with...
if (layout.num_screens() == 0)
layout.add_screen(rfb::Screen());
else if (layout.num_screens() != 1) {
// More than one screen. Remove all but the first (which we
// assume is the "primary").
while (true) {
iter = layout.begin();
++iter;
if (iter == layout.end())
break;
layout.remove_screen(iter->id);
}
}
// Resize the remaining single screen to the complete framebuffer
layout.begin()->dimensions.tl.x = 0;
layout.begin()->dimensions.tl.y = 0;
layout.begin()->dimensions.br.x = width;
layout.begin()->dimensions.br.y = height;
} else {
int i;
rdr::U32 id;
int sx, sy, sw, sh;
rfb::Rect viewport_rect, screen_rect;
// In full screen we report all screens that are fully covered.
viewport_rect.setXYWH(x() + (w() - width)/2, y() + (h() - height)/2,
width, height);
// If we can find a matching screen in the existing set, we use
// that, otherwise we create a brand new screen.
//
// FIXME: We should really track screens better so we can handle
// a resized one.
//
for (i = 0;i < Fl::screen_count();i++) {
Fl::screen_xywh(sx, sy, sw, sh, i);
// Check that the screen is fully inside the framebuffer
screen_rect.setXYWH(sx, sy, sw, sh);
if (!screen_rect.enclosed_by(viewport_rect))
continue;
// Adjust the coordinates so they are relative to our viewport
sx -= viewport_rect.tl.x;
sy -= viewport_rect.tl.y;
// Look for perfectly matching existing screen...
for (iter = cc->cp.screenLayout.begin();
iter != cc->cp.screenLayout.end(); ++iter) {
if ((iter->dimensions.tl.x == sx) &&
(iter->dimensions.tl.y == sy) &&
(iter->dimensions.width() == sw) &&
(iter->dimensions.height() == sh))
break;
}
// Found it?
if (iter != cc->cp.screenLayout.end()) {
layout.add_screen(*iter);
continue;
}
// Need to add a new one, which means we need to find an unused id
while (true) {
id = rand();
for (iter = cc->cp.screenLayout.begin();
iter != cc->cp.screenLayout.end(); ++iter) {
if (iter->id == id)
break;
}
if (iter == cc->cp.screenLayout.end())
break;
}
layout.add_screen(rfb::Screen(id, sx, sy, sw, sh, 0));
}
// If the viewport doesn't match a physical screen, then we might
// end up with no screens in the layout. Add a fake one...
if (layout.num_screens() == 0)
layout.add_screen(rfb::Screen(0, 0, 0, width, height, 0));
}
// Do we actually change anything?
if ((width == cc->cp.width) &&
(height == cc->cp.height) &&
(layout == cc->cp.screenLayout))
return;
char buffer[2048];
vlog.debug("Requesting framebuffer resize from %dx%d to %dx%d",
cc->cp.width, cc->cp.height, width, height);
layout.print(buffer, sizeof(buffer));
vlog.debug("%s", buffer);
if (!layout.validate(width, height)) {
vlog.error(_("Invalid screen layout computed for resize request!"));
return;
}
cc->writer()->writeSetDesktopSize(width, height, layout);
}
void DesktopWindow::repositionWidgets()
{
int new_x, new_y;
// Viewport position
new_x = viewport->x();
new_y = viewport->y();
if (w() > viewport->w())
new_x = (w() - viewport->w()) / 2;
else {
if (viewport->x() > 0)
new_x = 0;
else if (w() > (viewport->x() + viewport->w()))
new_x = w() - viewport->w();
}
// Same thing for y axis
if (h() > viewport->h())
new_y = (h() - viewport->h()) / 2;
else {
if (viewport->y() > 0)
new_y = 0;
else if (h() > (viewport->y() + viewport->h()))
new_y = h() - viewport->h();
}
if ((new_x != viewport->x()) || (new_y != viewport->y())) {
viewport->position(new_x, new_y);
damage(FL_DAMAGE_SCROLL);
}
// Scrollbars visbility
if (!fullscreen_active() && (w() < viewport->w()))
hscroll->show();
else
hscroll->hide();
if (!fullscreen_active() && (h() < viewport->h()))
vscroll->show();
else
vscroll->hide();
// Scrollbars positions
hscroll->resize(0, h() - Fl::scrollbar_size(),
w() - (vscroll->visible() ? Fl::scrollbar_size() : 0),
Fl::scrollbar_size());
vscroll->resize(w() - Fl::scrollbar_size(), 0,
Fl::scrollbar_size(),
h() - (hscroll->visible() ? Fl::scrollbar_size() : 0));
// Scrollbars range
hscroll->value(-viewport->x(),
w() - (vscroll->visible() ? vscroll->w() : 0),
0, viewport->w());
vscroll->value(-viewport->y(),
h() - (hscroll->visible() ? hscroll->h() : 0),
0, viewport->h());
hscroll->value(hscroll->clamp(hscroll->value()));
vscroll->value(vscroll->clamp(vscroll->value()));
}
void DesktopWindow::handleClose(Fl_Widget *wnd, void *data)
{
exit_vncviewer();
}
void DesktopWindow::handleOptions(void *data)
{
DesktopWindow *self = (DesktopWindow*)data;
if (self->fullscreen_active() && fullscreenSystemKeys)
self->grabKeyboard();
else
self->ungrabKeyboard();
if (fullScreen && !self->fullscreen_active())
self->fullscreen_on();
else if (!fullScreen && self->fullscreen_active())
self->fullscreen_off();
}
void DesktopWindow::handleFullscreenTimeout(void *data)
{
DesktopWindow *self = (DesktopWindow *)data;
assert(self);
self->delayedFullscreen = false;
if (self->delayedDesktopSize) {
self->handleDesktopSize();
self->delayedDesktopSize = false;
}
}
void DesktopWindow::scrollTo(int x, int y)
{
x = hscroll->clamp(x);
y = vscroll->clamp(y);
hscroll->value(x);
vscroll->value(y);
if (!hscroll->visible())
x = -viewport->x();
if (!vscroll->visible())
y = -viewport->y();
// Scrollbar position results in inverse movement of
// the viewport widget
x = -x;
y = -y;
if ((viewport->x() == x) && (viewport->y() == y))
return;
viewport->position(x, y);
damage(FL_DAMAGE_SCROLL);
}
void DesktopWindow::handleScroll(Fl_Widget *widget, void *data)
{
DesktopWindow *self = (DesktopWindow *)data;
self->scrollTo(self->hscroll->value(), self->vscroll->value());
}
void DesktopWindow::handleEdgeScroll(void *data)
{
DesktopWindow *self = (DesktopWindow *)data;
int mx, my;
int dx, dy;
assert(self);
if (!self->fullscreen_active())
return;
mx = Fl::event_x();
my = Fl::event_y();
dx = dy = 0;
// Clamp mouse position in case it is outside the window
if (mx < 0)
mx = 0;
if (mx > self->w())
mx = self->w();
if (my < 0)
my = 0;
if (my > self->h())
my = self->h();
if ((self->viewport->x() < 0) && (mx < EDGE_SCROLL_SIZE))
dx = EDGE_SCROLL_SPEED -
EDGE_SCROLL_SPEED * mx / EDGE_SCROLL_SIZE;
if ((self->viewport->x() + self->viewport->w() > self->w()) &&
(mx > self->w() - EDGE_SCROLL_SIZE))
dx = EDGE_SCROLL_SPEED * (self->w() - mx) / EDGE_SCROLL_SIZE -
EDGE_SCROLL_SPEED;
if ((self->viewport->y() < 0) && (my < EDGE_SCROLL_SIZE))
dy = EDGE_SCROLL_SPEED -
EDGE_SCROLL_SPEED * my / EDGE_SCROLL_SIZE;
if ((self->viewport->y() + self->viewport->h() > self->h()) &&
(my > self->h() - EDGE_SCROLL_SIZE))
dy = EDGE_SCROLL_SPEED * (self->h() - my) / EDGE_SCROLL_SIZE -
EDGE_SCROLL_SPEED;
if ((dx == 0) && (dy == 0))
return;
self->scrollTo(self->hscroll->value() + dx, self->vscroll->value() + dy);
Fl::repeat_timeout(0.1, handleEdgeScroll, data);
}
void DesktopWindow::handleStatsTimeout(void *data)
{
DesktopWindow *self = (DesktopWindow*)data;
const size_t statsCount = sizeof(stats)/sizeof(stats[0]);
unsigned frame, pixels, pos;
unsigned elapsed;
const unsigned statsWidth = 200;
const unsigned statsHeight = 100;
const unsigned graphWidth = statsWidth - 10;
const unsigned graphHeight = statsHeight - 25;
Fl_Image_Surface *surface;
Fl_RGB_Image *image;
unsigned maxFPS, maxPPS, maxBPS;
size_t i;
char buffer[256];
frame = self->cc->getFrameCount();
pixels = self->cc->getPixelCount();
pos = self->cc->getPosition();
elapsed = msSince(&self->statsLastTime);
if (elapsed < 1)
elapsed = 1;
memmove(&self->stats[0], &self->stats[1], sizeof(stats[0])*(statsCount-1));
self->stats[statsCount-1].fps = (frame - self->statsLastFrame) * 1000 / elapsed;
self->stats[statsCount-1].pps = (pixels - self->statsLastPixels) * 1000 / elapsed;
self->stats[statsCount-1].bps = (pos - self->statsLastPosition) * 1000 / elapsed;
gettimeofday(&self->statsLastTime, NULL);
self->statsLastFrame = frame;
self->statsLastPixels = pixels;
self->statsLastPosition = pos;
#if !defined(WIN32) && !defined(__APPLE__)
// FLTK < 1.3.5 crashes if fl_gc is unset
if (!fl_gc)
fl_gc = XDefaultGC(fl_display, 0);
#endif
surface = new Fl_Image_Surface(statsWidth, statsHeight);
surface->set_current();
fl_rectf(0, 0, statsWidth, statsHeight, FL_BLACK);
fl_rect(5, 5, graphWidth, graphHeight, FL_WHITE);
maxFPS = maxPPS = maxBPS = 0;
for (i = 0;i < statsCount;i++) {
if (self->stats[i].fps > maxFPS)
maxFPS = self->stats[i].fps;
if (self->stats[i].pps > maxPPS)
maxPPS = self->stats[i].pps;
if (self->stats[i].bps > maxBPS)
maxBPS = self->stats[i].bps;
}
if (maxFPS != 0) {
fl_color(FL_GREEN);
for (i = 0;i < statsCount-1;i++) {
fl_line(5 + i * graphWidth / statsCount,
5 + graphHeight - graphHeight * self->stats[i].fps / maxFPS,
5 + (i+1) * graphWidth / statsCount,
5 + graphHeight - graphHeight * self->stats[i+1].fps / maxFPS);
}
}
if (maxPPS != 0) {
fl_color(FL_YELLOW);
for (i = 0;i < statsCount-1;i++) {
fl_line(5 + i * graphWidth / statsCount,
5 + graphHeight - graphHeight * self->stats[i].pps / maxPPS,
5 + (i+1) * graphWidth / statsCount,
5 + graphHeight - graphHeight * self->stats[i+1].pps / maxPPS);
}
}
if (maxBPS != 0) {
fl_color(FL_RED);
for (i = 0;i < statsCount-1;i++) {
fl_line(5 + i * graphWidth / statsCount,
5 + graphHeight - graphHeight * self->stats[i].bps / maxBPS,
5 + (i+1) * graphWidth / statsCount,
5 + graphHeight - graphHeight * self->stats[i+1].bps / maxBPS);
}
}
fl_font(FL_HELVETICA, 10);
fl_color(FL_GREEN);
snprintf(buffer, sizeof(buffer), "%u fps", self->stats[statsCount-1].fps);
fl_draw(buffer, 5, statsHeight - 5);
fl_color(FL_YELLOW);
siPrefix(self->stats[statsCount-1].pps * 8, "pix/s",
buffer, sizeof(buffer), 3);
fl_draw(buffer, 5 + (statsWidth-10)/3, statsHeight - 5);
fl_color(FL_RED);
iecPrefix(self->stats[statsCount-1].bps * 8, "Bps",
buffer, sizeof(buffer), 3);
fl_draw(buffer, 5 + (statsWidth-10)*2/3, statsHeight - 5);
image = surface->image();
delete surface;
Fl_Display_Device::display_device()->set_current();
delete self->statsGraph;
self->statsGraph = new Surface(image);
delete image;
self->damage(FL_DAMAGE_CHILD, self->w() - statsWidth - 30,
self->h() - statsHeight - 30,
statsWidth, statsHeight);
Fl::repeat_timeout(0.5, handleStatsTimeout, data);
}
|