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