aboutsummaryrefslogtreecommitdiffstats
path: root/java/src/com/tigervnc/vncviewer/VncViewer.java
blob: 41f484f9a318ec37a1ae6a6fac6a8ccccea1d84e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
//
//  Copyright (C) 2001-2004 HorizonLive.com, Inc.  All Rights Reserved.
//  Copyright (C) 2002 Constantin Kaplinsky.  All Rights Reserved.
//  Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
//
//  This is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This software is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this software; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
//  USA.
//

//
// VncViewer.java - the VNC viewer applet.  This class mainly just sets up the
// user interface, leaving it to the VncCanvas to do the actual rendering of
// a VNC desktop.
//

package com.tigervnc.vncviewer;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class VncViewer extends java.applet.Applet
  implements java.lang.Runnable, WindowListener, ComponentListener {

  boolean inAnApplet = true;
  boolean inSeparateFrame = false;

  //
  // main() is called when run as a java program from the command line.
  // It simply runs the applet inside a newly-created frame.
  //

  public static void main(String[] argv) {
    VncViewer v = new VncViewer();
    v.mainArgs = argv;
    v.inAnApplet = false;
    v.inSeparateFrame = true;

    v.init();
    v.start();
  }

  String[] mainArgs;

  RfbProto rfb;
  Thread rfbThread;

  Frame vncFrame;
  Container vncContainer;
  ScrollPane desktopScrollPane;
  GridBagLayout gridbag;
  ButtonPanel buttonPanel;
  Label connStatusLabel;
  VncCanvas vc;
  OptionsFrame options;
  ClipboardFrame clipboard;
  RecordingFrame rec;

  // Control session recording.
  Object recordingSync;
  String sessionFileName;
  boolean recordingActive;
  boolean recordingStatusChanged;
  String cursorUpdatesDef;
  String eightBitColorsDef;

  // Variables read from parameter values.
  String socketFactory;
  String host;
  int port;
  String passwordParam;
  boolean showControls;
  boolean offerRelogin;
  boolean showOfflineDesktop;
  int deferScreenUpdates;
  int deferCursorUpdates;
  int deferUpdateRequests;
  int debugStatsExcludeUpdates;
  int debugStatsMeasureUpdates;

  // Reference to this applet for inter-applet communication.
  public static java.applet.Applet refApplet;

  //
  // init()
  //

  public void init() {

    readParameters();

    refApplet = this;

    if (inSeparateFrame) {
      vncFrame = new Frame("TigerVNC");
      if (!inAnApplet) {
	vncFrame.add("Center", this);
      }
      vncContainer = vncFrame;
    } else {
      vncContainer = this;
    }

    recordingSync = new Object();

    options = new OptionsFrame(this);
    clipboard = new ClipboardFrame(this);
    if (RecordingFrame.checkSecurity())
      rec = new RecordingFrame(this);

    sessionFileName = null;
    recordingActive = false;
    recordingStatusChanged = false;
    cursorUpdatesDef = null;
    eightBitColorsDef = null;

    if (inSeparateFrame) {
      vncFrame.addWindowListener(this);
      vncFrame.addComponentListener(this);
    }

    rfbThread = new Thread(this);
    rfbThread.start();
  }

  public void update(Graphics g) {
  }

  //
  // run() - executed by the rfbThread to deal with the RFB socket.
  //

  public void run() {

    gridbag = new GridBagLayout();
    vncContainer.setLayout(gridbag);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.anchor = GridBagConstraints.NORTHWEST;

    if (showControls) {
      buttonPanel = new ButtonPanel(this);
      gridbag.setConstraints(buttonPanel, gbc);
      vncContainer.add(buttonPanel);
    }

    try {
      connectAndAuthenticate();
      doProtocolInitialisation();

      if (showControls &&
          rfb.clientMsgCaps.isEnabled(RfbProto.VideoRectangleSelection)) {
        buttonPanel.addSelectButton();
      }

      if (showControls &&
          rfb.clientMsgCaps.isEnabled(RfbProto.VideoFreeze)) {
        buttonPanel.addVideoFreezeButton();
      }

      // FIXME: Use auto-scaling not only in a separate frame.
      if (options.autoScale && inSeparateFrame) {
	Dimension screenSize;
	try {
	  screenSize = vncContainer.getToolkit().getScreenSize();
	} catch (Exception e) {
	  screenSize = new Dimension(0, 0);
	}
	createCanvas(screenSize.width - 32, screenSize.height - 32);
      } else {
	createCanvas(0, 0);
      }

      gbc.weightx = 1.0;
      gbc.weighty = 1.0;

      if (inSeparateFrame) {

	// Create a panel which itself is resizeable and can hold
	// non-resizeable VncCanvas component at the top left corner.
	Panel canvasPanel = new Panel();
	canvasPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
	canvasPanel.add(vc);

	// Create a ScrollPane which will hold a panel with VncCanvas
	// inside.
	desktopScrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
	gbc.fill = GridBagConstraints.BOTH;
	gridbag.setConstraints(desktopScrollPane, gbc);
	desktopScrollPane.add(canvasPanel);
        // If auto scale is not enabled we don't need to set first frame
        // size to fullscreen
        if (!options.autoScale) {
          vc.isFirstSizeAutoUpdate = false;
        }

	// Finally, add our ScrollPane to the Frame window.
	vncFrame.add(desktopScrollPane);
	vncFrame.setTitle(rfb.desktopName);
	vncFrame.pack();
	vc.resizeDesktopFrame();

      } else {
	// Just add the VncCanvas component to the Applet.
	gridbag.setConstraints(vc, gbc);
	add(vc);
	validate();
      }

      if (showControls) {
        buttonPanel.enableButtons();
      }

      moveFocusToDesktop();
      processNormalProtocol();

    } catch (NoRouteToHostException e) {
      fatalError("Network error: no route to server: " + host, e);
    } catch (UnknownHostException e) {
      fatalError("Network error: server name unknown: " + host, e);
    } catch (ConnectException e) {
      fatalError("Network error: could not connect to server: " +
		 host + ":" + port, e);
    } catch (EOFException e) {
      if (showOfflineDesktop) {
	e.printStackTrace();
	System.out.println("Network error: remote side closed connection");
	if (vc != null) {
	  vc.enableInput(false);
	}
	if (inSeparateFrame) {
	  vncFrame.setTitle(rfb.desktopName + " [disconnected]");
	}
	if (rfb != null && !rfb.closed())
	  rfb.close();
	if (showControls && buttonPanel != null) {
	  buttonPanel.disableButtonsOnDisconnect();
	  if (inSeparateFrame) {
	    vncFrame.pack();
	  } else {
	    validate();
	  }
	}
      } else {
	fatalError("Network error: remote side closed connection", e);
      }
    } catch (IOException e) {
      String str = e.getMessage();
      if (str != null && str.length() != 0) {
	fatalError("Network Error: " + str, e);
      } else {
	fatalError(e.toString(), e);
      }
    } catch (Exception e) {
      String str = e.getMessage();
      if (str != null && str.length() != 0) {
	fatalError("Error: " + str, e);
      } else {
	fatalError(e.toString(), e);
      }
    }
    
  }

  //
  // Create a VncCanvas instance.
  //

  void createCanvas(int maxWidth, int maxHeight) throws IOException {
    // Determine if Java 2D API is available and use a special
    // version of VncCanvas if it is present.
    vc = null;
    try {
      // This throws ClassNotFoundException if there is no Java 2D API.
      Class cl = Class.forName("java.awt.Graphics2D");
      // If we could load Graphics2D class, then we can use VncCanvas2D.
      cl = Class.forName("com.tigervnc.vncviewer.VncCanvas2");
      Class[] argClasses = { this.getClass(), Integer.TYPE, Integer.TYPE };
      java.lang.reflect.Constructor cstr = cl.getConstructor(argClasses);
      Object[] argObjects =
        { this, new Integer(maxWidth), new Integer(maxHeight) };
      vc = (VncCanvas)cstr.newInstance(argObjects);
    } catch (Exception e) {
      System.out.println("Warning: Java 2D API is not available");
    }

    // If we failed to create VncCanvas2D, use old VncCanvas.
    if (vc == null)
      vc = new VncCanvas(this, maxWidth, maxHeight);
  }


  //
  // Process RFB socket messages.
  // If the rfbThread is being stopped, ignore any exceptions,
  // otherwise rethrow the exception so it can be handled.
  //
 
  void processNormalProtocol() throws Exception {
    try {
      vc.processNormalProtocol();
    } catch (Exception e) {
      if (rfbThread == null) {
	System.out.println("Ignoring RFB socket exceptions" +
			   " because applet is stopping");
      } else {
	throw e;
      }
    }
  }


  //
  // Connect to the RFB server and authenticate the user.
  //

  void connectAndAuthenticate() throws Exception
  {
    showConnectionStatus("Initializing...");
    if (inSeparateFrame) {
      vncFrame.pack();
      vncFrame.show();
    } else {
      validate();
    }

    showConnectionStatus("Connecting to " + host + ", port " + port + "...");

    rfb = new RfbProto(host, port, this);
    showConnectionStatus("Connected to server");

    rfb.readVersionMsg();
    showConnectionStatus("RFB server supports protocol version " +
			 rfb.serverMajor + "." + rfb.serverMinor);

    rfb.writeVersionMsg();
    showConnectionStatus("Using RFB protocol version " +
			 rfb.clientMajor + "." + rfb.clientMinor);

    int secType = rfb.negotiateSecurity();
    int authType;
    if (secType == RfbProto.SecTypeTight) {
      showConnectionStatus("Enabling TightVNC protocol extensions");
      rfb.setupTunneling();
      authType = rfb.negotiateAuthenticationTight();
    } else {
      authType = secType;
    }

    doAuthentification(authType);
  }

    void doAuthentification(int secType) throws Exception {
	switch (secType) {
	case RfbProto.SecTypeNone:
	    showConnectionStatus("No authentication needed");
	    rfb.authenticateNone();
	    break;
	case RfbProto.SecTypeVncAuth:
	    showConnectionStatus("Performing standard VNC authentication");
	    if (passwordParam != null) {
		rfb.authenticateVNC(passwordParam);
	    } else {
		String pw = askPassword();
		rfb.authenticateVNC(pw);
	    }
	    break;
	case RfbProto.SecTypeVeNCrypt:
	    showConnectionStatus("VeNCrypt chooser");
	    secType = rfb.authenticateVeNCrypt();
	    doAuthentification(secType);
	    break;
	case RfbProto.SecTypePlain:
	    showConnectionStatus("Plain authentication");
	    {
		String user = askUser();
		String pw = askPassword();
		rfb.authenticatePlain(user,pw);
	    }
	    break;
	default:
	    throw new Exception("Unknown authentication scheme " + secType);
	}
    }


  //
  // Show a message describing the connection status.
  // To hide the connection status label, use (msg == null).
  //

  void showConnectionStatus(String msg)
  {
    if (msg == null) {
      if (vncContainer.isAncestorOf(connStatusLabel)) {
	vncContainer.remove(connStatusLabel);
      }
      return;
    }

    System.out.println(msg);

    if (connStatusLabel == null) {
      connStatusLabel = new Label("Status: " + msg);
      connStatusLabel.setFont(new Font("Helvetica", Font.PLAIN, 12));
    } else {
      connStatusLabel.setText("Status: " + msg);
    }

    if (!vncContainer.isAncestorOf(connStatusLabel)) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridwidth = GridBagConstraints.REMAINDER;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.anchor = GridBagConstraints.NORTHWEST;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      gbc.insets = new Insets(20, 30, 20, 30);
      gridbag.setConstraints(connStatusLabel, gbc);
      vncContainer.add(connStatusLabel);
    }

    if (inSeparateFrame) {
      vncFrame.pack();
    } else {
      validate();
    }
  }


  //
  // Show an authentication panel.
  //

  String askUser() throws Exception
  {
    showConnectionStatus(null);

    AuthPanel authPanel = new AuthPanel(this, false);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.ipadx = 100;
    gbc.ipady = 50;
    gridbag.setConstraints(authPanel, gbc);
    vncContainer.add(authPanel);

    if (inSeparateFrame) {
      vncFrame.pack();
    } else {
      validate();
    }

    authPanel.moveFocusToDefaultField();
    String pw = authPanel.getPassword();
    vncContainer.remove(authPanel);

    return pw;
  }

  String askPassword() throws Exception
  {
    showConnectionStatus(null);

    AuthPanel authPanel = new AuthPanel(this, true);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.ipadx = 100;
    gbc.ipady = 50;
    gridbag.setConstraints(authPanel, gbc);
    vncContainer.add(authPanel);

    if (inSeparateFrame) {
      vncFrame.pack();
    } else {
      validate();
    }

    authPanel.moveFocusToDefaultField();
    String pw = authPanel.getPassword();
    vncContainer.remove(authPanel);

    return pw;
  }


  //
  // Do the rest of the protocol initialisation.
  //

  void doProtocolInitialisation() throws IOException
  {
    rfb.writeClientInit();
    rfb.readServerInit();

    System.out.println("Desktop name is " + rfb.desktopName);
    System.out.println("Desktop size is " + rfb.framebufferWidth + " x " +
		       rfb.framebufferHeight);

    setEncodings();

    showConnectionStatus(null);
  }


  //
  // Send current encoding list to the RFB server.
  //

  int[] encodingsSaved;
  int nEncodingsSaved;

  void setEncodings()        { setEncodings(false); }
  void autoSelectEncodings() { setEncodings(true); }

  void setEncodings(boolean autoSelectOnly) {
    if (options == null || rfb == null || !rfb.inNormalProtocol)
      return;

    int preferredEncoding = options.preferredEncoding;
    if (preferredEncoding == -1) {
      long kbitsPerSecond = rfb.kbitsPerSecond();
      if (nEncodingsSaved < 1) {
        // Choose Tight or ZRLE encoding for the very first update.
        System.out.println("Using Tight/ZRLE encodings");
        preferredEncoding = RfbProto.EncodingTight;
      } else if (kbitsPerSecond > 2000 &&
                 encodingsSaved[0] != RfbProto.EncodingHextile) {
        // Switch to Hextile if the connection speed is above 2Mbps.
        System.out.println("Throughput " + kbitsPerSecond +
                           " kbit/s - changing to Hextile encoding");
        preferredEncoding = RfbProto.EncodingHextile;
      } else if (kbitsPerSecond < 1000 &&
                 encodingsSaved[0] != RfbProto.EncodingTight) {
        // Switch to Tight/ZRLE if the connection speed is below 1Mbps.
        System.out.println("Throughput " + kbitsPerSecond +
                           " kbit/s - changing to Tight/ZRLE encodings");
        preferredEncoding = RfbProto.EncodingTight;
      } else {
        // Don't change the encoder.
        if (autoSelectOnly)
          return;
        preferredEncoding = encodingsSaved[0];
      }
    } else {
      // Auto encoder selection is not enabled.
      if (autoSelectOnly)
        return;
    }

    int[] encodings = new int[20];
    int nEncodings = 0;

    encodings[nEncodings++] = preferredEncoding;
    if (options.useCopyRect) {
      encodings[nEncodings++] = RfbProto.EncodingCopyRect;
    }

    if (preferredEncoding != RfbProto.EncodingTight) {
      encodings[nEncodings++] = RfbProto.EncodingTight;
    }
    if (preferredEncoding != RfbProto.EncodingZRLE) {
      encodings[nEncodings++] = RfbProto.EncodingZRLE;
    }
    if (preferredEncoding != RfbProto.EncodingHextile) {
      encodings[nEncodings++] = RfbProto.EncodingHextile;
    }
    if (preferredEncoding != RfbProto.EncodingZlib) {
      encodings[nEncodings++] = RfbProto.EncodingZlib;
    }
    if (preferredEncoding != RfbProto.EncodingCoRRE) {
      encodings[nEncodings++] = RfbProto.EncodingCoRRE;
    }
    if (preferredEncoding != RfbProto.EncodingRRE) {
      encodings[nEncodings++] = RfbProto.EncodingRRE;
    }

    if (options.compressLevel >= 0 && options.compressLevel <= 9) {
      encodings[nEncodings++] =
        RfbProto.EncodingCompressLevel0 + options.compressLevel;
    }
    if (options.jpegQuality >= 0 && options.jpegQuality <= 9) {
      encodings[nEncodings++] =
        RfbProto.EncodingQualityLevel0 + options.jpegQuality;
    }

    if (options.requestCursorUpdates) {
      encodings[nEncodings++] = RfbProto.EncodingXCursor;
      encodings[nEncodings++] = RfbProto.EncodingRichCursor;
      if (!options.ignoreCursorUpdates)
	encodings[nEncodings++] = RfbProto.EncodingPointerPos;
    }

    encodings[nEncodings++] = RfbProto.EncodingLastRect;
    encodings[nEncodings++] = RfbProto.EncodingNewFBSize;

    boolean encodingsWereChanged = false;
    if (nEncodings != nEncodingsSaved) {
      encodingsWereChanged = true;
    } else {
      for (int i = 0; i < nEncodings; i++) {
        if (encodings[i] != encodingsSaved[i]) {
          encodingsWereChanged = true;
          break;
        }
      }
    }

    if (encodingsWereChanged) {
      try {
        rfb.writeSetEncodings(encodings, nEncodings);
        if (vc != null) {
          vc.softCursorFree();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      encodingsSaved = encodings;
      nEncodingsSaved = nEncodings;
    }
  }


  //
  // setCutText() - send the given cut text to the RFB server.
  //

  void setCutText(String text) {
    try {
      if (rfb != null && rfb.inNormalProtocol) {
	rfb.writeClientCutText(text);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  //
  // Order change in session recording status. To stop recording, pass
  // null in place of the fname argument.
  //

  void setRecordingStatus(String fname) {
    synchronized(recordingSync) {
      sessionFileName = fname;
      recordingStatusChanged = true;
    }
  }

  //
  // Start or stop session recording. Returns true if this method call
  // causes recording of a new session.
  //

  boolean checkRecordingStatus() throws IOException {
    synchronized(recordingSync) {
      if (recordingStatusChanged) {
	recordingStatusChanged = false;
	if (sessionFileName != null) {
	  startRecording();
	  return true;
	} else {
	  stopRecording();
	}
      }
    }
    return false;
  }

  //
  // Start session recording.
  //

  protected void startRecording() throws IOException {
    synchronized(recordingSync) {
      if (!recordingActive) {
	// Save settings to restore them after recording the session.
	cursorUpdatesDef =
	  options.choices[options.cursorUpdatesIndex].getSelectedItem();
	eightBitColorsDef =
	  options.choices[options.eightBitColorsIndex].getSelectedItem();
	// Set options to values suitable for recording.
	options.choices[options.cursorUpdatesIndex].select("Disable");
	options.choices[options.cursorUpdatesIndex].setEnabled(false);
	options.setEncodings();
	options.choices[options.eightBitColorsIndex].select("No");
	options.choices[options.eightBitColorsIndex].setEnabled(false);
	options.setColorFormat();
      } else {
	rfb.closeSession();
      }

      System.out.println("Recording the session in " + sessionFileName);
      rfb.startSession(sessionFileName);
      recordingActive = true;
    }
  }

  //
  // Stop session recording.
  //

  protected void stopRecording() throws IOException {
    synchronized(recordingSync) {
      if (recordingActive) {
	// Restore options.
	options.choices[options.cursorUpdatesIndex].select(cursorUpdatesDef);
	options.choices[options.cursorUpdatesIndex].setEnabled(true);
	options.setEncodings();
	options.choices[options.eightBitColorsIndex].select(eightBitColorsDef);
	options.choices[options.eightBitColorsIndex].setEnabled(true);
	options.setColorFormat();

	rfb.closeSession();
	System.out.println("Session recording stopped.");
      }
      sessionFileName = null;
      recordingActive = false;
    }
  }


  //
  // readParameters() - read parameters from the html source or from the
  // command line.  On the command line, the arguments are just a sequence of
  // param_name/param_value pairs where the names and values correspond to
  // those expected in the html applet tag source.
  //

  void readParameters() {
    host = readParameter("HOST", !inAnApplet);
    if (host == null) {
      host = getCodeBase().getHost();
      if (host.equals("")) {
	fatalError("HOST parameter not specified");
      }
    }

    port = readIntParameter("PORT", 5900);

    // Read "ENCPASSWORD" or "PASSWORD" parameter if specified.
    readPasswordParameters();

    String str;
    if (inAnApplet) {
      str = readParameter("Open New Window", false);
      if (str != null && str.equalsIgnoreCase("Yes"))
	inSeparateFrame = true;
    }

    // "Show Controls" set to "No" disables button panel.
    showControls = true;
    str = readParameter("Show Controls", false);
    if (str != null && str.equalsIgnoreCase("No"))
      showControls = false;

    // "Offer Relogin" set to "No" disables "Login again" and "Close
    // window" buttons under error messages in applet mode.
    offerRelogin = true;
    str = readParameter("Offer Relogin", false);
    if (str != null && str.equalsIgnoreCase("No"))
      offerRelogin = false;

    // Do we continue showing desktop on remote disconnect?
    showOfflineDesktop = false;
    str = readParameter("Show Offline Desktop", false);
    if (str != null && str.equalsIgnoreCase("Yes"))
      showOfflineDesktop = true;

    // Fine tuning options.
    deferScreenUpdates = readIntParameter("Defer screen updates", 20);
    deferCursorUpdates = readIntParameter("Defer cursor updates", 10);
    deferUpdateRequests = readIntParameter("Defer update requests", 0);

    // Debugging options.
    debugStatsExcludeUpdates = readIntParameter("DEBUG_XU", 0);
    debugStatsMeasureUpdates = readIntParameter("DEBUG_CU", 0);

    // SocketFactory.
    socketFactory = readParameter("SocketFactory", false);
  }

  //
  // Read password parameters. If an "ENCPASSWORD" parameter is set,
  // then decrypt the password into the passwordParam string. Otherwise,
  // try to read the "PASSWORD" parameter directly to passwordParam.
  //

  private void readPasswordParameters() {
    String encPasswordParam = readParameter("ENCPASSWORD", false);
    if (encPasswordParam == null) {
      passwordParam = readParameter("PASSWORD", false);
    } else {
      // ENCPASSWORD is hexascii-encoded. Decode.
      byte[] pw = {0, 0, 0, 0, 0, 0, 0, 0};
      int len = encPasswordParam.length() / 2;
      if (len > 8)
        len = 8;
      for (int i = 0; i < len; i++) {
        String hex = encPasswordParam.substring(i*2, i*2+2);
        Integer x = new Integer(Integer.parseInt(hex, 16));
        pw[i] = x.byteValue();
      }
      // Decrypt the password.
      byte[] key = {23, 82, 107, 6, 35, 78, 88, 7};
      DesCipher des = new DesCipher(key);
      des.decrypt(pw, 0, pw, 0);
      passwordParam = new String(pw);
    }
  }

  public String readParameter(String name, boolean required) {
    if (inAnApplet) {
      String s = getParameter(name);
      if ((s == null) && required) {
	fatalError(name + " parameter not specified");
      }
      return s;
    }

    for (int i = 0; i < mainArgs.length; i += 2) {
      if (mainArgs[i].equalsIgnoreCase(name)) {
	try {
	  return mainArgs[i+1];
	} catch (Exception e) {
	  if (required) {
	    fatalError(name + " parameter not specified");
	  }
	  return null;
	}
      }
    }
    if (required) {
      fatalError(name + " parameter not specified");
    }
    return null;
  }

  int readIntParameter(String name, int defaultValue) {
    String str = readParameter(name, false);
    int result = defaultValue;
    if (str != null) {
      try {
	result = Integer.parseInt(str);
      } catch (NumberFormatException e) { }
    }
    return result;
  }

  //
  // moveFocusToDesktop() - move keyboard focus either to VncCanvas.
  //

  void moveFocusToDesktop() {
    if (vncContainer != null) {
      if (vc != null && vncContainer.isAncestorOf(vc))
	vc.requestFocus();
    }
  }

  //
  // disconnect() - close connection to server.
  //

  synchronized public void disconnect() {
    System.out.println("Disconnecting");

    if (vc != null) {
      double sec = (System.currentTimeMillis() - vc.statStartTime) / 1000.0;
      double rate = Math.round(vc.statNumUpdates / sec * 100) / 100.0;
      long nRealRects = vc.statNumPixelRects;
      long nPseudoRects = vc.statNumTotalRects - vc.statNumPixelRects;
      System.out.println("Updates received: " + vc.statNumUpdates + " (" +
                         nRealRects + " rectangles + " + nPseudoRects +
                         " pseudo), " + rate + " updates/sec");
      long numRectsOther = nRealRects - vc.statNumRectsTight
        - vc.statNumRectsZRLE - vc.statNumRectsHextile
        - vc.statNumRectsRaw - vc.statNumRectsCopy;
      System.out.println("Rectangles:" +
                         " Tight=" + vc.statNumRectsTight +
                         "(JPEG=" + vc.statNumRectsTightJPEG +
                         ") ZRLE=" + vc.statNumRectsZRLE +
                         " Hextile=" + vc.statNumRectsHextile +
                         " Raw=" + vc.statNumRectsRaw +
                         " CopyRect=" + vc.statNumRectsCopy +
                         " other=" + numRectsOther);

      long raw = vc.statNumBytesDecoded;
      long compressed = vc.statNumBytesEncoded;
      if (compressed > 0) {
          double ratio = Math.round((double)raw / compressed * 1000) / 1000.0;
          System.out.println("Pixel data: " + vc.statNumBytesDecoded +
                             " bytes, " + vc.statNumBytesEncoded +
                             " compressed, ratio " + ratio);
      }
    }

    if (rfb != null && !rfb.closed())
      rfb.close();
    options.dispose();
    clipboard.dispose();
    if (rec != null)
      rec.dispose();

    if (inAnApplet) {
      showMessage("Disconnected");
    } else {
      System.exit(0);
    }
  }

  //
  // fatalError() - print out a fatal error message.
  // FIXME: Do we really need two versions of the fatalError() method?
  //

  synchronized public void fatalError(String str) {
    System.out.println(str);

    if (inAnApplet) {
      // vncContainer null, applet not inited,
      // can not present the error to the user.
      Thread.currentThread().stop();
    } else {
      System.exit(1);
    }
  }

  synchronized public void fatalError(String str, Exception e) {
 
    if (rfb != null && rfb.closed()) {
      // Not necessary to show error message if the error was caused
      // by I/O problems after the rfb.close() method call.
      System.out.println("RFB thread finished");
      return;
    }

    System.out.println(str);
    e.printStackTrace();

    if (rfb != null)
      rfb.close();

    if (inAnApplet) {
      showMessage(str);
    } else {
      System.exit(1);
    }
  }

  //
  // Show message text and optionally "Relogin" and "Close" buttons.
  //

  void showMessage(String msg) {
    vncContainer.removeAll();

    Label errLabel = new Label(msg, Label.CENTER);
    errLabel.setFont(new Font("Helvetica", Font.PLAIN, 12));

    if (offerRelogin) {

      Panel gridPanel = new Panel(new GridLayout(0, 1));
      Panel outerPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
      outerPanel.add(gridPanel);
      vncContainer.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 16));
      vncContainer.add(outerPanel);
      Panel textPanel = new Panel(new FlowLayout(FlowLayout.CENTER));
      textPanel.add(errLabel);
      gridPanel.add(textPanel);
      gridPanel.add(new ReloginPanel(this));

    } else {

      vncContainer.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 30));
      vncContainer.add(errLabel);

    }

    if (inSeparateFrame) {
      vncFrame.pack();
    } else {
      validate();
    }
  }

  //
  // Stop the applet.
  // Main applet thread will terminate on first exception
  // after seeing that rfbThread has been set to null.
  //

  public void stop() {
    System.out.println("Stopping applet");
    rfbThread = null;
  }

  //
  // This method is called before the applet is destroyed.
  //

  public void destroy() {
    System.out.println("Destroying applet");

    vncContainer.removeAll();
    options.dispose();
    clipboard.dispose();
    if (rec != null)
      rec.dispose();
    if (rfb != null && !rfb.closed())
      rfb.close();
    if (inSeparateFrame)
      vncFrame.dispose();
  }

  //
  // Start/stop receiving mouse events.
  //

  public void enableInput(boolean enable) {
    vc.enableInput(enable);
  }
  
  //
  // Resize framebuffer if autoScale is enabled.
  //
  
  public void componentResized(ComponentEvent e) {
    if (e.getComponent() == vncFrame) {
      if (options.autoScale) {
        if (vc != null) {
          if (!vc.isFirstSizeAutoUpdate) {
            vc.updateFramebufferSize();
          }
        }
      }
    }
  }
  
  //
  // Ignore component events we're not interested in.
  //
  
  public void componentShown(ComponentEvent e) { }
  public void componentMoved(ComponentEvent e) { }
  public void componentHidden(ComponentEvent e) { }

  //
  // Close application properly on window close event.
  //

  public void windowClosing(WindowEvent evt) {
    System.out.println("Closing window");
    if (rfb != null)
      disconnect();

    vncContainer.hide();

    if (!inAnApplet) {
      System.exit(0);
    }
  }

  //
  // Ignore window events we're not interested in.
  //

  public void windowActivated(WindowEvent evt) {}
  public void windowDeactivated (WindowEvent evt) {}
  public void windowOpened(WindowEvent evt) {}
  public void windowClosed(WindowEvent evt) {}
  public void windowIconified(WindowEvent evt) {}
  public void windowDeiconified(WindowEvent evt) {}
}