blob: de5c0574724495b254cf3cf0bd42737c55ea6cbd [file] [log] [blame]
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001//
2// Copyright (C) 2004 Horizon Wimba. All Rights Reserved.
3// Copyright (C) 2001-2003 HorizonLive.com, Inc. All Rights Reserved.
4// Copyright (C) 2001,2002 Constantin Kaplinsky. All Rights Reserved.
5// Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
6// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
7//
8// This is free software; you can redistribute it and/or modify
9// it under the terms of the GNU General Public License as published by
10// the Free Software Foundation; either version 2 of the License, or
11// (at your option) any later version.
12//
13// This software is distributed in the hope that it will be useful,
14// but WITHOUT ANY WARRANTY; without even the implied warranty of
15// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16// GNU General Public License for more details.
17//
18// You should have received a copy of the GNU General Public License
19// along with this software; if not, write to the Free Software
20// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
21// USA.
22//
23
Constantin Kaplinsky90d8a502008-04-14 09:45:50 +000024package com.tightvnc.vncviewer;
25
enikeyc41ba1d2008-12-19 09:07:22 +000026import com.tightvnc.decoder.CoRREDecoder;
27import com.tightvnc.decoder.HextileDecoder;
28import com.tightvnc.decoder.RREDecoder;
29import com.tightvnc.decoder.RawDecoder;
30import com.tightvnc.decoder.TightDecoder;
31import com.tightvnc.decoder.ZRLEDecoder;
32import com.tightvnc.decoder.ZlibDecoder;
enikey0dbc1532008-12-19 08:51:47 +000033import com.tightvnc.decoder.common.Repaintable;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000034import java.awt.*;
35import java.awt.event.*;
36import java.awt.image.*;
37import java.io.*;
38import java.lang.*;
39import java.util.zip.*;
40
41
42//
43// VncCanvas is a subclass of Canvas which draws a VNC desktop on it.
44//
45
46class VncCanvas extends Canvas
enikey0dbc1532008-12-19 08:51:47 +000047 implements KeyListener, MouseListener, MouseMotionListener, RecordInterface,
48 Repaintable {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000049
50 VncViewer viewer;
51 RfbProto rfb;
52 ColorModel cm8, cm24;
53 Color[] colors;
54 int bytesPixel;
55
56 int maxWidth = 0, maxHeight = 0;
57 int scalingFactor;
58 int scaledWidth, scaledHeight;
59
60 Image memImage;
61 Graphics memGraphics;
62
63 Image rawPixelsImage;
64 MemoryImageSource pixelsSource;
65 byte[] pixels8;
66 int[] pixels24;
67
enikeyc41ba1d2008-12-19 09:07:22 +000068 //
69 // Decoders
70 //
71
72 RawDecoder rawDecoder;
73 RREDecoder rreDecoder;
74 CoRREDecoder correDecoder;
75 ZlibDecoder zlibDecoder;
76 HextileDecoder hextileDecoder;
77 ZRLEDecoder zrleDecoder;
78 TightDecoder tightDecoder;
79
80 // Base decoder decoders array
81 RawDecoder []decoders = null;
82
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000083 // Update statistics.
84 long statStartTime; // time on first framebufferUpdateRequest
85 int statNumUpdates; // counter for FramebufferUpdate messages
86 int statNumTotalRects; // rectangles in FramebufferUpdate messages
87 int statNumPixelRects; // the same, but excluding pseudo-rectangles
88 int statNumRectsTight; // Tight-encoded rectangles (including JPEG)
89 int statNumRectsTightJPEG; // JPEG-compressed Tight-encoded rectangles
90 int statNumRectsZRLE; // ZRLE-encoded rectangles
91 int statNumRectsHextile; // Hextile-encoded rectangles
92 int statNumRectsRaw; // Raw-encoded rectangles
93 int statNumRectsCopy; // CopyRect rectangles
94 int statNumBytesEncoded; // number of bytes in updates, as received
95 int statNumBytesDecoded; // number of bytes, as if Raw encoding was used
96
97 // ZRLE encoder's data.
98 byte[] zrleBuf;
99 int zrleBufLen = 0;
100 byte[] zrleTilePixels8;
101 int[] zrleTilePixels24;
102 ZlibInStream zrleInStream;
103 boolean zrleRecWarningShown = false;
enikey87647e92008-12-04 08:42:34 +0000104 boolean isFirstSizeAutoUpdate = true;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000105
106 // Zlib encoder's data.
107 byte[] zlibBuf;
108 int zlibBufLen = 0;
109 Inflater zlibInflater;
110
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000111 // True if we process keyboard and mouse events.
112 boolean inputEnabled;
113
114 //
115 // The constructors.
116 //
117
118 public VncCanvas(VncViewer v, int maxWidth_, int maxHeight_)
119 throws IOException {
120
121 viewer = v;
122 maxWidth = maxWidth_;
123 maxHeight = maxHeight_;
124
125 rfb = viewer.rfb;
126 scalingFactor = viewer.options.scalingFactor;
127
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000128 cm8 = new DirectColorModel(8, 7, (7 << 3), (3 << 6));
129 cm24 = new DirectColorModel(24, 0xFF0000, 0x00FF00, 0x0000FF);
130
131 colors = new Color[256];
132 for (int i = 0; i < 256; i++)
133 colors[i] = new Color(cm8.getRGB(i));
134
enikeyc41ba1d2008-12-19 09:07:22 +0000135 //
136 // Create decoders
137 //
138
139 // Input stream for decoders
140 RfbInputStream rfbis = new RfbInputStream(rfb);
141
142 rawDecoder = new RawDecoder(memGraphics, rfbis);
143 rreDecoder = new RREDecoder(memGraphics, rfbis);
144 correDecoder = new CoRREDecoder(memGraphics, rfbis);
145 hextileDecoder = new HextileDecoder(memGraphics, rfbis);
146 tightDecoder = new TightDecoder(memGraphics, rfbis);
enikey4582bab2008-12-19 09:19:59 +0000147 zlibDecoder = new ZlibDecoder(memGraphics, rfbis);
enikeyc41ba1d2008-12-19 09:07:22 +0000148 zrleDecoder = new ZRLEDecoder(memGraphics, rfbis);
149
150 //
151 // Set data for decoders that needs extra parameters
152 //
153
154 hextileDecoder.setRepainableControl(this);
155 tightDecoder.setRepainableControl(this);
156
157 //
158 // Create array that contains our decoders
159 //
160
161 decoders = new RawDecoder[7];
162 decoders[0] = rawDecoder;
163 decoders[1] = rreDecoder;
164 decoders[2] = correDecoder;
165 decoders[3] = hextileDecoder;
166 decoders[4] = zlibDecoder;
167 decoders[5] = tightDecoder;
168 decoders[6] = zrleDecoder;
169
170 //
171 // Set session recorder for decoders
172 //
173
174 for (int i = 0; i < decoders.length; i++) {
175 decoders[i].setSessionRecorder(this);
176 }
enikey2f7f46e2008-12-19 09:32:35 +0000177
178 setPixelFormat();
179
180 resetSelection();
181
182 inputEnabled = false;
183 if (!viewer.options.viewOnly)
184 enableInput(true);
enikeyc41ba1d2008-12-19 09:07:22 +0000185
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000186 // Enable mouse and keyboard event listeners.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000187 addKeyListener(this);
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000188 addMouseListener(this);
189 addMouseMotionListener(this);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000190 }
191
192 public VncCanvas(VncViewer v) throws IOException {
193 this(v, 0, 0);
194 }
195
196 //
197 // Callback methods to determine geometry of our Component.
198 //
199
200 public Dimension getPreferredSize() {
201 return new Dimension(scaledWidth, scaledHeight);
202 }
203
204 public Dimension getMinimumSize() {
205 return new Dimension(scaledWidth, scaledHeight);
206 }
207
208 public Dimension getMaximumSize() {
209 return new Dimension(scaledWidth, scaledHeight);
210 }
211
212 //
213 // All painting is performed here.
214 //
215
216 public void update(Graphics g) {
217 paint(g);
218 }
219
220 public void paint(Graphics g) {
221 synchronized(memImage) {
222 if (rfb.framebufferWidth == scaledWidth) {
223 g.drawImage(memImage, 0, 0, null);
224 } else {
225 paintScaledFrameBuffer(g);
226 }
227 }
228 if (showSoftCursor) {
229 int x0 = cursorX - hotX, y0 = cursorY - hotY;
230 Rectangle r = new Rectangle(x0, y0, cursorWidth, cursorHeight);
231 if (r.intersects(g.getClipBounds())) {
232 g.drawImage(softCursor, x0, y0, null);
233 }
234 }
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000235 if (isInSelectionMode()) {
236 Rectangle r = getSelection(true);
237 if (r.width > 0 && r.height > 0) {
238 // Don't forget to correct the coordinates for the right and bottom
239 // borders, so that the borders are the part of the selection.
240 r.width -= 1;
241 r.height -= 1;
242 g.setXORMode(Color.yellow);
243 g.drawRect(r.x, r.y, r.width, r.height);
244 }
245 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000246 }
247
248 public void paintScaledFrameBuffer(Graphics g) {
249 g.drawImage(memImage, 0, 0, scaledWidth, scaledHeight, null);
250 }
251
252 //
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000253 // Start/stop receiving mouse events. Keyboard events are received
254 // even in view-only mode, because we want to map the 'r' key to the
255 // screen refreshing function.
256 //
257
258 public synchronized void enableInput(boolean enable) {
259 if (enable && !inputEnabled) {
260 inputEnabled = true;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000261 if (viewer.showControls) {
262 viewer.buttonPanel.enableRemoteAccessControls(true);
263 }
264 createSoftCursor(); // scaled cursor
265 } else if (!enable && inputEnabled) {
266 inputEnabled = false;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000267 if (viewer.showControls) {
268 viewer.buttonPanel.enableRemoteAccessControls(false);
269 }
270 createSoftCursor(); // non-scaled cursor
271 }
272 }
273
274 public void setPixelFormat() throws IOException {
275 if (viewer.options.eightBitColors) {
276 rfb.writeSetPixelFormat(8, 8, false, true, 7, 7, 3, 0, 3, 6);
277 bytesPixel = 1;
278 } else {
279 rfb.writeSetPixelFormat(32, 24, false, true, 255, 255, 255, 16, 8, 0);
280 bytesPixel = 4;
281 }
282 updateFramebufferSize();
283 }
284
enikey45cfaa52008-12-03 06:52:09 +0000285 void setScalingFactor(int sf) {
286 scalingFactor = sf;
287 updateFramebufferSize();
288 invalidate();
289 }
290
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000291 void updateFramebufferSize() {
292
293 // Useful shortcuts.
294 int fbWidth = rfb.framebufferWidth;
295 int fbHeight = rfb.framebufferHeight;
296
enikey87647e92008-12-04 08:42:34 +0000297 // FIXME: This part of code must be in VncViewer i think
enikey73683202008-12-03 09:17:25 +0000298 if (viewer.options.autoScale) {
enikey87647e92008-12-04 08:42:34 +0000299 if (viewer.inAnApplet) {
300 maxWidth = viewer.getWidth();
301 maxHeight = viewer.getHeight();
302 } else {
303 if (viewer.vncFrame != null) {
304 if (isFirstSizeAutoUpdate) {
305 isFirstSizeAutoUpdate = false;
306 Dimension screenSize = viewer.vncFrame.getToolkit().getScreenSize();
307 maxWidth = (int)screenSize.getWidth() - 100;
enikeyc41ba1d2008-12-19 09:07:22 +0000308 maxHeight = (int)screenSize.getHeight() - 100;
enikey87647e92008-12-04 08:42:34 +0000309 viewer.vncFrame.setSize(maxWidth, maxHeight);
310 } else {
311 viewer.desktopScrollPane.doLayout();
312 maxWidth = viewer.desktopScrollPane.getWidth();
313 maxHeight = viewer.desktopScrollPane.getHeight();
314 }
315 } else {
316 maxWidth = fbWidth;
317 maxHeight = fbHeight;
318 }
enikey73683202008-12-03 09:17:25 +0000319 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000320 int f1 = maxWidth * 100 / fbWidth;
321 int f2 = maxHeight * 100 / fbHeight;
322 scalingFactor = Math.min(f1, f2);
323 if (scalingFactor > 100)
324 scalingFactor = 100;
325 System.out.println("Scaling desktop at " + scalingFactor + "%");
326 }
327
328 // Update scaled framebuffer geometry.
329 scaledWidth = (fbWidth * scalingFactor + 50) / 100;
330 scaledHeight = (fbHeight * scalingFactor + 50) / 100;
331
332 // Create new off-screen image either if it does not exist, or if
333 // its geometry should be changed. It's not necessary to replace
334 // existing image if only pixel format should be changed.
335 if (memImage == null) {
336 memImage = viewer.vncContainer.createImage(fbWidth, fbHeight);
337 memGraphics = memImage.getGraphics();
338 } else if (memImage.getWidth(null) != fbWidth ||
339 memImage.getHeight(null) != fbHeight) {
340 synchronized(memImage) {
341 memImage = viewer.vncContainer.createImage(fbWidth, fbHeight);
342 memGraphics = memImage.getGraphics();
343 }
344 }
345
enikey4582bab2008-12-19 09:19:59 +0000346 //
347 // Update decoders
348 //
349
350 //
351 // FIXME: Why decoders can be null here?
352 //
353
354 if (decoders != null) {
355 for (int i = 0; i < decoders.length; i++) {
356 //
357 // Set changes to every decoder that we can use
358 //
359
360 decoders[i].setBPP(bytesPixel);
361 decoders[i].setFrameBufferSize(fbWidth, fbHeight);
362 decoders[i].setGraphics(memGraphics);
363
364 //
365 // Update decoder
366 //
367
368 decoders[i].update();
369 }
370 }
371
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000372 // Images with raw pixels should be re-allocated on every change
373 // of geometry or pixel format.
374 if (bytesPixel == 1) {
375
376 pixels24 = null;
377 pixels8 = new byte[fbWidth * fbHeight];
378
379 pixelsSource =
380 new MemoryImageSource(fbWidth, fbHeight, cm8, pixels8, 0, fbWidth);
381
382 zrleTilePixels24 = null;
383 zrleTilePixels8 = new byte[64 * 64];
384
385 } else {
386
387 pixels8 = null;
388 pixels24 = new int[fbWidth * fbHeight];
389
390 pixelsSource =
391 new MemoryImageSource(fbWidth, fbHeight, cm24, pixels24, 0, fbWidth);
392
393 zrleTilePixels8 = null;
394 zrleTilePixels24 = new int[64 * 64];
395
396 }
397 pixelsSource.setAnimated(true);
398 rawPixelsImage = Toolkit.getDefaultToolkit().createImage(pixelsSource);
399
enikey87647e92008-12-04 08:42:34 +0000400 // FIXME: This part of code must be in VncViewer i think
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000401 // Update the size of desktop containers.
402 if (viewer.inSeparateFrame) {
enikey87647e92008-12-04 08:42:34 +0000403 if (viewer.desktopScrollPane != null) {
404 if (!viewer.options.autoScale) {
405 resizeDesktopFrame();
406 } else {
407 setSize(scaledWidth, scaledHeight);
408 viewer.desktopScrollPane.setSize(maxWidth + 200,
409 maxHeight + 200);
410 }
411 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000412 } else {
413 setSize(scaledWidth, scaledHeight);
414 }
415 viewer.moveFocusToDesktop();
416 }
417
418 void resizeDesktopFrame() {
419 setSize(scaledWidth, scaledHeight);
420
421 // FIXME: Find a better way to determine correct size of a
422 // ScrollPane. -- const
423 Insets insets = viewer.desktopScrollPane.getInsets();
424 viewer.desktopScrollPane.setSize(scaledWidth +
425 2 * Math.min(insets.left, insets.right),
426 scaledHeight +
427 2 * Math.min(insets.top, insets.bottom));
428
429 viewer.vncFrame.pack();
430
431 // Try to limit the frame size to the screen size.
432
433 Dimension screenSize = viewer.vncFrame.getToolkit().getScreenSize();
434 Dimension frameSize = viewer.vncFrame.getSize();
435 Dimension newSize = frameSize;
436
437 // Reduce Screen Size by 30 pixels in each direction;
438 // This is a (poor) attempt to account for
439 // 1) Menu bar on Macintosh (should really also account for
440 // Dock on OSX). Usually 22px on top of screen.
441 // 2) Taxkbar on Windows (usually about 28 px on bottom)
442 // 3) Other obstructions.
443
444 screenSize.height -= 30;
445 screenSize.width -= 30;
446
447 boolean needToResizeFrame = false;
448 if (frameSize.height > screenSize.height) {
449 newSize.height = screenSize.height;
450 needToResizeFrame = true;
451 }
452 if (frameSize.width > screenSize.width) {
453 newSize.width = screenSize.width;
454 needToResizeFrame = true;
455 }
456 if (needToResizeFrame) {
457 viewer.vncFrame.setSize(newSize);
458 }
459
460 viewer.desktopScrollPane.doLayout();
461 }
462
463 //
464 // processNormalProtocol() - executed by the rfbThread to deal with the
465 // RFB socket.
466 //
467
468 public void processNormalProtocol() throws Exception {
469
470 // Start/stop session recording if necessary.
471 viewer.checkRecordingStatus();
472
473 rfb.writeFramebufferUpdateRequest(0, 0, rfb.framebufferWidth,
474 rfb.framebufferHeight, false);
475
476 if (viewer.options.continuousUpdates) {
477 rfb.tryEnableContinuousUpdates(0, 0, rfb.framebufferWidth,
478 rfb.framebufferHeight);
479 }
480
481 resetStats();
482 boolean statsRestarted = false;
483
484 //
485 // main dispatch loop
486 //
487
488 while (true) {
489
490 // Read message type from the server.
491 int msgType = rfb.readServerMessageType();
492
493 // Process the message depending on its type.
494 switch (msgType) {
495 case RfbProto.FramebufferUpdate:
496
497 if (statNumUpdates == viewer.debugStatsExcludeUpdates &&
498 !statsRestarted) {
499 resetStats();
500 statsRestarted = true;
501 } else if (statNumUpdates == viewer.debugStatsMeasureUpdates &&
502 statsRestarted) {
503 viewer.disconnect();
504 }
505
506 rfb.readFramebufferUpdate();
507 statNumUpdates++;
508
509 boolean cursorPosReceived = false;
510
511 for (int i = 0; i < rfb.updateNRects; i++) {
512
513 rfb.readFramebufferUpdateRectHdr();
514 statNumTotalRects++;
515 int rx = rfb.updateRectX, ry = rfb.updateRectY;
516 int rw = rfb.updateRectW, rh = rfb.updateRectH;
517
518 if (rfb.updateRectEncoding == rfb.EncodingLastRect)
519 break;
520
521 if (rfb.updateRectEncoding == rfb.EncodingNewFBSize) {
522 rfb.setFramebufferSize(rw, rh);
523 updateFramebufferSize();
524 break;
525 }
526
527 if (rfb.updateRectEncoding == rfb.EncodingXCursor ||
528 rfb.updateRectEncoding == rfb.EncodingRichCursor) {
529 handleCursorShapeUpdate(rfb.updateRectEncoding, rx, ry, rw, rh);
530 continue;
531 }
532
533 if (rfb.updateRectEncoding == rfb.EncodingPointerPos) {
534 softCursorMove(rx, ry);
535 cursorPosReceived = true;
536 continue;
537 }
538
539 long numBytesReadBefore = rfb.getNumBytesRead();
540
541 rfb.startTiming();
542
543 switch (rfb.updateRectEncoding) {
544 case RfbProto.EncodingRaw:
545 statNumRectsRaw++;
546 handleRawRect(rx, ry, rw, rh);
547 break;
548 case RfbProto.EncodingCopyRect:
549 statNumRectsCopy++;
550 handleCopyRect(rx, ry, rw, rh);
551 break;
552 case RfbProto.EncodingRRE:
553 handleRRERect(rx, ry, rw, rh);
554 break;
555 case RfbProto.EncodingCoRRE:
556 handleCoRRERect(rx, ry, rw, rh);
557 break;
558 case RfbProto.EncodingHextile:
559 statNumRectsHextile++;
560 handleHextileRect(rx, ry, rw, rh);
561 break;
562 case RfbProto.EncodingZRLE:
563 statNumRectsZRLE++;
564 handleZRLERect(rx, ry, rw, rh);
565 break;
566 case RfbProto.EncodingZlib:
567 handleZlibRect(rx, ry, rw, rh);
568 break;
569 case RfbProto.EncodingTight:
enikey2f7f46e2008-12-19 09:32:35 +0000570 if (tightDecoder != null) {
enikey479b18c2008-12-19 09:39:40 +0000571 statNumRectsTightJPEG = tightDecoder.getNumJPEGRects();
enikey2f7f46e2008-12-19 09:32:35 +0000572 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000573 handleTightRect(rx, ry, rw, rh);
574 break;
575 default:
576 throw new Exception("Unknown RFB rectangle encoding " +
577 rfb.updateRectEncoding);
578 }
579
580 rfb.stopTiming();
581
582 statNumPixelRects++;
583 statNumBytesDecoded += rw * rh * bytesPixel;
584 statNumBytesEncoded +=
585 (int)(rfb.getNumBytesRead() - numBytesReadBefore);
586 }
587
588 boolean fullUpdateNeeded = false;
589
590 // Start/stop session recording if necessary. Request full
591 // update if a new session file was opened.
592 if (viewer.checkRecordingStatus())
593 fullUpdateNeeded = true;
594
595 // Defer framebuffer update request if necessary. But wake up
596 // immediately on keyboard or mouse event. Also, don't sleep
597 // if there is some data to receive, or if the last update
598 // included a PointerPos message.
599 if (viewer.deferUpdateRequests > 0 &&
600 rfb.available() == 0 && !cursorPosReceived) {
601 synchronized(rfb) {
602 try {
603 rfb.wait(viewer.deferUpdateRequests);
604 } catch (InterruptedException e) {
605 }
606 }
607 }
608
609 viewer.autoSelectEncodings();
610
611 // Before requesting framebuffer update, check if the pixel
612 // format should be changed.
613 if (viewer.options.eightBitColors != (bytesPixel == 1)) {
614 // Pixel format should be changed.
615 if (!rfb.continuousUpdatesAreActive()) {
616 // Continuous updates are not used. In this case, we just
617 // set new pixel format and request full update.
618 setPixelFormat();
619 fullUpdateNeeded = true;
620 } else {
621 // Otherwise, disable continuous updates first. Pixel
622 // format will be set later when we are sure that there
623 // will be no unsolicited framebuffer updates.
624 rfb.tryDisableContinuousUpdates();
625 break; // skip the code below
626 }
627 }
628
629 // Enable/disable continuous updates to reflect the GUI setting.
630 boolean enable = viewer.options.continuousUpdates;
631 if (enable != rfb.continuousUpdatesAreActive()) {
632 if (enable) {
633 rfb.tryEnableContinuousUpdates(0, 0, rfb.framebufferWidth,
634 rfb.framebufferHeight);
635 } else {
636 rfb.tryDisableContinuousUpdates();
637 }
638 }
639
640 // Finally, request framebuffer update if needed.
641 if (fullUpdateNeeded) {
642 rfb.writeFramebufferUpdateRequest(0, 0, rfb.framebufferWidth,
643 rfb.framebufferHeight, false);
644 } else if (!rfb.continuousUpdatesAreActive()) {
645 rfb.writeFramebufferUpdateRequest(0, 0, rfb.framebufferWidth,
646 rfb.framebufferHeight, true);
647 }
648
649 break;
650
651 case RfbProto.SetColourMapEntries:
652 throw new Exception("Can't handle SetColourMapEntries message");
653
654 case RfbProto.Bell:
655 Toolkit.getDefaultToolkit().beep();
656 break;
657
658 case RfbProto.ServerCutText:
659 String s = rfb.readServerCutText();
660 viewer.clipboard.setCutText(s);
661 break;
662
663 case RfbProto.EndOfContinuousUpdates:
664 if (rfb.continuousUpdatesAreActive()) {
665 rfb.endOfContinuousUpdates();
666
667 // Change pixel format if such change was pending. Note that we
668 // could not change pixel format while continuous updates were
669 // in effect.
670 boolean incremental = true;
671 if (viewer.options.eightBitColors != (bytesPixel == 1)) {
672 setPixelFormat();
673 incremental = false;
674 }
675 // From this point, we ask for updates explicitly.
676 rfb.writeFramebufferUpdateRequest(0, 0, rfb.framebufferWidth,
677 rfb.framebufferHeight,
678 incremental);
679 }
680 break;
681
682 default:
683 throw new Exception("Unknown RFB message type " + msgType);
684 }
685 }
686 }
687
688
689 //
690 // Handle a raw rectangle. The second form with paint==false is used
691 // by the Hextile decoder for raw-encoded tiles.
692 //
693
enikey6c72ce12008-12-19 09:47:14 +0000694 void handleRawRect(int x, int y, int w, int h) throws IOException, Exception {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000695 handleRawRect(x, y, w, h, true);
696 }
697
698 void handleRawRect(int x, int y, int w, int h, boolean paint)
enikey6c72ce12008-12-19 09:47:14 +0000699 throws IOException , Exception{
700 rawDecoder.handleRect(x, y, w, h);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000701 if (paint)
702 scheduleRepaint(x, y, w, h);
703 }
704
705 //
706 // Handle a CopyRect rectangle.
707 //
708
709 void handleCopyRect(int x, int y, int w, int h) throws IOException {
710
711 rfb.readCopyRect();
712 memGraphics.copyArea(rfb.copyRectSrcX, rfb.copyRectSrcY, w, h,
713 x - rfb.copyRectSrcX, y - rfb.copyRectSrcY);
714
715 scheduleRepaint(x, y, w, h);
716 }
717
718 //
719 // Handle an RRE-encoded rectangle.
720 //
721
722 void handleRRERect(int x, int y, int w, int h) throws IOException {
enikey6c72ce12008-12-19 09:47:14 +0000723 rreDecoder.handleRect(x, y, w, h);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000724 scheduleRepaint(x, y, w, h);
725 }
726
727 //
728 // Handle a CoRRE-encoded rectangle.
729 //
730
731 void handleCoRRERect(int x, int y, int w, int h) throws IOException {
enikey6c72ce12008-12-19 09:47:14 +0000732 correDecoder.handleRect(x, y, w, h);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000733 scheduleRepaint(x, y, w, h);
734 }
735
736 //
737 // Handle a Hextile-encoded rectangle.
738 //
739
740 // These colors should be kept between handleHextileSubrect() calls.
741 private Color hextile_bg, hextile_fg;
742
enikey6c72ce12008-12-19 09:47:14 +0000743 void handleHextileRect(int x, int y, int w, int h) throws IOException,
744 Exception {
745 hextileDecoder.handleRect(x, y, w, h);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000746 }
747
748 //
749 // Handle one tile in the Hextile-encoded data.
750 //
751
752 void handleHextileSubrect(int tx, int ty, int tw, int th)
enikey6c72ce12008-12-19 09:47:14 +0000753 throws IOException, Exception {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000754
755 int subencoding = rfb.readU8();
756 if (rfb.rec != null) {
757 rfb.rec.writeByte(subencoding);
758 }
759
760 // Is it a raw-encoded sub-rectangle?
761 if ((subencoding & rfb.HextileRaw) != 0) {
762 handleRawRect(tx, ty, tw, th, false);
763 return;
764 }
765
766 // Read and draw the background if specified.
767 byte[] cbuf = new byte[bytesPixel];
768 if ((subencoding & rfb.HextileBackgroundSpecified) != 0) {
769 rfb.readFully(cbuf);
770 if (bytesPixel == 1) {
771 hextile_bg = colors[cbuf[0] & 0xFF];
772 } else {
773 hextile_bg = new Color(cbuf[2] & 0xFF, cbuf[1] & 0xFF, cbuf[0] & 0xFF);
774 }
775 if (rfb.rec != null) {
776 rfb.rec.write(cbuf);
777 }
778 }
779 memGraphics.setColor(hextile_bg);
780 memGraphics.fillRect(tx, ty, tw, th);
781
782 // Read the foreground color if specified.
783 if ((subencoding & rfb.HextileForegroundSpecified) != 0) {
784 rfb.readFully(cbuf);
785 if (bytesPixel == 1) {
786 hextile_fg = colors[cbuf[0] & 0xFF];
787 } else {
788 hextile_fg = new Color(cbuf[2] & 0xFF, cbuf[1] & 0xFF, cbuf[0] & 0xFF);
789 }
790 if (rfb.rec != null) {
791 rfb.rec.write(cbuf);
792 }
793 }
794
795 // Done with this tile if there is no sub-rectangles.
796 if ((subencoding & rfb.HextileAnySubrects) == 0)
797 return;
798
799 int nSubrects = rfb.readU8();
800 int bufsize = nSubrects * 2;
801 if ((subencoding & rfb.HextileSubrectsColoured) != 0) {
802 bufsize += nSubrects * bytesPixel;
803 }
804 byte[] buf = new byte[bufsize];
805 rfb.readFully(buf);
806 if (rfb.rec != null) {
807 rfb.rec.writeByte(nSubrects);
808 rfb.rec.write(buf);
809 }
810
811 int b1, b2, sx, sy, sw, sh;
812 int i = 0;
813
814 if ((subencoding & rfb.HextileSubrectsColoured) == 0) {
815
816 // Sub-rectangles are all of the same color.
817 memGraphics.setColor(hextile_fg);
818 for (int j = 0; j < nSubrects; j++) {
819 b1 = buf[i++] & 0xFF;
820 b2 = buf[i++] & 0xFF;
821 sx = tx + (b1 >> 4);
822 sy = ty + (b1 & 0xf);
823 sw = (b2 >> 4) + 1;
824 sh = (b2 & 0xf) + 1;
825 memGraphics.fillRect(sx, sy, sw, sh);
826 }
827 } else if (bytesPixel == 1) {
828
829 // BGR233 (8-bit color) version for colored sub-rectangles.
830 for (int j = 0; j < nSubrects; j++) {
831 hextile_fg = colors[buf[i++] & 0xFF];
832 b1 = buf[i++] & 0xFF;
833 b2 = buf[i++] & 0xFF;
834 sx = tx + (b1 >> 4);
835 sy = ty + (b1 & 0xf);
836 sw = (b2 >> 4) + 1;
837 sh = (b2 & 0xf) + 1;
838 memGraphics.setColor(hextile_fg);
839 memGraphics.fillRect(sx, sy, sw, sh);
840 }
841
842 } else {
843
844 // Full-color (24-bit) version for colored sub-rectangles.
845 for (int j = 0; j < nSubrects; j++) {
846 hextile_fg = new Color(buf[i+2] & 0xFF,
847 buf[i+1] & 0xFF,
848 buf[i] & 0xFF);
849 i += 4;
850 b1 = buf[i++] & 0xFF;
851 b2 = buf[i++] & 0xFF;
852 sx = tx + (b1 >> 4);
853 sy = ty + (b1 & 0xf);
854 sw = (b2 >> 4) + 1;
855 sh = (b2 & 0xf) + 1;
856 memGraphics.setColor(hextile_fg);
857 memGraphics.fillRect(sx, sy, sw, sh);
858 }
859
860 }
861 }
862
863 //
864 // Handle a ZRLE-encoded rectangle.
865 //
866 // FIXME: Currently, session recording is not fully supported for ZRLE.
867 //
868
869 void handleZRLERect(int x, int y, int w, int h) throws Exception {
870
871 if (zrleInStream == null)
872 zrleInStream = new ZlibInStream();
873
874 int nBytes = rfb.readU32();
875 if (nBytes > 64 * 1024 * 1024)
876 throw new Exception("ZRLE decoder: illegal compressed data size");
877
878 if (zrleBuf == null || zrleBufLen < nBytes) {
879 zrleBufLen = nBytes + 4096;
880 zrleBuf = new byte[zrleBufLen];
881 }
882
883 // FIXME: Do not wait for all the data before decompression.
884 rfb.readFully(zrleBuf, 0, nBytes);
885
886 if (rfb.rec != null) {
887 if (rfb.recordFromBeginning) {
888 rfb.rec.writeIntBE(nBytes);
889 rfb.rec.write(zrleBuf, 0, nBytes);
890 } else if (!zrleRecWarningShown) {
891 System.out.println("Warning: ZRLE session can be recorded" +
892 " only from the beginning");
893 System.out.println("Warning: Recorded file may be corrupted");
894 zrleRecWarningShown = true;
895 }
896 }
897
898 zrleInStream.setUnderlying(new MemInStream(zrleBuf, 0, nBytes), nBytes);
899
900 for (int ty = y; ty < y+h; ty += 64) {
901
902 int th = Math.min(y+h-ty, 64);
903
904 for (int tx = x; tx < x+w; tx += 64) {
905
906 int tw = Math.min(x+w-tx, 64);
907
908 int mode = zrleInStream.readU8();
909 boolean rle = (mode & 128) != 0;
910 int palSize = mode & 127;
911 int[] palette = new int[128];
912
913 readZrlePalette(palette, palSize);
914
915 if (palSize == 1) {
916 int pix = palette[0];
917 Color c = (bytesPixel == 1) ?
918 colors[pix] : new Color(0xFF000000 | pix);
919 memGraphics.setColor(c);
920 memGraphics.fillRect(tx, ty, tw, th);
921 continue;
922 }
923
924 if (!rle) {
925 if (palSize == 0) {
926 readZrleRawPixels(tw, th);
927 } else {
928 readZrlePackedPixels(tw, th, palette, palSize);
929 }
930 } else {
931 if (palSize == 0) {
932 readZrlePlainRLEPixels(tw, th);
933 } else {
934 readZrlePackedRLEPixels(tw, th, palette);
935 }
936 }
937 handleUpdatedZrleTile(tx, ty, tw, th);
938 }
939 }
940
941 zrleInStream.reset();
942
943 scheduleRepaint(x, y, w, h);
944 }
945
946 int readPixel(InStream is) throws Exception {
947 int pix;
948 if (bytesPixel == 1) {
949 pix = is.readU8();
950 } else {
951 int p1 = is.readU8();
952 int p2 = is.readU8();
953 int p3 = is.readU8();
954 pix = (p3 & 0xFF) << 16 | (p2 & 0xFF) << 8 | (p1 & 0xFF);
955 }
956 return pix;
957 }
958
959 void readPixels(InStream is, int[] dst, int count) throws Exception {
960 int pix;
961 if (bytesPixel == 1) {
962 byte[] buf = new byte[count];
963 is.readBytes(buf, 0, count);
964 for (int i = 0; i < count; i++) {
965 dst[i] = (int)buf[i] & 0xFF;
966 }
967 } else {
968 byte[] buf = new byte[count * 3];
969 is.readBytes(buf, 0, count * 3);
970 for (int i = 0; i < count; i++) {
971 dst[i] = ((buf[i*3+2] & 0xFF) << 16 |
972 (buf[i*3+1] & 0xFF) << 8 |
973 (buf[i*3] & 0xFF));
974 }
975 }
976 }
977
978 void readZrlePalette(int[] palette, int palSize) throws Exception {
979 readPixels(zrleInStream, palette, palSize);
980 }
981
982 void readZrleRawPixels(int tw, int th) throws Exception {
983 if (bytesPixel == 1) {
984 zrleInStream.readBytes(zrleTilePixels8, 0, tw * th);
985 } else {
986 readPixels(zrleInStream, zrleTilePixels24, tw * th); ///
987 }
988 }
989
990 void readZrlePackedPixels(int tw, int th, int[] palette, int palSize)
991 throws Exception {
992
993 int bppp = ((palSize > 16) ? 8 :
994 ((palSize > 4) ? 4 : ((palSize > 2) ? 2 : 1)));
995 int ptr = 0;
996
997 for (int i = 0; i < th; i++) {
998 int eol = ptr + tw;
999 int b = 0;
1000 int nbits = 0;
1001
1002 while (ptr < eol) {
1003 if (nbits == 0) {
1004 b = zrleInStream.readU8();
1005 nbits = 8;
1006 }
1007 nbits -= bppp;
1008 int index = (b >> nbits) & ((1 << bppp) - 1) & 127;
1009 if (bytesPixel == 1) {
1010 zrleTilePixels8[ptr++] = (byte)palette[index];
1011 } else {
1012 zrleTilePixels24[ptr++] = palette[index];
1013 }
1014 }
1015 }
1016 }
1017
1018 void readZrlePlainRLEPixels(int tw, int th) throws Exception {
1019 int ptr = 0;
1020 int end = ptr + tw * th;
1021 while (ptr < end) {
1022 int pix = readPixel(zrleInStream);
1023 int len = 1;
1024 int b;
1025 do {
1026 b = zrleInStream.readU8();
1027 len += b;
1028 } while (b == 255);
1029
1030 if (!(len <= end - ptr))
1031 throw new Exception("ZRLE decoder: assertion failed" +
1032 " (len <= end-ptr)");
1033
1034 if (bytesPixel == 1) {
1035 while (len-- > 0) zrleTilePixels8[ptr++] = (byte)pix;
1036 } else {
1037 while (len-- > 0) zrleTilePixels24[ptr++] = pix;
1038 }
1039 }
1040 }
1041
1042 void readZrlePackedRLEPixels(int tw, int th, int[] palette)
1043 throws Exception {
1044
1045 int ptr = 0;
1046 int end = ptr + tw * th;
1047 while (ptr < end) {
1048 int index = zrleInStream.readU8();
1049 int len = 1;
1050 if ((index & 128) != 0) {
1051 int b;
1052 do {
1053 b = zrleInStream.readU8();
1054 len += b;
1055 } while (b == 255);
enikeyc41ba1d2008-12-19 09:07:22 +00001056
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001057 if (!(len <= end - ptr))
1058 throw new Exception("ZRLE decoder: assertion failed" +
1059 " (len <= end - ptr)");
1060 }
1061
1062 index &= 127;
1063 int pix = palette[index];
1064
1065 if (bytesPixel == 1) {
1066 while (len-- > 0) zrleTilePixels8[ptr++] = (byte)pix;
1067 } else {
1068 while (len-- > 0) zrleTilePixels24[ptr++] = pix;
1069 }
1070 }
1071 }
1072
1073 //
1074 // Copy pixels from zrleTilePixels8 or zrleTilePixels24, then update.
1075 //
1076
1077 void handleUpdatedZrleTile(int x, int y, int w, int h) {
1078 Object src, dst;
1079 if (bytesPixel == 1) {
1080 src = zrleTilePixels8; dst = pixels8;
1081 } else {
1082 src = zrleTilePixels24; dst = pixels24;
1083 }
1084 int offsetSrc = 0;
1085 int offsetDst = (y * rfb.framebufferWidth + x);
1086 for (int j = 0; j < h; j++) {
1087 System.arraycopy(src, offsetSrc, dst, offsetDst, w);
1088 offsetSrc += w;
1089 offsetDst += rfb.framebufferWidth;
1090 }
1091 handleUpdatedPixels(x, y, w, h);
1092 }
1093
1094 //
1095 // Handle a Zlib-encoded rectangle.
1096 //
1097
1098 void handleZlibRect(int x, int y, int w, int h) throws Exception {
1099
1100 int nBytes = rfb.readU32();
1101
1102 if (zlibBuf == null || zlibBufLen < nBytes) {
1103 zlibBufLen = nBytes * 2;
1104 zlibBuf = new byte[zlibBufLen];
1105 }
1106
1107 rfb.readFully(zlibBuf, 0, nBytes);
1108
1109 if (rfb.rec != null && rfb.recordFromBeginning) {
1110 rfb.rec.writeIntBE(nBytes);
1111 rfb.rec.write(zlibBuf, 0, nBytes);
1112 }
1113
1114 if (zlibInflater == null) {
1115 zlibInflater = new Inflater();
1116 }
1117 zlibInflater.setInput(zlibBuf, 0, nBytes);
1118
1119 if (bytesPixel == 1) {
1120 for (int dy = y; dy < y + h; dy++) {
1121 zlibInflater.inflate(pixels8, dy * rfb.framebufferWidth + x, w);
1122 if (rfb.rec != null && !rfb.recordFromBeginning)
1123 rfb.rec.write(pixels8, dy * rfb.framebufferWidth + x, w);
1124 }
1125 } else {
1126 byte[] buf = new byte[w * 4];
1127 int i, offset;
1128 for (int dy = y; dy < y + h; dy++) {
1129 zlibInflater.inflate(buf);
1130 offset = dy * rfb.framebufferWidth + x;
1131 for (i = 0; i < w; i++) {
1132 pixels24[offset + i] =
1133 (buf[i * 4 + 2] & 0xFF) << 16 |
1134 (buf[i * 4 + 1] & 0xFF) << 8 |
1135 (buf[i * 4] & 0xFF);
1136 }
1137 if (rfb.rec != null && !rfb.recordFromBeginning)
1138 rfb.rec.write(buf);
1139 }
1140 }
1141
1142 handleUpdatedPixels(x, y, w, h);
1143 scheduleRepaint(x, y, w, h);
1144 }
1145
1146 //
1147 // Handle a Tight-encoded rectangle.
1148 //
1149
1150 void handleTightRect(int x, int y, int w, int h) throws Exception {
enikey2f7f46e2008-12-19 09:32:35 +00001151 tightDecoder.handleRect(x, y, w, h);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001152 scheduleRepaint(x, y, w, h);
1153 }
1154
1155 //
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001156 // Display newly updated area of pixels.
1157 //
1158
1159 void handleUpdatedPixels(int x, int y, int w, int h) {
1160
1161 // Draw updated pixels of the off-screen image.
1162 pixelsSource.newPixels(x, y, w, h);
1163 memGraphics.setClip(x, y, w, h);
1164 memGraphics.drawImage(rawPixelsImage, 0, 0, null);
1165 memGraphics.setClip(0, 0, rfb.framebufferWidth, rfb.framebufferHeight);
1166 }
1167
1168 //
1169 // Tell JVM to repaint specified desktop area.
1170 //
1171
enikey0dbc1532008-12-19 08:51:47 +00001172 public void scheduleRepaint(int x, int y, int w, int h) {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001173 // Request repaint, deferred if necessary.
1174 if (rfb.framebufferWidth == scaledWidth) {
1175 repaint(viewer.deferScreenUpdates, x, y, w, h);
1176 } else {
1177 int sx = x * scalingFactor / 100;
1178 int sy = y * scalingFactor / 100;
1179 int sw = ((x + w) * scalingFactor + 49) / 100 - sx + 1;
1180 int sh = ((y + h) * scalingFactor + 49) / 100 - sy + 1;
1181 repaint(viewer.deferScreenUpdates, sx, sy, sw, sh);
1182 }
1183 }
1184
1185 //
1186 // Handle events.
1187 //
1188
1189 public void keyPressed(KeyEvent evt) {
1190 processLocalKeyEvent(evt);
1191 }
1192 public void keyReleased(KeyEvent evt) {
1193 processLocalKeyEvent(evt);
1194 }
1195 public void keyTyped(KeyEvent evt) {
1196 evt.consume();
1197 }
1198
1199 public void mousePressed(MouseEvent evt) {
1200 processLocalMouseEvent(evt, false);
1201 }
1202 public void mouseReleased(MouseEvent evt) {
1203 processLocalMouseEvent(evt, false);
1204 }
1205 public void mouseMoved(MouseEvent evt) {
1206 processLocalMouseEvent(evt, true);
1207 }
1208 public void mouseDragged(MouseEvent evt) {
1209 processLocalMouseEvent(evt, true);
1210 }
1211
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001212 //
1213 // Ignored events.
1214 //
1215
1216 public void mouseClicked(MouseEvent evt) {}
1217 public void mouseEntered(MouseEvent evt) {}
1218 public void mouseExited(MouseEvent evt) {}
1219
1220 //
1221 // Actual event processing.
1222 //
1223
1224 private void processLocalKeyEvent(KeyEvent evt) {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001225 if (viewer.rfb != null && rfb.inNormalProtocol) {
1226 if (!inputEnabled) {
1227 if ((evt.getKeyChar() == 'r' || evt.getKeyChar() == 'R') &&
1228 evt.getID() == KeyEvent.KEY_PRESSED ) {
1229 // Request screen update.
1230 try {
1231 rfb.writeFramebufferUpdateRequest(0, 0, rfb.framebufferWidth,
1232 rfb.framebufferHeight, false);
1233 } catch (IOException e) {
1234 e.printStackTrace();
1235 }
1236 }
1237 } else {
1238 // Input enabled.
1239 synchronized(rfb) {
1240 try {
1241 rfb.writeKeyEvent(evt);
1242 } catch (Exception e) {
1243 e.printStackTrace();
1244 }
1245 rfb.notify();
1246 }
1247 }
1248 }
enikeyc41ba1d2008-12-19 09:07:22 +00001249 // Don't ever pass keyboard events to AWT for default processing.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001250 // Otherwise, pressing Tab would switch focus to ButtonPanel etc.
1251 evt.consume();
1252 }
1253
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001254 private void processLocalMouseEvent(MouseEvent evt, boolean moved) {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001255 if (viewer.rfb != null && rfb.inNormalProtocol) {
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001256 if (!inSelectionMode) {
1257 if (inputEnabled) {
1258 sendMouseEvent(evt, moved);
1259 }
1260 } else {
1261 handleSelectionMouseEvent(evt);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001262 }
1263 }
1264 }
1265
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001266 private void sendMouseEvent(MouseEvent evt, boolean moved) {
1267 if (moved) {
1268 softCursorMove(evt.getX(), evt.getY());
1269 }
1270 if (rfb.framebufferWidth != scaledWidth) {
1271 int sx = (evt.getX() * 100 + scalingFactor/2) / scalingFactor;
1272 int sy = (evt.getY() * 100 + scalingFactor/2) / scalingFactor;
1273 evt.translatePoint(sx - evt.getX(), sy - evt.getY());
1274 }
1275 synchronized(rfb) {
1276 try {
1277 rfb.writePointerEvent(evt);
1278 } catch (Exception e) {
1279 e.printStackTrace();
1280 }
1281 rfb.notify();
1282 }
1283 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001284
1285 //
1286 // Reset update statistics.
1287 //
1288
1289 void resetStats() {
1290 statStartTime = System.currentTimeMillis();
1291 statNumUpdates = 0;
1292 statNumTotalRects = 0;
1293 statNumPixelRects = 0;
1294 statNumRectsTight = 0;
1295 statNumRectsTightJPEG = 0;
1296 statNumRectsZRLE = 0;
1297 statNumRectsHextile = 0;
1298 statNumRectsRaw = 0;
1299 statNumRectsCopy = 0;
1300 statNumBytesEncoded = 0;
1301 statNumBytesDecoded = 0;
enikey2f7f46e2008-12-19 09:32:35 +00001302 if (tightDecoder != null)
1303 tightDecoder.setNumJPEGRects(0);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001304 }
1305
1306 //////////////////////////////////////////////////////////////////
1307 //
1308 // Handle cursor shape updates (XCursor and RichCursor encodings).
1309 //
1310
1311 boolean showSoftCursor = false;
1312
1313 MemoryImageSource softCursorSource;
1314 Image softCursor;
1315
1316 int cursorX = 0, cursorY = 0;
1317 int cursorWidth, cursorHeight;
1318 int origCursorWidth, origCursorHeight;
1319 int hotX, hotY;
1320 int origHotX, origHotY;
1321
1322 //
1323 // Handle cursor shape update (XCursor and RichCursor encodings).
1324 //
1325
1326 synchronized void
1327 handleCursorShapeUpdate(int encodingType,
1328 int xhot, int yhot, int width, int height)
1329 throws IOException {
1330
1331 softCursorFree();
1332
1333 if (width * height == 0)
1334 return;
1335
1336 // Ignore cursor shape data if requested by user.
1337 if (viewer.options.ignoreCursorUpdates) {
1338 int bytesPerRow = (width + 7) / 8;
1339 int bytesMaskData = bytesPerRow * height;
1340
1341 if (encodingType == rfb.EncodingXCursor) {
1342 rfb.skipBytes(6 + bytesMaskData * 2);
1343 } else {
1344 // rfb.EncodingRichCursor
1345 rfb.skipBytes(width * height + bytesMaskData);
1346 }
1347 return;
1348 }
1349
1350 // Decode cursor pixel data.
1351 softCursorSource = decodeCursorShape(encodingType, width, height);
1352
1353 // Set original (non-scaled) cursor dimensions.
1354 origCursorWidth = width;
1355 origCursorHeight = height;
1356 origHotX = xhot;
1357 origHotY = yhot;
1358
1359 // Create off-screen cursor image.
1360 createSoftCursor();
1361
1362 // Show the cursor.
1363 showSoftCursor = true;
1364 repaint(viewer.deferCursorUpdates,
1365 cursorX - hotX, cursorY - hotY, cursorWidth, cursorHeight);
1366 }
1367
1368 //
1369 // decodeCursorShape(). Decode cursor pixel data and return
1370 // corresponding MemoryImageSource instance.
1371 //
1372
1373 synchronized MemoryImageSource
1374 decodeCursorShape(int encodingType, int width, int height)
1375 throws IOException {
1376
1377 int bytesPerRow = (width + 7) / 8;
1378 int bytesMaskData = bytesPerRow * height;
1379
1380 int[] softCursorPixels = new int[width * height];
1381
1382 if (encodingType == rfb.EncodingXCursor) {
1383
1384 // Read foreground and background colors of the cursor.
1385 byte[] rgb = new byte[6];
1386 rfb.readFully(rgb);
1387 int[] colors = { (0xFF000000 | (rgb[3] & 0xFF) << 16 |
1388 (rgb[4] & 0xFF) << 8 | (rgb[5] & 0xFF)),
1389 (0xFF000000 | (rgb[0] & 0xFF) << 16 |
1390 (rgb[1] & 0xFF) << 8 | (rgb[2] & 0xFF)) };
1391
1392 // Read pixel and mask data.
1393 byte[] pixBuf = new byte[bytesMaskData];
1394 rfb.readFully(pixBuf);
1395 byte[] maskBuf = new byte[bytesMaskData];
1396 rfb.readFully(maskBuf);
1397
1398 // Decode pixel data into softCursorPixels[].
1399 byte pixByte, maskByte;
1400 int x, y, n, result;
1401 int i = 0;
1402 for (y = 0; y < height; y++) {
1403 for (x = 0; x < width / 8; x++) {
1404 pixByte = pixBuf[y * bytesPerRow + x];
1405 maskByte = maskBuf[y * bytesPerRow + x];
1406 for (n = 7; n >= 0; n--) {
1407 if ((maskByte >> n & 1) != 0) {
1408 result = colors[pixByte >> n & 1];
1409 } else {
1410 result = 0; // Transparent pixel
1411 }
1412 softCursorPixels[i++] = result;
1413 }
1414 }
1415 for (n = 7; n >= 8 - width % 8; n--) {
1416 if ((maskBuf[y * bytesPerRow + x] >> n & 1) != 0) {
1417 result = colors[pixBuf[y * bytesPerRow + x] >> n & 1];
1418 } else {
1419 result = 0; // Transparent pixel
1420 }
1421 softCursorPixels[i++] = result;
1422 }
1423 }
1424
1425 } else {
1426 // encodingType == rfb.EncodingRichCursor
1427
1428 // Read pixel and mask data.
1429 byte[] pixBuf = new byte[width * height * bytesPixel];
1430 rfb.readFully(pixBuf);
1431 byte[] maskBuf = new byte[bytesMaskData];
1432 rfb.readFully(maskBuf);
1433
1434 // Decode pixel data into softCursorPixels[].
1435 byte pixByte, maskByte;
1436 int x, y, n, result;
1437 int i = 0;
1438 for (y = 0; y < height; y++) {
1439 for (x = 0; x < width / 8; x++) {
1440 maskByte = maskBuf[y * bytesPerRow + x];
1441 for (n = 7; n >= 0; n--) {
1442 if ((maskByte >> n & 1) != 0) {
1443 if (bytesPixel == 1) {
1444 result = cm8.getRGB(pixBuf[i]);
1445 } else {
1446 result = 0xFF000000 |
1447 (pixBuf[i * 4 + 2] & 0xFF) << 16 |
1448 (pixBuf[i * 4 + 1] & 0xFF) << 8 |
1449 (pixBuf[i * 4] & 0xFF);
1450 }
1451 } else {
1452 result = 0; // Transparent pixel
1453 }
1454 softCursorPixels[i++] = result;
1455 }
1456 }
1457 for (n = 7; n >= 8 - width % 8; n--) {
1458 if ((maskBuf[y * bytesPerRow + x] >> n & 1) != 0) {
1459 if (bytesPixel == 1) {
1460 result = cm8.getRGB(pixBuf[i]);
1461 } else {
1462 result = 0xFF000000 |
1463 (pixBuf[i * 4 + 2] & 0xFF) << 16 |
1464 (pixBuf[i * 4 + 1] & 0xFF) << 8 |
1465 (pixBuf[i * 4] & 0xFF);
1466 }
1467 } else {
1468 result = 0; // Transparent pixel
1469 }
1470 softCursorPixels[i++] = result;
1471 }
1472 }
1473
1474 }
1475
1476 return new MemoryImageSource(width, height, softCursorPixels, 0, width);
1477 }
1478
1479 //
1480 // createSoftCursor(). Assign softCursor new Image (scaled if necessary).
1481 // Uses softCursorSource as a source for new cursor image.
1482 //
1483
1484 synchronized void
1485 createSoftCursor() {
1486
1487 if (softCursorSource == null)
1488 return;
1489
1490 int scaleCursor = viewer.options.scaleCursor;
1491 if (scaleCursor == 0 || !inputEnabled)
1492 scaleCursor = 100;
1493
1494 // Save original cursor coordinates.
1495 int x = cursorX - hotX;
1496 int y = cursorY - hotY;
1497 int w = cursorWidth;
1498 int h = cursorHeight;
1499
1500 cursorWidth = (origCursorWidth * scaleCursor + 50) / 100;
1501 cursorHeight = (origCursorHeight * scaleCursor + 50) / 100;
1502 hotX = (origHotX * scaleCursor + 50) / 100;
1503 hotY = (origHotY * scaleCursor + 50) / 100;
1504 softCursor = Toolkit.getDefaultToolkit().createImage(softCursorSource);
1505
1506 if (scaleCursor != 100) {
1507 softCursor = softCursor.getScaledInstance(cursorWidth, cursorHeight,
1508 Image.SCALE_SMOOTH);
1509 }
1510
1511 if (showSoftCursor) {
1512 // Compute screen area to update.
1513 x = Math.min(x, cursorX - hotX);
1514 y = Math.min(y, cursorY - hotY);
1515 w = Math.max(w, cursorWidth);
1516 h = Math.max(h, cursorHeight);
1517
1518 repaint(viewer.deferCursorUpdates, x, y, w, h);
1519 }
1520 }
1521
1522 //
1523 // softCursorMove(). Moves soft cursor into a particular location.
1524 //
1525
1526 synchronized void softCursorMove(int x, int y) {
1527 int oldX = cursorX;
1528 int oldY = cursorY;
1529 cursorX = x;
1530 cursorY = y;
1531 if (showSoftCursor) {
1532 repaint(viewer.deferCursorUpdates,
1533 oldX - hotX, oldY - hotY, cursorWidth, cursorHeight);
1534 repaint(viewer.deferCursorUpdates,
1535 cursorX - hotX, cursorY - hotY, cursorWidth, cursorHeight);
1536 }
1537 }
1538
1539 //
1540 // softCursorFree(). Remove soft cursor, dispose resources.
1541 //
1542
1543 synchronized void softCursorFree() {
1544 if (showSoftCursor) {
1545 showSoftCursor = false;
1546 softCursor = null;
1547 softCursorSource = null;
1548
1549 repaint(viewer.deferCursorUpdates,
1550 cursorX - hotX, cursorY - hotY, cursorWidth, cursorHeight);
1551 }
1552 }
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001553
1554 //////////////////////////////////////////////////////////////////
1555 //
1556 // Support for selecting a rectangular video area.
1557 //
1558
1559 /** This flag is false in normal operation, and true in the selection mode. */
1560 private boolean inSelectionMode;
1561
1562 /** The point where the selection was started. */
1563 private Point selectionStart;
1564
1565 /** The second point of the selection. */
1566 private Point selectionEnd;
1567
1568 /**
1569 * We change cursor when enabling the selection mode. In this variable, we
1570 * save the original cursor so we can restore it on returning to the normal
1571 * mode.
1572 */
1573 private Cursor savedCursor;
1574
1575 /**
1576 * Initialize selection-related varibles.
1577 */
1578 private synchronized void resetSelection() {
1579 inSelectionMode = false;
1580 selectionStart = new Point(0, 0);
1581 selectionEnd = new Point(0, 0);
1582
1583 savedCursor = getCursor();
1584 }
1585
1586 /**
1587 * Check current state of the selection mode.
1588 * @return true in the selection mode, false otherwise.
1589 */
1590 public boolean isInSelectionMode() {
1591 return inSelectionMode;
1592 }
1593
1594 /**
1595 * Get current selection.
1596 * @param useScreenCoords use screen coordinates if true, or framebuffer
1597 * coordinates if false. This makes difference when scaling factor is not 100.
1598 * @return The selection as a {@link Rectangle}.
1599 */
1600 private synchronized Rectangle getSelection(boolean useScreenCoords) {
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001601 int x0 = selectionStart.x;
1602 int x1 = selectionEnd.x;
1603 int y0 = selectionStart.y;
1604 int y1 = selectionEnd.y;
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001605 // Make x and y point to the upper left corner of the selection.
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001606 if (x1 < x0) {
1607 int t = x0; x0 = x1; x1 = t;
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001608 }
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001609 if (y1 < y0) {
1610 int t = y0; y0 = y1; y1 = t;
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001611 }
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001612 // Include the borders in the selection (unless it's empty).
1613 if (x0 != x1 && y0 != y1) {
1614 x1 += 1;
1615 y1 += 1;
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001616 }
1617 // Translate from screen coordinates to framebuffer coordinates.
1618 if (rfb.framebufferWidth != scaledWidth) {
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001619 x0 = (x0 * 100 + scalingFactor/2) / scalingFactor;
1620 y0 = (y0 * 100 + scalingFactor/2) / scalingFactor;
1621 x1 = (x1 * 100 + scalingFactor/2) / scalingFactor;
1622 y1 = (y1 * 100 + scalingFactor/2) / scalingFactor;
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001623 }
Constantin Kaplinsky10da44d2008-09-03 03:12:18 +00001624 // Clip the selection to framebuffer.
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001625 if (x0 < 0)
1626 x0 = 0;
1627 if (y0 < 0)
1628 y0 = 0;
1629 if (x1 > rfb.framebufferWidth)
1630 x1 = rfb.framebufferWidth;
1631 if (y1 > rfb.framebufferHeight)
1632 y1 = rfb.framebufferHeight;
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001633 // Make width a multiple of 16.
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001634 int widthBlocks = (x1 - x0 + 8) / 16;
1635 if (selectionStart.x <= selectionEnd.x) {
1636 x1 = x0 + widthBlocks * 16;
1637 if (x1 > rfb.framebufferWidth) {
1638 x1 -= 16;
1639 }
1640 } else {
1641 x0 = x1 - widthBlocks * 16;
1642 if (x0 < 0) {
1643 x0 += 16;
1644 }
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001645 }
1646 // Make height a multiple of 8.
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001647 int heightBlocks = (y1 - y0 + 4) / 8;
1648 if (selectionStart.y <= selectionEnd.y) {
1649 y1 = y0 + heightBlocks * 8;
1650 if (y1 > rfb.framebufferHeight) {
1651 y1 -= 8;
1652 }
1653 } else {
1654 y0 = y1 - heightBlocks * 8;
1655 if (y0 < 0) {
1656 y0 += 8;
1657 }
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001658 }
1659 // Translate the selection back to screen coordinates if requested.
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001660 if (useScreenCoords && rfb.framebufferWidth != scaledWidth) {
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001661 x0 = (x0 * scalingFactor + 50) / 100;
1662 y0 = (y0 * scalingFactor + 50) / 100;
1663 x1 = (x1 * scalingFactor + 50) / 100;
1664 y1 = (y1 * scalingFactor + 50) / 100;
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001665 }
Constantin Kaplinsky4f374ff2008-09-03 04:51:28 +00001666 // Construct and return the result.
1667 return new Rectangle(x0, y0, x1 - x0, y1 - y0);
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001668 }
1669
1670 /**
1671 * Enable or disable the selection mode.
1672 * @param enable enables the selection mode if true, disables if fasle.
1673 */
1674 public synchronized void enableSelection(boolean enable) {
1675 if (enable && !inSelectionMode) {
1676 // Enter the selection mode.
1677 inSelectionMode = true;
1678 savedCursor = getCursor();
1679 setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
1680 repaint();
1681 } else if (!enable && inSelectionMode) {
1682 // Leave the selection mode.
1683 inSelectionMode = false;
1684 setCursor(savedCursor);
1685 repaint();
1686 }
1687 }
1688
1689 /**
1690 * Process mouse events in the selection mode.
enikeyc41ba1d2008-12-19 09:07:22 +00001691 *
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001692 * @param evt mouse event that was originally passed to
1693 * {@link MouseListener} or {@link MouseMotionListener}.
1694 */
1695 private synchronized void handleSelectionMouseEvent(MouseEvent evt) {
1696 int id = evt.getID();
1697 boolean button1 = (evt.getModifiers() & InputEvent.BUTTON1_MASK) != 0;
1698
1699 if (id == MouseEvent.MOUSE_PRESSED && button1) {
1700 selectionStart = selectionEnd = evt.getPoint();
1701 repaint();
1702 }
1703 if (id == MouseEvent.MOUSE_DRAGGED && button1) {
1704 selectionEnd = evt.getPoint();
1705 repaint();
1706 }
1707 if (id == MouseEvent.MOUSE_RELEASED && button1) {
1708 try {
1709 rfb.trySendVideoSelection(getSelection(false));
1710 } catch (IOException e) {
1711 e.printStackTrace();
1712 }
1713 }
1714 }
1715
enikey418611f2008-12-19 04:37:09 +00001716 //
1717 // Override RecordInterface methods
1718 //
1719
1720 public boolean isRecordFromBeginning() {
1721 return rfb.recordFromBeginning;
1722 }
1723
1724 public boolean canWrite() {
1725 // We can record if rec is not null
1726 return rfb.rec != null;
1727 }
1728
1729 public void write(byte b[]) throws IOException {
1730 rfb.rec.write(b);
1731 }
1732
1733 public void write(byte b[], int off, int len) throws IOException {
1734 rfb.rec.write(b, off, len);
1735 }
1736
1737 public void writeByte(byte b) throws IOException {
1738 rfb.rec.writeByte(b);
1739 }
1740
1741 public void writeByte(int i) throws IOException {
1742 rfb.rec.writeByte(i);
1743 }
1744
1745 public void writeIntBE(int v) throws IOException {
1746 rfb.rec.writeIntBE(v);
1747 }
1748
1749 public void recordCompactLen(int len) throws IOException {
1750 rfb.recordCompactLen(len);
1751 }
1752
1753 public void recordCompressedData(byte[] data) throws IOException {
1754 rfb.recordCompressedData(data);
1755 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001756}