blob: 156b41a5ef3e9572d2dde8139ac1785093e32d22 [file] [log] [blame]
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001//
2// Copyright (C) 2001-2004 HorizonLive.com, Inc. All Rights Reserved.
3// Copyright (C) 2001-2006 Constantin Kaplinsky. All Rights Reserved.
4// Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
5// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
6//
7// This is free software; you can redistribute it and/or modify
8// it under the terms of the GNU General Public License as published by
9// the Free Software Foundation; either version 2 of the License, or
10// (at your option) any later version.
11//
12// This software is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU General Public License for more details.
16//
17// You should have received a copy of the GNU General Public License
18// along with this software; if not, write to the Free Software
19// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20// USA.
21//
22
23//
24// RfbProto.java
25//
26
Constantin Kaplinsky90d8a502008-04-14 09:45:50 +000027package com.tightvnc.vncviewer;
28
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000029import java.io.*;
30import java.awt.*;
31import java.awt.event.*;
32import java.net.Socket;
33import java.util.zip.*;
34
35class RfbProto {
36
37 final static String
38 versionMsg_3_3 = "RFB 003.003\n",
39 versionMsg_3_7 = "RFB 003.007\n",
40 versionMsg_3_8 = "RFB 003.008\n";
41
42 // Vendor signatures: standard VNC/RealVNC, TridiaVNC, and TightVNC
43 final static String
44 StandardVendor = "STDV",
45 TridiaVncVendor = "TRDV",
46 TightVncVendor = "TGHT";
47
48 // Security types
49 final static int
50 SecTypeInvalid = 0,
51 SecTypeNone = 1,
52 SecTypeVncAuth = 2,
53 SecTypeTight = 16;
54
55 // Supported tunneling types
56 final static int
57 NoTunneling = 0;
58 final static String
59 SigNoTunneling = "NOTUNNEL";
60
61 // Supported authentication types
62 final static int
63 AuthNone = 1,
64 AuthVNC = 2,
65 AuthUnixLogin = 129;
66 final static String
67 SigAuthNone = "NOAUTH__",
68 SigAuthVNC = "VNCAUTH_",
69 SigAuthUnixLogin = "ULGNAUTH";
70
71 // VNC authentication results
72 final static int
73 VncAuthOK = 0,
74 VncAuthFailed = 1,
75 VncAuthTooMany = 2;
76
77 // Standard server-to-client messages
78 final static int
79 FramebufferUpdate = 0,
80 SetColourMapEntries = 1,
81 Bell = 2,
82 ServerCutText = 3;
83
84 // Non-standard server-to-client messages
85 final static int
86 EndOfContinuousUpdates = 150;
87 final static String
88 SigEndOfContinuousUpdates = "CUS_EOCU";
89
90 // Standard client-to-server messages
91 final static int
92 SetPixelFormat = 0,
93 FixColourMapEntries = 1,
94 SetEncodings = 2,
95 FramebufferUpdateRequest = 3,
96 KeyboardEvent = 4,
97 PointerEvent = 5,
98 ClientCutText = 6;
99
100 // Non-standard client-to-server messages
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000101 final static int EnableContinuousUpdates = 150;
102 final static int VideoRectangleSelection = 151;
103 final static String SigEnableContinuousUpdates = "CUC_ENCU";
104 final static String SigVideoRectangleSelection = "VRECTSEL";
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000105
106 // Supported encodings and pseudo-encodings
107 final static int
108 EncodingRaw = 0,
109 EncodingCopyRect = 1,
110 EncodingRRE = 2,
111 EncodingCoRRE = 4,
112 EncodingHextile = 5,
113 EncodingZlib = 6,
114 EncodingTight = 7,
115 EncodingZRLE = 16,
116 EncodingCompressLevel0 = 0xFFFFFF00,
117 EncodingQualityLevel0 = 0xFFFFFFE0,
118 EncodingXCursor = 0xFFFFFF10,
119 EncodingRichCursor = 0xFFFFFF11,
120 EncodingPointerPos = 0xFFFFFF18,
121 EncodingLastRect = 0xFFFFFF20,
122 EncodingNewFBSize = 0xFFFFFF21;
123 final static String
124 SigEncodingRaw = "RAW_____",
125 SigEncodingCopyRect = "COPYRECT",
126 SigEncodingRRE = "RRE_____",
127 SigEncodingCoRRE = "CORRE___",
128 SigEncodingHextile = "HEXTILE_",
129 SigEncodingZlib = "ZLIB____",
130 SigEncodingTight = "TIGHT___",
131 SigEncodingZRLE = "ZRLE____",
132 SigEncodingCompressLevel0 = "COMPRLVL",
133 SigEncodingQualityLevel0 = "JPEGQLVL",
134 SigEncodingXCursor = "X11CURSR",
135 SigEncodingRichCursor = "RCHCURSR",
136 SigEncodingPointerPos = "POINTPOS",
137 SigEncodingLastRect = "LASTRECT",
138 SigEncodingNewFBSize = "NEWFBSIZ";
139
140 final static int MaxNormalEncoding = 255;
141
142 // Contstants used in the Hextile decoder
143 final static int
144 HextileRaw = 1,
145 HextileBackgroundSpecified = 2,
146 HextileForegroundSpecified = 4,
147 HextileAnySubrects = 8,
148 HextileSubrectsColoured = 16;
149
150 // Contstants used in the Tight decoder
151 final static int TightMinToCompress = 12;
152 final static int
153 TightExplicitFilter = 0x04,
154 TightFill = 0x08,
155 TightJpeg = 0x09,
156 TightMaxSubencoding = 0x09,
157 TightFilterCopy = 0x00,
158 TightFilterPalette = 0x01,
159 TightFilterGradient = 0x02;
160
161
162 String host;
163 int port;
164 Socket sock;
165 OutputStream os;
166 SessionRecorder rec;
167 boolean inNormalProtocol = false;
168 VncViewer viewer;
169
170 // Input stream is declared private to make sure it can be accessed
171 // only via RfbProto methods. We have to do this because we want to
172 // count how many bytes were read.
173 private DataInputStream is;
174 private long numBytesRead = 0;
175 public long getNumBytesRead() { return numBytesRead; }
176
177 // Java on UNIX does not call keyPressed() on some keys, for example
178 // swedish keys To prevent our workaround to produce duplicate
179 // keypresses on JVMs that actually works, keep track of if
enikey2f0294e2008-12-24 08:18:54 +0000180 // keyPressed() for a "broken" key was called or not.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000181 boolean brokenKeyPressed = false;
182
183 // This will be set to true on the first framebuffer update
184 // containing Zlib-, ZRLE- or Tight-encoded data.
185 boolean wereZlibUpdates = false;
186
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000187 // This fields are needed to show warnings about inefficiently saved
188 // sessions only once per each saved session file.
189 boolean zlibWarningShown;
190 boolean tightWarningShown;
191
192 // Before starting to record each saved session, we set this field
193 // to 0, and increment on each framebuffer update. We don't flush
enikey2f0294e2008-12-24 08:18:54 +0000194 // the SessionRecorder data into the file before the second update.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000195 // This allows us to write initial framebuffer update with zero
196 // timestamp, to let the player show initial desktop before
197 // playback.
198 int numUpdatesInSession;
199
200 // Measuring network throughput.
201 boolean timing;
202 long timeWaitedIn100us;
203 long timedKbits;
204
205 // Protocol version and TightVNC-specific protocol options.
206 int serverMajor, serverMinor;
207 int clientMajor, clientMinor;
208 boolean protocolTightVNC;
209 CapsContainer tunnelCaps, authCaps;
210 CapsContainer serverMsgCaps, clientMsgCaps;
211 CapsContainer encodingCaps;
212
213 // "Continuous updates" is a TightVNC-specific feature that allows
214 // receiving framebuffer updates continuously, without sending update
215 // requests. The variables below track the state of this feature.
216 // Initially, continuous updates are disabled. They can be enabled
217 // by calling tryEnableContinuousUpdates() method, and only if this
218 // feature is supported by the server. To disable continuous updates,
219 // tryDisableContinuousUpdates() should be called.
220 private boolean continuousUpdatesActive = false;
221 private boolean continuousUpdatesEnding = false;
222
223 // If true, informs that the RFB socket was closed.
224 private boolean closed;
225
226 //
227 // Constructor. Make TCP connection to RFB server.
228 //
229
230 RfbProto(String h, int p, VncViewer v) throws IOException {
231 viewer = v;
232 host = h;
233 port = p;
234
235 if (viewer.socketFactory == null) {
236 sock = new Socket(host, port);
enikey17ac1812008-12-19 11:22:13 +0000237 sock.setTcpNoDelay(true);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000238 } else {
239 try {
240 Class factoryClass = Class.forName(viewer.socketFactory);
241 SocketFactory factory = (SocketFactory)factoryClass.newInstance();
242 if (viewer.inAnApplet)
243 sock = factory.createSocket(host, port, viewer);
244 else
245 sock = factory.createSocket(host, port, viewer.mainArgs);
246 } catch(Exception e) {
247 e.printStackTrace();
248 throw new IOException(e.getMessage());
249 }
250 }
251 is = new DataInputStream(new BufferedInputStream(sock.getInputStream(),
252 16384));
253 os = sock.getOutputStream();
254
255 timing = false;
256 timeWaitedIn100us = 5;
257 timedKbits = 0;
258 }
259
260
261 synchronized void close() {
262 try {
263 sock.close();
264 closed = true;
265 System.out.println("RFB socket closed");
266 if (rec != null) {
267 rec.close();
268 rec = null;
269 }
270 } catch (Exception e) {
271 e.printStackTrace();
272 }
273 }
274
275 synchronized boolean closed() {
276 return closed;
277 }
278
279 //
280 // Read server's protocol version message
281 //
282
283 void readVersionMsg() throws Exception {
284
285 byte[] b = new byte[12];
286
287 readFully(b);
288
289 if ((b[0] != 'R') || (b[1] != 'F') || (b[2] != 'B') || (b[3] != ' ')
290 || (b[4] < '0') || (b[4] > '9') || (b[5] < '0') || (b[5] > '9')
291 || (b[6] < '0') || (b[6] > '9') || (b[7] != '.')
292 || (b[8] < '0') || (b[8] > '9') || (b[9] < '0') || (b[9] > '9')
293 || (b[10] < '0') || (b[10] > '9') || (b[11] != '\n'))
294 {
295 throw new Exception("Host " + host + " port " + port +
296 " is not an RFB server");
297 }
298
299 serverMajor = (b[4] - '0') * 100 + (b[5] - '0') * 10 + (b[6] - '0');
300 serverMinor = (b[8] - '0') * 100 + (b[9] - '0') * 10 + (b[10] - '0');
301
302 if (serverMajor < 3) {
303 throw new Exception("RFB server does not support protocol version 3");
304 }
305 }
306
307
308 //
309 // Write our protocol version message
310 //
311
312 void writeVersionMsg() throws IOException {
313 clientMajor = 3;
314 if (serverMajor > 3 || serverMinor >= 8) {
315 clientMinor = 8;
316 os.write(versionMsg_3_8.getBytes());
317 } else if (serverMinor >= 7) {
318 clientMinor = 7;
319 os.write(versionMsg_3_7.getBytes());
320 } else {
321 clientMinor = 3;
322 os.write(versionMsg_3_3.getBytes());
323 }
324 protocolTightVNC = false;
325 initCapabilities();
326 }
327
328
329 //
330 // Negotiate the authentication scheme.
331 //
332
333 int negotiateSecurity() throws Exception {
334 return (clientMinor >= 7) ?
335 selectSecurityType() : readSecurityType();
336 }
337
338 //
339 // Read security type from the server (protocol version 3.3).
340 //
341
342 int readSecurityType() throws Exception {
343 int secType = readU32();
344
345 switch (secType) {
346 case SecTypeInvalid:
347 readConnFailedReason();
348 return SecTypeInvalid; // should never be executed
349 case SecTypeNone:
350 case SecTypeVncAuth:
351 return secType;
352 default:
353 throw new Exception("Unknown security type from RFB server: " + secType);
354 }
355 }
356
357 //
358 // Select security type from the server's list (protocol versions 3.7/3.8).
359 //
360
361 int selectSecurityType() throws Exception {
362 int secType = SecTypeInvalid;
363
364 // Read the list of secutiry types.
365 int nSecTypes = readU8();
366 if (nSecTypes == 0) {
367 readConnFailedReason();
368 return SecTypeInvalid; // should never be executed
369 }
370 byte[] secTypes = new byte[nSecTypes];
371 readFully(secTypes);
372
373 // Find out if the server supports TightVNC protocol extensions
374 for (int i = 0; i < nSecTypes; i++) {
375 if (secTypes[i] == SecTypeTight) {
376 protocolTightVNC = true;
377 os.write(SecTypeTight);
378 return SecTypeTight;
379 }
380 }
381
382 // Find first supported security type.
383 for (int i = 0; i < nSecTypes; i++) {
384 if (secTypes[i] == SecTypeNone || secTypes[i] == SecTypeVncAuth) {
385 secType = secTypes[i];
386 break;
387 }
388 }
389
390 if (secType == SecTypeInvalid) {
391 throw new Exception("Server did not offer supported security type");
392 } else {
393 os.write(secType);
394 }
395
396 return secType;
397 }
398
399 //
400 // Perform "no authentication".
401 //
402
403 void authenticateNone() throws Exception {
404 if (clientMinor >= 8)
405 readSecurityResult("No authentication");
406 }
407
408 //
409 // Perform standard VNC Authentication.
410 //
411
412 void authenticateVNC(String pw) throws Exception {
413 byte[] challenge = new byte[16];
414 readFully(challenge);
415
416 if (pw.length() > 8)
417 pw = pw.substring(0, 8); // Truncate to 8 chars
418
419 // Truncate password on the first zero byte.
420 int firstZero = pw.indexOf(0);
421 if (firstZero != -1)
422 pw = pw.substring(0, firstZero);
423
424 byte[] key = {0, 0, 0, 0, 0, 0, 0, 0};
425 System.arraycopy(pw.getBytes(), 0, key, 0, pw.length());
426
427 DesCipher des = new DesCipher(key);
428
429 des.encrypt(challenge, 0, challenge, 0);
430 des.encrypt(challenge, 8, challenge, 8);
431
432 os.write(challenge);
433
434 readSecurityResult("VNC authentication");
435 }
436
437 //
438 // Read security result.
439 // Throws an exception on authentication failure.
440 //
441
442 void readSecurityResult(String authType) throws Exception {
443 int securityResult = readU32();
444
445 switch (securityResult) {
446 case VncAuthOK:
447 System.out.println(authType + ": success");
448 break;
449 case VncAuthFailed:
450 if (clientMinor >= 8)
451 readConnFailedReason();
452 throw new Exception(authType + ": failed");
453 case VncAuthTooMany:
454 throw new Exception(authType + ": failed, too many tries");
455 default:
456 throw new Exception(authType + ": unknown result " + securityResult);
457 }
458 }
459
460 //
461 // Read the string describing the reason for a connection failure,
462 // and throw an exception.
463 //
464
465 void readConnFailedReason() throws Exception {
466 int reasonLen = readU32();
467 byte[] reason = new byte[reasonLen];
468 readFully(reason);
469 throw new Exception(new String(reason));
470 }
471
472 //
473 // Initialize capability lists (TightVNC protocol extensions).
474 //
475
476 void initCapabilities() {
477 tunnelCaps = new CapsContainer();
478 authCaps = new CapsContainer();
479 serverMsgCaps = new CapsContainer();
480 clientMsgCaps = new CapsContainer();
481 encodingCaps = new CapsContainer();
482
483 // Supported authentication methods
484 authCaps.add(AuthNone, StandardVendor, SigAuthNone,
485 "No authentication");
486 authCaps.add(AuthVNC, StandardVendor, SigAuthVNC,
487 "Standard VNC password authentication");
488
489 // Supported non-standard server-to-client messages
490 serverMsgCaps.add(EndOfContinuousUpdates, TightVncVendor,
491 SigEndOfContinuousUpdates,
492 "End of continuous updates notification");
493
494 // Supported non-standard client-to-server messages
495 clientMsgCaps.add(EnableContinuousUpdates, TightVncVendor,
496 SigEnableContinuousUpdates,
497 "Enable/disable continuous updates");
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000498 clientMsgCaps.add(VideoRectangleSelection, TightVncVendor,
499 SigVideoRectangleSelection,
500 "Select a rectangle to be treated as video");
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000501
502 // Supported encoding types
503 encodingCaps.add(EncodingCopyRect, StandardVendor,
504 SigEncodingCopyRect, "Standard CopyRect encoding");
505 encodingCaps.add(EncodingRRE, StandardVendor,
506 SigEncodingRRE, "Standard RRE encoding");
507 encodingCaps.add(EncodingCoRRE, StandardVendor,
508 SigEncodingCoRRE, "Standard CoRRE encoding");
509 encodingCaps.add(EncodingHextile, StandardVendor,
510 SigEncodingHextile, "Standard Hextile encoding");
511 encodingCaps.add(EncodingZRLE, StandardVendor,
512 SigEncodingZRLE, "Standard ZRLE encoding");
513 encodingCaps.add(EncodingZlib, TridiaVncVendor,
514 SigEncodingZlib, "Zlib encoding");
515 encodingCaps.add(EncodingTight, TightVncVendor,
516 SigEncodingTight, "Tight encoding");
517
518 // Supported pseudo-encoding types
519 encodingCaps.add(EncodingCompressLevel0, TightVncVendor,
520 SigEncodingCompressLevel0, "Compression level");
521 encodingCaps.add(EncodingQualityLevel0, TightVncVendor,
522 SigEncodingQualityLevel0, "JPEG quality level");
523 encodingCaps.add(EncodingXCursor, TightVncVendor,
524 SigEncodingXCursor, "X-style cursor shape update");
525 encodingCaps.add(EncodingRichCursor, TightVncVendor,
526 SigEncodingRichCursor, "Rich-color cursor shape update");
527 encodingCaps.add(EncodingPointerPos, TightVncVendor,
528 SigEncodingPointerPos, "Pointer position update");
529 encodingCaps.add(EncodingLastRect, TightVncVendor,
530 SigEncodingLastRect, "LastRect protocol extension");
531 encodingCaps.add(EncodingNewFBSize, TightVncVendor,
532 SigEncodingNewFBSize, "Framebuffer size change");
533 }
534
535 //
536 // Setup tunneling (TightVNC protocol extensions)
537 //
538
539 void setupTunneling() throws IOException {
540 int nTunnelTypes = readU32();
541 if (nTunnelTypes != 0) {
542 readCapabilityList(tunnelCaps, nTunnelTypes);
543
544 // We don't support tunneling yet.
545 writeInt(NoTunneling);
546 }
547 }
548
549 //
550 // Negotiate authentication scheme (TightVNC protocol extensions)
551 //
552
553 int negotiateAuthenticationTight() throws Exception {
554 int nAuthTypes = readU32();
555 if (nAuthTypes == 0)
556 return AuthNone;
557
558 readCapabilityList(authCaps, nAuthTypes);
559 for (int i = 0; i < authCaps.numEnabled(); i++) {
560 int authType = authCaps.getByOrder(i);
561 if (authType == AuthNone || authType == AuthVNC) {
562 writeInt(authType);
563 return authType;
564 }
565 }
566 throw new Exception("No suitable authentication scheme found");
567 }
568
569 //
570 // Read a capability list (TightVNC protocol extensions)
571 //
572
573 void readCapabilityList(CapsContainer caps, int count) throws IOException {
574 int code;
575 byte[] vendor = new byte[4];
576 byte[] name = new byte[8];
577 for (int i = 0; i < count; i++) {
578 code = readU32();
579 readFully(vendor);
580 readFully(name);
581 caps.enable(new CapabilityInfo(code, vendor, name));
582 }
583 }
584
585 //
586 // Write a 32-bit integer into the output stream.
587 //
588
589 void writeInt(int value) throws IOException {
590 byte[] b = new byte[4];
591 b[0] = (byte) ((value >> 24) & 0xff);
592 b[1] = (byte) ((value >> 16) & 0xff);
593 b[2] = (byte) ((value >> 8) & 0xff);
594 b[3] = (byte) (value & 0xff);
595 os.write(b);
596 }
597
598 //
599 // Write the client initialisation message
600 //
601
602 void writeClientInit() throws IOException {
603 if (viewer.options.shareDesktop) {
604 os.write(1);
605 } else {
606 os.write(0);
607 }
608 viewer.options.disableShareDesktop();
609 }
610
611
612 //
613 // Read the server initialisation message
614 //
615
616 String desktopName;
617 int framebufferWidth, framebufferHeight;
618 int bitsPerPixel, depth;
619 boolean bigEndian, trueColour;
620 int redMax, greenMax, blueMax, redShift, greenShift, blueShift;
621
622 void readServerInit() throws IOException {
623 framebufferWidth = readU16();
624 framebufferHeight = readU16();
625 bitsPerPixel = readU8();
626 depth = readU8();
627 bigEndian = (readU8() != 0);
628 trueColour = (readU8() != 0);
629 redMax = readU16();
630 greenMax = readU16();
631 blueMax = readU16();
632 redShift = readU8();
633 greenShift = readU8();
634 blueShift = readU8();
635 byte[] pad = new byte[3];
636 readFully(pad);
637 int nameLength = readU32();
638 byte[] name = new byte[nameLength];
639 readFully(name);
640 desktopName = new String(name);
641
642 // Read interaction capabilities (TightVNC protocol extensions)
643 if (protocolTightVNC) {
644 int nServerMessageTypes = readU16();
645 int nClientMessageTypes = readU16();
646 int nEncodingTypes = readU16();
647 readU16();
648 readCapabilityList(serverMsgCaps, nServerMessageTypes);
649 readCapabilityList(clientMsgCaps, nClientMessageTypes);
650 readCapabilityList(encodingCaps, nEncodingTypes);
651 }
652
653 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
654 viewer.options.disableContUpdates();
655 }
656
657 inNormalProtocol = true;
658 }
659
660
661 //
662 // Create session file and write initial protocol messages into it.
663 //
664
665 void startSession(String fname) throws IOException {
666 rec = new SessionRecorder(fname);
667 rec.writeHeader();
668 rec.write(versionMsg_3_3.getBytes());
669 rec.writeIntBE(SecTypeNone);
670 rec.writeShortBE(framebufferWidth);
671 rec.writeShortBE(framebufferHeight);
672 byte[] fbsServerInitMsg = {
673 32, 24, 0, 1, 0,
674 (byte)0xFF, 0, (byte)0xFF, 0, (byte)0xFF,
675 16, 8, 0, 0, 0, 0
676 };
677 rec.write(fbsServerInitMsg);
678 rec.writeIntBE(desktopName.length());
679 rec.write(desktopName.getBytes());
680 numUpdatesInSession = 0;
681
682 // FIXME: If there were e.g. ZRLE updates only, that should not
683 // affect recording of Zlib and Tight updates. So, actually
684 // we should maintain separate flags for Zlib, ZRLE and
685 // Tight, instead of one ``wereZlibUpdates'' variable.
686 //
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000687
688 zlibWarningShown = false;
689 tightWarningShown = false;
690 }
691
692 //
693 // Close session file.
694 //
695
696 void closeSession() throws IOException {
697 if (rec != null) {
698 rec.close();
699 rec = null;
700 }
701 }
702
703
704 //
705 // Set new framebuffer size
706 //
707
708 void setFramebufferSize(int width, int height) {
709 framebufferWidth = width;
710 framebufferHeight = height;
711 }
712
713
714 //
715 // Read the server message type
716 //
717
718 int readServerMessageType() throws IOException {
719 int msgType = readU8();
720
721 // If the session is being recorded:
722 if (rec != null) {
723 if (msgType == Bell) { // Save Bell messages in session files.
724 rec.writeByte(msgType);
725 if (numUpdatesInSession > 0)
726 rec.flush();
727 }
728 }
729
730 return msgType;
731 }
732
733
734 //
735 // Read a FramebufferUpdate message
736 //
737
738 int updateNRects;
739
740 void readFramebufferUpdate() throws IOException {
741 skipBytes(1);
742 updateNRects = readU16();
743
744 // If the session is being recorded:
745 if (rec != null) {
746 rec.writeByte(FramebufferUpdate);
747 rec.writeByte(0);
748 rec.writeShortBE(updateNRects);
749 }
750
751 numUpdatesInSession++;
752 }
753
enikey2f0294e2008-12-24 08:18:54 +0000754 //
755 // Returns true if encoding is not pseudo
756 //
757 // FIXME: Find better way to differ pseudo and real encodings
758 //
759
760 boolean isRealDecoderEncoding(int encoding) {
761 if ((encoding >= 1) && (encoding <= 16)) {
762 return true;
763 }
764 return false;
765 }
766
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000767 // Read a FramebufferUpdate rectangle header
768
769 int updateRectX, updateRectY, updateRectW, updateRectH, updateRectEncoding;
770
771 void readFramebufferUpdateRectHdr() throws Exception {
772 updateRectX = readU16();
773 updateRectY = readU16();
774 updateRectW = readU16();
775 updateRectH = readU16();
776 updateRectEncoding = readU32();
777
778 if (updateRectEncoding == EncodingZlib ||
779 updateRectEncoding == EncodingZRLE ||
780 updateRectEncoding == EncodingTight)
781 wereZlibUpdates = true;
782
783 // If the session is being recorded:
784 if (rec != null) {
785 if (numUpdatesInSession > 1)
786 rec.flush(); // Flush the output on each rectangle.
787 rec.writeShortBE(updateRectX);
788 rec.writeShortBE(updateRectY);
789 rec.writeShortBE(updateRectW);
790 rec.writeShortBE(updateRectH);
enikey2f0294e2008-12-24 08:18:54 +0000791
792 //
793 // If this is pseudo encoding or CopyRect that write encoding ID
794 // in this place. All real encoding ID will be written to record stream
795 // in decoder classes.
796 //
797 // TODO: Make CopyRect decoder class.
798 //
799
800 if (((updateRectEncoding == EncodingCopyRect)
801 || (!isRealDecoderEncoding(updateRectEncoding))) && (rec != null)) {
802 rec.writeIntBE(updateRectEncoding);
803 }
804
805 //
806 // Old code
807 //
808
809 /*if (updateRectEncoding == EncodingZlib && !recordFromBeginning) {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000810 // Here we cannot write Zlib-encoded rectangles because the
811 // decoder won't be able to reproduce zlib stream state.
812 if (!zlibWarningShown) {
813 System.out.println("Warning: Raw encoding will be used " +
814 "instead of Zlib in recorded session.");
815 zlibWarningShown = true;
816 }
817 rec.writeIntBE(EncodingRaw);
818 } else {
819 rec.writeIntBE(updateRectEncoding);
820 if (updateRectEncoding == EncodingTight && !recordFromBeginning &&
821 !tightWarningShown) {
822 System.out.println("Warning: Re-compressing Tight-encoded " +
823 "updates for session recording.");
824 tightWarningShown = true;
825 }
enikey2f0294e2008-12-24 08:18:54 +0000826 }*/
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000827 }
828
829 if (updateRectEncoding < 0 || updateRectEncoding > MaxNormalEncoding)
830 return;
831
832 if (updateRectX + updateRectW > framebufferWidth ||
833 updateRectY + updateRectH > framebufferHeight) {
834 throw new Exception("Framebuffer update rectangle too large: " +
835 updateRectW + "x" + updateRectH + " at (" +
836 updateRectX + "," + updateRectY + ")");
837 }
838 }
839
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000840 //
841 // Read a ServerCutText message
842 //
843
844 String readServerCutText() throws IOException {
845 skipBytes(3);
846 int len = readU32();
847 byte[] text = new byte[len];
848 readFully(text);
849 return new String(text);
850 }
851
852
853 //
854 // Read an integer in compact representation (1..3 bytes).
855 // Such format is used as a part of the Tight encoding.
856 // Also, this method records data if session recording is active and
857 // the viewer's recordFromBeginning variable is set to true.
858 //
859
860 int readCompactLen() throws IOException {
861 int[] portion = new int[3];
862 portion[0] = readU8();
863 int byteCount = 1;
864 int len = portion[0] & 0x7F;
865 if ((portion[0] & 0x80) != 0) {
866 portion[1] = readU8();
867 byteCount++;
868 len |= (portion[1] & 0x7F) << 7;
869 if ((portion[1] & 0x80) != 0) {
870 portion[2] = readU8();
871 byteCount++;
872 len |= (portion[2] & 0xFF) << 14;
873 }
874 }
875
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000876 return len;
877 }
878
879
880 //
881 // Write a FramebufferUpdateRequest message
882 //
883
884 void writeFramebufferUpdateRequest(int x, int y, int w, int h,
885 boolean incremental)
886 throws IOException
887 {
888 byte[] b = new byte[10];
889
890 b[0] = (byte) FramebufferUpdateRequest;
891 b[1] = (byte) (incremental ? 1 : 0);
892 b[2] = (byte) ((x >> 8) & 0xff);
893 b[3] = (byte) (x & 0xff);
894 b[4] = (byte) ((y >> 8) & 0xff);
895 b[5] = (byte) (y & 0xff);
896 b[6] = (byte) ((w >> 8) & 0xff);
897 b[7] = (byte) (w & 0xff);
898 b[8] = (byte) ((h >> 8) & 0xff);
899 b[9] = (byte) (h & 0xff);
900
901 os.write(b);
902 }
903
904
905 //
906 // Write a SetPixelFormat message
907 //
908
909 void writeSetPixelFormat(int bitsPerPixel, int depth, boolean bigEndian,
910 boolean trueColour,
911 int redMax, int greenMax, int blueMax,
912 int redShift, int greenShift, int blueShift)
913 throws IOException
914 {
915 byte[] b = new byte[20];
916
917 b[0] = (byte) SetPixelFormat;
918 b[4] = (byte) bitsPerPixel;
919 b[5] = (byte) depth;
920 b[6] = (byte) (bigEndian ? 1 : 0);
921 b[7] = (byte) (trueColour ? 1 : 0);
922 b[8] = (byte) ((redMax >> 8) & 0xff);
923 b[9] = (byte) (redMax & 0xff);
924 b[10] = (byte) ((greenMax >> 8) & 0xff);
925 b[11] = (byte) (greenMax & 0xff);
926 b[12] = (byte) ((blueMax >> 8) & 0xff);
927 b[13] = (byte) (blueMax & 0xff);
928 b[14] = (byte) redShift;
929 b[15] = (byte) greenShift;
930 b[16] = (byte) blueShift;
931
932 os.write(b);
933 }
934
935
936 //
937 // Write a FixColourMapEntries message. The values in the red, green and
938 // blue arrays are from 0 to 65535.
939 //
940
941 void writeFixColourMapEntries(int firstColour, int nColours,
942 int[] red, int[] green, int[] blue)
943 throws IOException
944 {
945 byte[] b = new byte[6 + nColours * 6];
946
947 b[0] = (byte) FixColourMapEntries;
948 b[2] = (byte) ((firstColour >> 8) & 0xff);
949 b[3] = (byte) (firstColour & 0xff);
950 b[4] = (byte) ((nColours >> 8) & 0xff);
951 b[5] = (byte) (nColours & 0xff);
952
953 for (int i = 0; i < nColours; i++) {
954 b[6 + i * 6] = (byte) ((red[i] >> 8) & 0xff);
955 b[6 + i * 6 + 1] = (byte) (red[i] & 0xff);
956 b[6 + i * 6 + 2] = (byte) ((green[i] >> 8) & 0xff);
957 b[6 + i * 6 + 3] = (byte) (green[i] & 0xff);
958 b[6 + i * 6 + 4] = (byte) ((blue[i] >> 8) & 0xff);
959 b[6 + i * 6 + 5] = (byte) (blue[i] & 0xff);
960 }
enikey2f0294e2008-12-24 08:18:54 +0000961
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000962 os.write(b);
963 }
964
965
966 //
967 // Write a SetEncodings message
968 //
969
970 void writeSetEncodings(int[] encs, int len) throws IOException {
971 byte[] b = new byte[4 + 4 * len];
972
973 b[0] = (byte) SetEncodings;
974 b[2] = (byte) ((len >> 8) & 0xff);
975 b[3] = (byte) (len & 0xff);
976
977 for (int i = 0; i < len; i++) {
978 b[4 + 4 * i] = (byte) ((encs[i] >> 24) & 0xff);
979 b[5 + 4 * i] = (byte) ((encs[i] >> 16) & 0xff);
980 b[6 + 4 * i] = (byte) ((encs[i] >> 8) & 0xff);
981 b[7 + 4 * i] = (byte) (encs[i] & 0xff);
982 }
983
984 os.write(b);
985 }
986
987
988 //
989 // Write a ClientCutText message
990 //
991
992 void writeClientCutText(String text) throws IOException {
993 byte[] b = new byte[8 + text.length()];
994
995 b[0] = (byte) ClientCutText;
996 b[4] = (byte) ((text.length() >> 24) & 0xff);
997 b[5] = (byte) ((text.length() >> 16) & 0xff);
998 b[6] = (byte) ((text.length() >> 8) & 0xff);
999 b[7] = (byte) (text.length() & 0xff);
1000
1001 System.arraycopy(text.getBytes(), 0, b, 8, text.length());
1002
1003 os.write(b);
1004 }
1005
1006
1007 //
1008 // A buffer for putting pointer and keyboard events before being sent. This
enikey2f0294e2008-12-24 08:18:54 +00001009 // is to ensure that multiple RFB events generated from a single Java Event
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001010 // will all be sent in a single network packet. The maximum possible
1011 // length is 4 modifier down events, a single key event followed by 4
1012 // modifier up events i.e. 9 key events or 72 bytes.
1013 //
1014
1015 byte[] eventBuf = new byte[72];
1016 int eventBufLen;
1017
1018
1019 // Useful shortcuts for modifier masks.
1020
1021 final static int CTRL_MASK = InputEvent.CTRL_MASK;
1022 final static int SHIFT_MASK = InputEvent.SHIFT_MASK;
1023 final static int META_MASK = InputEvent.META_MASK;
1024 final static int ALT_MASK = InputEvent.ALT_MASK;
1025
1026
1027 //
1028 // Write a pointer event message. We may need to send modifier key events
1029 // around it to set the correct modifier state.
1030 //
1031
1032 int pointerMask = 0;
1033
1034 void writePointerEvent(MouseEvent evt) throws IOException {
1035 int modifiers = evt.getModifiers();
1036
1037 int mask2 = 2;
1038 int mask3 = 4;
1039 if (viewer.options.reverseMouseButtons2And3) {
1040 mask2 = 4;
1041 mask3 = 2;
1042 }
1043
1044 // Note: For some reason, AWT does not set BUTTON1_MASK on left
1045 // button presses. Here we think that it was the left button if
1046 // modifiers do not include BUTTON2_MASK or BUTTON3_MASK.
1047
1048 if (evt.getID() == MouseEvent.MOUSE_PRESSED) {
1049 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1050 pointerMask = mask2;
1051 modifiers &= ~ALT_MASK;
1052 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1053 pointerMask = mask3;
1054 modifiers &= ~META_MASK;
1055 } else {
1056 pointerMask = 1;
1057 }
1058 } else if (evt.getID() == MouseEvent.MOUSE_RELEASED) {
1059 pointerMask = 0;
1060 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1061 modifiers &= ~ALT_MASK;
1062 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1063 modifiers &= ~META_MASK;
1064 }
1065 }
1066
1067 eventBufLen = 0;
1068 writeModifierKeyEvents(modifiers);
1069
1070 int x = evt.getX();
1071 int y = evt.getY();
1072
1073 if (x < 0) x = 0;
1074 if (y < 0) y = 0;
1075
1076 eventBuf[eventBufLen++] = (byte) PointerEvent;
1077 eventBuf[eventBufLen++] = (byte) pointerMask;
1078 eventBuf[eventBufLen++] = (byte) ((x >> 8) & 0xff);
1079 eventBuf[eventBufLen++] = (byte) (x & 0xff);
1080 eventBuf[eventBufLen++] = (byte) ((y >> 8) & 0xff);
1081 eventBuf[eventBufLen++] = (byte) (y & 0xff);
1082
1083 //
1084 // Always release all modifiers after an "up" event
1085 //
1086
1087 if (pointerMask == 0) {
1088 writeModifierKeyEvents(0);
1089 }
1090
1091 os.write(eventBuf, 0, eventBufLen);
1092 }
1093
1094
1095 //
1096 // Write a key event message. We may need to send modifier key events
1097 // around it to set the correct modifier state. Also we need to translate
1098 // from the Java key values to the X keysym values used by the RFB protocol.
1099 //
1100
1101 void writeKeyEvent(KeyEvent evt) throws IOException {
1102
1103 int keyChar = evt.getKeyChar();
1104
1105 //
1106 // Ignore event if only modifiers were pressed.
1107 //
1108
1109 // Some JVMs return 0 instead of CHAR_UNDEFINED in getKeyChar().
1110 if (keyChar == 0)
1111 keyChar = KeyEvent.CHAR_UNDEFINED;
1112
1113 if (keyChar == KeyEvent.CHAR_UNDEFINED) {
1114 int code = evt.getKeyCode();
1115 if (code == KeyEvent.VK_CONTROL || code == KeyEvent.VK_SHIFT ||
1116 code == KeyEvent.VK_META || code == KeyEvent.VK_ALT)
1117 return;
1118 }
1119
1120 //
1121 // Key press or key release?
1122 //
1123
1124 boolean down = (evt.getID() == KeyEvent.KEY_PRESSED);
1125
1126 int key;
1127 if (evt.isActionKey()) {
1128
1129 //
1130 // An action key should be one of the following.
1131 // If not then just ignore the event.
1132 //
1133
1134 switch(evt.getKeyCode()) {
1135 case KeyEvent.VK_HOME: key = 0xff50; break;
1136 case KeyEvent.VK_LEFT: key = 0xff51; break;
1137 case KeyEvent.VK_UP: key = 0xff52; break;
1138 case KeyEvent.VK_RIGHT: key = 0xff53; break;
1139 case KeyEvent.VK_DOWN: key = 0xff54; break;
1140 case KeyEvent.VK_PAGE_UP: key = 0xff55; break;
1141 case KeyEvent.VK_PAGE_DOWN: key = 0xff56; break;
1142 case KeyEvent.VK_END: key = 0xff57; break;
1143 case KeyEvent.VK_INSERT: key = 0xff63; break;
1144 case KeyEvent.VK_F1: key = 0xffbe; break;
1145 case KeyEvent.VK_F2: key = 0xffbf; break;
1146 case KeyEvent.VK_F3: key = 0xffc0; break;
1147 case KeyEvent.VK_F4: key = 0xffc1; break;
1148 case KeyEvent.VK_F5: key = 0xffc2; break;
1149 case KeyEvent.VK_F6: key = 0xffc3; break;
1150 case KeyEvent.VK_F7: key = 0xffc4; break;
1151 case KeyEvent.VK_F8: key = 0xffc5; break;
1152 case KeyEvent.VK_F9: key = 0xffc6; break;
1153 case KeyEvent.VK_F10: key = 0xffc7; break;
1154 case KeyEvent.VK_F11: key = 0xffc8; break;
1155 case KeyEvent.VK_F12: key = 0xffc9; break;
1156 default:
1157 return;
1158 }
1159
1160 } else {
1161
1162 //
1163 // A "normal" key press. Ordinary ASCII characters go straight through.
1164 // For CTRL-<letter>, CTRL is sent separately so just send <letter>.
1165 // Backspace, tab, return, escape and delete have special keysyms.
1166 // Anything else we ignore.
1167 //
1168
1169 key = keyChar;
1170
1171 if (key < 0x20) {
1172 if (evt.isControlDown()) {
1173 key += 0x60;
1174 } else {
1175 switch(key) {
1176 case KeyEvent.VK_BACK_SPACE: key = 0xff08; break;
1177 case KeyEvent.VK_TAB: key = 0xff09; break;
1178 case KeyEvent.VK_ENTER: key = 0xff0d; break;
1179 case KeyEvent.VK_ESCAPE: key = 0xff1b; break;
1180 }
1181 }
1182 } else if (key == 0x7f) {
1183 // Delete
1184 key = 0xffff;
1185 } else if (key > 0xff) {
1186 // JDK1.1 on X incorrectly passes some keysyms straight through,
1187 // so we do too. JDK1.1.4 seems to have fixed this.
1188 // The keysyms passed are 0xff00 .. XK_BackSpace .. XK_Delete
1189 // Also, we pass through foreign currency keysyms (0x20a0..0x20af).
1190 if ((key < 0xff00 || key > 0xffff) &&
1191 !(key >= 0x20a0 && key <= 0x20af))
1192 return;
1193 }
1194 }
1195
1196 // Fake keyPresses for keys that only generates keyRelease events
1197 if ((key == 0xe5) || (key == 0xc5) || // XK_aring / XK_Aring
1198 (key == 0xe4) || (key == 0xc4) || // XK_adiaeresis / XK_Adiaeresis
1199 (key == 0xf6) || (key == 0xd6) || // XK_odiaeresis / XK_Odiaeresis
1200 (key == 0xa7) || (key == 0xbd) || // XK_section / XK_onehalf
1201 (key == 0xa3)) { // XK_sterling
1202 // Make sure we do not send keypress events twice on platforms
1203 // with correct JVMs (those that actually report KeyPress for all
enikey2f0294e2008-12-24 08:18:54 +00001204 // keys)
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001205 if (down)
1206 brokenKeyPressed = true;
1207
1208 if (!down && !brokenKeyPressed) {
1209 // We've got a release event for this key, but haven't received
enikey2f0294e2008-12-24 08:18:54 +00001210 // a press. Fake it.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001211 eventBufLen = 0;
1212 writeModifierKeyEvents(evt.getModifiers());
1213 writeKeyEvent(key, true);
1214 os.write(eventBuf, 0, eventBufLen);
1215 }
1216
1217 if (!down)
enikey2f0294e2008-12-24 08:18:54 +00001218 brokenKeyPressed = false;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001219 }
1220
1221 eventBufLen = 0;
1222 writeModifierKeyEvents(evt.getModifiers());
1223 writeKeyEvent(key, down);
1224
1225 // Always release all modifiers after an "up" event
1226 if (!down)
1227 writeModifierKeyEvents(0);
1228
1229 os.write(eventBuf, 0, eventBufLen);
1230 }
1231
1232
1233 //
1234 // Add a raw key event with the given X keysym to eventBuf.
1235 //
1236
1237 void writeKeyEvent(int keysym, boolean down) {
1238 eventBuf[eventBufLen++] = (byte) KeyboardEvent;
1239 eventBuf[eventBufLen++] = (byte) (down ? 1 : 0);
1240 eventBuf[eventBufLen++] = (byte) 0;
1241 eventBuf[eventBufLen++] = (byte) 0;
1242 eventBuf[eventBufLen++] = (byte) ((keysym >> 24) & 0xff);
1243 eventBuf[eventBufLen++] = (byte) ((keysym >> 16) & 0xff);
1244 eventBuf[eventBufLen++] = (byte) ((keysym >> 8) & 0xff);
1245 eventBuf[eventBufLen++] = (byte) (keysym & 0xff);
1246 }
1247
1248
1249 //
1250 // Write key events to set the correct modifier state.
1251 //
1252
1253 int oldModifiers = 0;
1254
1255 void writeModifierKeyEvents(int newModifiers) {
1256 if ((newModifiers & CTRL_MASK) != (oldModifiers & CTRL_MASK))
1257 writeKeyEvent(0xffe3, (newModifiers & CTRL_MASK) != 0);
1258
1259 if ((newModifiers & SHIFT_MASK) != (oldModifiers & SHIFT_MASK))
1260 writeKeyEvent(0xffe1, (newModifiers & SHIFT_MASK) != 0);
1261
1262 if ((newModifiers & META_MASK) != (oldModifiers & META_MASK))
1263 writeKeyEvent(0xffe7, (newModifiers & META_MASK) != 0);
1264
1265 if ((newModifiers & ALT_MASK) != (oldModifiers & ALT_MASK))
1266 writeKeyEvent(0xffe9, (newModifiers & ALT_MASK) != 0);
1267
1268 oldModifiers = newModifiers;
1269 }
1270
1271
1272 //
1273 // Enable continuous updates for the specified area of the screen (but
1274 // only if EnableContinuousUpdates message is supported by the server).
1275 //
1276
1277 void tryEnableContinuousUpdates(int x, int y, int w, int h)
1278 throws IOException
1279 {
1280 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1281 System.out.println("Continuous updates not supported by the server");
1282 return;
1283 }
1284
1285 if (continuousUpdatesActive) {
1286 System.out.println("Continuous updates already active");
1287 return;
1288 }
1289
1290 byte[] b = new byte[10];
1291
1292 b[0] = (byte) EnableContinuousUpdates;
1293 b[1] = (byte) 1; // enable
1294 b[2] = (byte) ((x >> 8) & 0xff);
1295 b[3] = (byte) (x & 0xff);
1296 b[4] = (byte) ((y >> 8) & 0xff);
1297 b[5] = (byte) (y & 0xff);
1298 b[6] = (byte) ((w >> 8) & 0xff);
1299 b[7] = (byte) (w & 0xff);
1300 b[8] = (byte) ((h >> 8) & 0xff);
1301 b[9] = (byte) (h & 0xff);
1302
1303 os.write(b);
1304
1305 continuousUpdatesActive = true;
1306 System.out.println("Continuous updates activated");
1307 }
1308
1309
1310 //
1311 // Disable continuous updates (only if EnableContinuousUpdates message
1312 // is supported by the server).
1313 //
1314
1315 void tryDisableContinuousUpdates() throws IOException
1316 {
1317 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1318 System.out.println("Continuous updates not supported by the server");
1319 return;
1320 }
1321
1322 if (!continuousUpdatesActive) {
1323 System.out.println("Continuous updates already disabled");
1324 return;
1325 }
1326
1327 if (continuousUpdatesEnding)
1328 return;
1329
1330 byte[] b = { (byte)EnableContinuousUpdates, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1331 os.write(b);
1332
1333 if (!serverMsgCaps.isEnabled(EndOfContinuousUpdates)) {
1334 // If the server did not advertise support for the
1335 // EndOfContinuousUpdates message (should not normally happen
1336 // when EnableContinuousUpdates is supported), then we clear
1337 // 'continuousUpdatesActive' variable immediately. Normally,
1338 // it will be reset on receiving EndOfContinuousUpdates message
1339 // from the server.
1340 continuousUpdatesActive = false;
1341 } else {
1342 // Indicate that we are waiting for EndOfContinuousUpdates.
1343 continuousUpdatesEnding = true;
1344 }
1345 }
1346
1347
1348 //
1349 // Process EndOfContinuousUpdates message received from the server.
1350 //
1351
1352 void endOfContinuousUpdates()
1353 {
1354 continuousUpdatesActive = false;
1355 continuousUpdatesEnding = false;
1356 }
1357
1358
1359 //
1360 // Check if continuous updates are in effect.
1361 //
1362
1363 boolean continuousUpdatesAreActive()
1364 {
1365 return continuousUpdatesActive;
1366 }
1367
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001368 /**
1369 * Send a rectangle selection to be treated as video by the server (but
1370 * only if VideoRectangleSelection message is supported by the server).
1371 * @param rect specifies coordinates and size of the rectangule.
1372 * @throws java.io.IOException
1373 */
1374 void trySendVideoSelection(Rectangle rect) throws IOException
1375 {
1376 if (!clientMsgCaps.isEnabled(VideoRectangleSelection)) {
1377 System.out.println("Video area selection is not supported by the server");
1378 return;
1379 }
1380
Constantin Kaplinsky4f652852008-09-05 02:41:15 +00001381 // Send zero coordinates if the rectangle is empty.
1382 if (rect.isEmpty()) {
1383 rect = new Rectangle();
1384 }
1385
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001386 int x = rect.x;
1387 int y = rect.y;
1388 int w = rect.width;
1389 int h = rect.height;
enikey2f0294e2008-12-24 08:18:54 +00001390
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001391 byte[] b = new byte[10];
1392
1393 b[0] = (byte) VideoRectangleSelection;
1394 b[1] = (byte) 0; // reserved
1395 b[2] = (byte) ((x >> 8) & 0xff);
1396 b[3] = (byte) (x & 0xff);
1397 b[4] = (byte) ((y >> 8) & 0xff);
1398 b[5] = (byte) (y & 0xff);
1399 b[6] = (byte) ((w >> 8) & 0xff);
1400 b[7] = (byte) (w & 0xff);
1401 b[8] = (byte) ((h >> 8) & 0xff);
1402 b[9] = (byte) (h & 0xff);
1403
1404 os.write(b);
1405
1406 System.out.println("Video rectangle selection message sent");
1407 }
1408
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001409 public void startTiming() {
1410 timing = true;
1411
1412 // Carry over up to 1s worth of previous rate for smoothing.
1413
1414 if (timeWaitedIn100us > 10000) {
1415 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
1416 timeWaitedIn100us = 10000;
1417 }
1418 }
1419
1420 public void stopTiming() {
enikey2f0294e2008-12-24 08:18:54 +00001421 timing = false;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001422 if (timeWaitedIn100us < timedKbits/2)
1423 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
1424 }
1425
1426 public long kbitsPerSecond() {
1427 return timedKbits * 10000 / timeWaitedIn100us;
1428 }
1429
1430 public long timeWaited() {
1431 return timeWaitedIn100us;
1432 }
1433
1434 //
1435 // Methods for reading data via our DataInputStream member variable (is).
1436 //
1437 // In addition to reading data, the readFully() methods updates variables
1438 // used to estimate data throughput.
1439 //
1440
1441 public void readFully(byte b[]) throws IOException {
1442 readFully(b, 0, b.length);
1443 }
1444
1445 public void readFully(byte b[], int off, int len) throws IOException {
1446 long before = 0;
1447 if (timing)
1448 before = System.currentTimeMillis();
1449
1450 is.readFully(b, off, len);
1451
1452 if (timing) {
1453 long after = System.currentTimeMillis();
1454 long newTimeWaited = (after - before) * 10;
1455 int newKbits = len * 8 / 1000;
1456
1457 // limit rate to between 10kbit/s and 40Mbit/s
1458
1459 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
1460 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
1461
1462 timeWaitedIn100us += newTimeWaited;
1463 timedKbits += newKbits;
1464 }
1465
1466 numBytesRead += len;
1467 }
1468
1469 final int available() throws IOException {
1470 return is.available();
1471 }
1472
1473 // FIXME: DataInputStream::skipBytes() is not guaranteed to skip
1474 // exactly n bytes. Probably we don't want to use this method.
1475 final int skipBytes(int n) throws IOException {
1476 int r = is.skipBytes(n);
1477 numBytesRead += r;
1478 return r;
1479 }
1480
1481 final int readU8() throws IOException {
1482 int r = is.readUnsignedByte();
1483 numBytesRead++;
1484 return r;
1485 }
1486
1487 final int readU16() throws IOException {
1488 int r = is.readUnsignedShort();
1489 numBytesRead += 2;
1490 return r;
1491 }
1492
1493 final int readU32() throws IOException {
1494 int r = is.readInt();
1495 numBytesRead += 4;
1496 return r;
1497 }
1498}