Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2009-2013 Pierre Ossman <ossman@cendio.se> for Cendio AB
  3. * Copyright (C) 2011-2013 D. R. Commander. All Rights Reserved.
  4. * Copyright (C) 2011-2015 Brian P. Hinz
  5. *
  6. * This is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This software is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this software; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  19. * USA.
  20. */
  21. //
  22. // CConn
  23. //
  24. // Methods on CConn are called from both the GUI thread and the thread which
  25. // processes incoming RFB messages ("the RFB thread"). This means we need to
  26. // be careful with synchronization here.
  27. //
  28. // Any access to writer() must not only be synchronized, but we must also make
  29. // sure that the connection is in RFBSTATE_NORMAL. We are guaranteed this for
  30. // any code called after serverInit() has been called. Since the DesktopWindow
  31. // isn't created until then, any methods called only from DesktopWindow can
  32. // assume that we are in RFBSTATE_NORMAL.
  33. package com.tigervnc.vncviewer;
  34. import java.awt.*;
  35. import java.awt.event.*;
  36. import java.io.IOException;
  37. import java.io.InputStream;
  38. import java.io.FileInputStream;
  39. import java.io.FileNotFoundException;
  40. import java.util.jar.Attributes;
  41. import java.util.jar.Manifest;
  42. import javax.swing.*;
  43. import javax.swing.ImageIcon;
  44. import java.net.InetSocketAddress;
  45. import java.net.SocketException;
  46. import java.util.*;
  47. import com.tigervnc.rdr.*;
  48. import com.tigervnc.rfb.*;
  49. import com.tigervnc.rfb.Point;
  50. import com.tigervnc.rfb.Exception;
  51. import com.tigervnc.network.Socket;
  52. import com.tigervnc.network.TcpSocket;
  53. public class CConn extends CConnection implements
  54. UserPasswdGetter, UserMsgBox, OptionsDialogCallback,
  55. FdInStreamBlockCallback, ActionListener {
  56. public final PixelFormat getPreferredPF() { return fullColourPF; }
  57. static final PixelFormat verylowColourPF =
  58. new PixelFormat(8, 3, false, true, 1, 1, 1, 2, 1, 0);
  59. static final PixelFormat lowColourPF =
  60. new PixelFormat(8, 6, false, true, 3, 3, 3, 4, 2, 0);
  61. static final PixelFormat mediumColourPF =
  62. new PixelFormat(8, 8, false, false, 7, 7, 3, 0, 3, 6);
  63. static final int KEY_LOC_SHIFT_R = 0;
  64. static final int KEY_LOC_SHIFT_L = 16;
  65. static final int SUPER_MASK = 1<<15;
  66. ////////////////////////////////////////////////////////////////////
  67. // The following methods are all called from the RFB thread
  68. public CConn(VncViewer viewer_, Socket sock_,
  69. String vncServerName)
  70. {
  71. serverHost = null; serverPort = 0; sock = sock_; viewer = viewer_;
  72. pendingPFChange = false;
  73. currentEncoding = Encodings.encodingTight; lastServerEncoding = -1;
  74. fullColour = viewer.fullColour.getValue();
  75. lowColourLevel = viewer.lowColourLevel.getValue();
  76. autoSelect = viewer.autoSelect.getValue();
  77. formatChange = false; encodingChange = false;
  78. fullScreen = viewer.fullScreen.getValue();
  79. menuKeyCode = MenuKey.getMenuKeyCode();
  80. options = new OptionsDialog(this);
  81. options.initDialog();
  82. clipboardDialog = new ClipboardDialog(this);
  83. firstUpdate = true; pendingUpdate = false; continuousUpdates = false;
  84. forceNonincremental = true; supportsSyncFence = false;
  85. downKeySym = new HashMap<Integer, Integer>();
  86. setShared(viewer.shared.getValue());
  87. upg = this;
  88. msg = this;
  89. String encStr = viewer.preferredEncoding.getValue();
  90. int encNum = Encodings.encodingNum(encStr);
  91. if (encNum != -1) {
  92. currentEncoding = encNum;
  93. }
  94. cp.supportsDesktopResize = true;
  95. cp.supportsExtendedDesktopSize = true;
  96. cp.supportsSetDesktopSize = false;
  97. cp.supportsClientRedirect = true;
  98. cp.supportsDesktopRename = true;
  99. cp.supportsLocalCursor = viewer.useLocalCursor.getValue();
  100. cp.customCompressLevel = viewer.customCompressLevel.getValue();
  101. cp.compressLevel = viewer.compressLevel.getValue();
  102. cp.noJpeg = viewer.noJpeg.getValue();
  103. cp.qualityLevel = viewer.qualityLevel.getValue();
  104. initMenu();
  105. if (sock != null) {
  106. String name = sock.getPeerEndpoint();
  107. vlog.info("Accepted connection from " + name);
  108. } else {
  109. if (vncServerName != null &&
  110. !viewer.alwaysShowServerDialog.getValue()) {
  111. serverHost = Hostname.getHost(vncServerName);
  112. serverPort = Hostname.getPort(vncServerName);
  113. } else {
  114. ServerDialog dlg = new ServerDialog(options, vncServerName, this);
  115. boolean ret = dlg.showDialog();
  116. if (!ret) {
  117. close();
  118. return;
  119. }
  120. serverHost = viewer.vncServerName.getValueStr();
  121. serverPort = viewer.vncServerPort.getValue();
  122. }
  123. try {
  124. sock = new TcpSocket(serverHost, serverPort);
  125. } catch (java.lang.Exception e) {
  126. throw new Exception(e.getMessage());
  127. }
  128. vlog.info("connected to host "+serverHost+" port "+serverPort);
  129. }
  130. sock.inStream().setBlockCallback(this);
  131. setServerName(serverHost);
  132. setStreams(sock.inStream(), sock.outStream());
  133. initialiseProtocol();
  134. }
  135. public void refreshFramebuffer()
  136. {
  137. forceNonincremental = true;
  138. // Without fences, we cannot safely trigger an update request directly
  139. // but must wait for the next update to arrive.
  140. if (supportsSyncFence)
  141. requestNewUpdate();
  142. }
  143. public boolean showMsgBox(int flags, String title, String text)
  144. {
  145. //StringBuffer titleText = new StringBuffer("VNC Viewer: "+title);
  146. return true;
  147. }
  148. // deleteWindow() is called when the user closes the desktop or menu windows.
  149. void deleteWindow() {
  150. if (viewport != null)
  151. viewport.dispose();
  152. viewport = null;
  153. }
  154. // blockCallback() is called when reading from the socket would block.
  155. public void blockCallback() {
  156. try {
  157. synchronized(this) {
  158. wait(1);
  159. }
  160. } catch (java.lang.InterruptedException e) {
  161. throw new Exception(e.getMessage());
  162. }
  163. }
  164. // getUserPasswd() is called by the CSecurity object when it needs us to read
  165. // a password from the user.
  166. public final boolean getUserPasswd(StringBuffer user, StringBuffer passwd) {
  167. String title = ("VNC Authentication ["
  168. +csecurity.description() + "]");
  169. String passwordFileStr = viewer.passwordFile.getValue();
  170. PasswdDialog dlg;
  171. if (user == null && passwordFileStr != "") {
  172. InputStream fp = null;
  173. try {
  174. fp = new FileInputStream(passwordFileStr);
  175. } catch(FileNotFoundException e) {
  176. throw new Exception("Opening password file failed");
  177. }
  178. byte[] obfPwd = new byte[256];
  179. try {
  180. fp.read(obfPwd);
  181. fp.close();
  182. } catch(IOException e) {
  183. throw new Exception("Failed to read VncPasswd file");
  184. }
  185. String PlainPasswd = VncAuth.unobfuscatePasswd(obfPwd);
  186. passwd.append(PlainPasswd);
  187. passwd.setLength(PlainPasswd.length());
  188. return true;
  189. }
  190. if (user == null) {
  191. dlg = new PasswdDialog(title, (user == null), (passwd == null));
  192. } else {
  193. if ((passwd == null) && viewer.sendLocalUsername.getValue()) {
  194. user.append((String)System.getProperties().get("user.name"));
  195. return true;
  196. }
  197. dlg = new PasswdDialog(title, viewer.sendLocalUsername.getValue(),
  198. (passwd == null));
  199. }
  200. if (!dlg.showDialog()) return false;
  201. if (user != null) {
  202. if (viewer.sendLocalUsername.getValue()) {
  203. user.append((String)System.getProperties().get("user.name"));
  204. } else {
  205. user.append(dlg.userEntry.getText());
  206. }
  207. }
  208. if (passwd != null)
  209. passwd.append(new String(dlg.passwdEntry.getPassword()));
  210. return true;
  211. }
  212. // CConnection callback methods
  213. // serverInit() is called when the serverInit message has been received. At
  214. // this point we create the desktop window and display it. We also tell the
  215. // server the pixel format and encodings to use and request the first update.
  216. public void serverInit() {
  217. super.serverInit();
  218. // If using AutoSelect with old servers, start in FullColor
  219. // mode. See comment in autoSelectFormatAndEncoding.
  220. if (cp.beforeVersion(3, 8) && autoSelect)
  221. fullColour = true;
  222. serverPF = cp.pf();
  223. desktop = new DesktopWindow(cp.width, cp.height, serverPF, this);
  224. fullColourPF = desktop.getPreferredPF();
  225. // Force a switch to the format and encoding we'd like
  226. formatChange = true; encodingChange = true;
  227. // And kick off the update cycle
  228. requestNewUpdate();
  229. // This initial update request is a bit of a corner case, so we need
  230. // to help out setting the correct format here.
  231. assert(pendingPFChange);
  232. desktop.setServerPF(pendingPF);
  233. cp.setPF(pendingPF);
  234. pendingPFChange = false;
  235. if (viewer.embed.getValue()) {
  236. desktop.setScaledSize();
  237. setupEmbeddedFrame();
  238. } else {
  239. recreateViewport();
  240. }
  241. }
  242. void setupEmbeddedFrame() {
  243. UIManager.getDefaults().put("ScrollPane.ancestorInputMap",
  244. new UIDefaults.LazyInputMap(new Object[]{}));
  245. JScrollPane sp = new JScrollPane();
  246. sp.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
  247. sp.getViewport().setBackground(Color.BLACK);
  248. InputMap im = sp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
  249. int ctrlAltShiftMask = Event.SHIFT_MASK | Event.CTRL_MASK | Event.ALT_MASK;
  250. if (im != null) {
  251. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, ctrlAltShiftMask),
  252. "unitScrollUp");
  253. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, ctrlAltShiftMask),
  254. "unitScrollDown");
  255. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, ctrlAltShiftMask),
  256. "unitScrollLeft");
  257. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, ctrlAltShiftMask),
  258. "unitScrollRight");
  259. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, ctrlAltShiftMask),
  260. "scrollUp");
  261. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, ctrlAltShiftMask),
  262. "scrollDown");
  263. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, ctrlAltShiftMask),
  264. "scrollLeft");
  265. im.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, ctrlAltShiftMask),
  266. "scrollRight");
  267. }
  268. sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  269. sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
  270. sp.getViewport().setView(desktop);
  271. viewer.getContentPane().removeAll();
  272. viewer.add(sp);
  273. viewer.addFocusListener(new FocusAdapter() {
  274. public void focusGained(FocusEvent e) {
  275. if (desktop.isAncestorOf(viewer))
  276. desktop.requestFocus();
  277. }
  278. public void focusLost(FocusEvent e) {
  279. releaseDownKeys();
  280. }
  281. });
  282. viewer.validate();
  283. desktop.requestFocus();
  284. }
  285. // setDesktopSize() is called when the desktop size changes (including when
  286. // it is set initially).
  287. public void setDesktopSize(int w, int h) {
  288. super.setDesktopSize(w, h);
  289. resizeFramebuffer();
  290. }
  291. // setExtendedDesktopSize() is a more advanced version of setDesktopSize()
  292. public void setExtendedDesktopSize(int reason, int result, int w, int h,
  293. ScreenSet layout) {
  294. super.setExtendedDesktopSize(reason, result, w, h, layout);
  295. if ((reason == screenTypes.reasonClient) &&
  296. (result != screenTypes.resultSuccess)) {
  297. vlog.error("SetDesktopSize failed: " + result);
  298. return;
  299. }
  300. resizeFramebuffer();
  301. }
  302. // clientRedirect() migrates the client to another host/port
  303. public void clientRedirect(int port, String host,
  304. String x509subject) {
  305. try {
  306. sock.close();
  307. setServerPort(port);
  308. sock = new TcpSocket(host, port);
  309. vlog.info("Redirected to "+host+":"+port);
  310. VncViewer.newViewer(viewer, sock, true);
  311. } catch (java.lang.Exception e) {
  312. throw new Exception(e.getMessage());
  313. }
  314. }
  315. // setName() is called when the desktop name changes
  316. public void setName(String name) {
  317. super.setName(name);
  318. if (viewport != null) {
  319. viewport.setTitle(name+" - TigerVNC");
  320. }
  321. }
  322. // framebufferUpdateStart() is called at the beginning of an update.
  323. // Here we try to send out a new framebuffer update request so that the
  324. // next update can be sent out in parallel with us decoding the current
  325. // one.
  326. public void framebufferUpdateStart()
  327. {
  328. // Note: This might not be true if sync fences are supported
  329. pendingUpdate = false;
  330. requestNewUpdate();
  331. }
  332. // framebufferUpdateEnd() is called at the end of an update.
  333. // For each rectangle, the FdInStream will have timed the speed
  334. // of the connection, allowing us to select format and encoding
  335. // appropriately, and then request another incremental update.
  336. public void framebufferUpdateEnd()
  337. {
  338. desktop.updateWindow();
  339. if (firstUpdate) {
  340. int width, height;
  341. // We need fences to make extra update requests and continuous
  342. // updates "safe". See fence() for the next step.
  343. if (cp.supportsFence)
  344. writer().writeFence(fenceTypes.fenceFlagRequest | fenceTypes.fenceFlagSyncNext, 0, null);
  345. if (cp.supportsSetDesktopSize &&
  346. viewer.desktopSize.getValue() != null &&
  347. viewer.desktopSize.getValue().split("x").length == 2) {
  348. width = Integer.parseInt(viewer.desktopSize.getValue().split("x")[0]);
  349. height = Integer.parseInt(viewer.desktopSize.getValue().split("x")[1]);
  350. ScreenSet layout;
  351. layout = cp.screenLayout;
  352. if (layout.num_screens() == 0)
  353. layout.add_screen(new Screen());
  354. else if (layout.num_screens() != 1) {
  355. while (true) {
  356. Iterator<Screen> iter = layout.screens.iterator();
  357. Screen screen = (Screen)iter.next();
  358. if (!iter.hasNext())
  359. break;
  360. layout.remove_screen(screen.id);
  361. }
  362. }
  363. Screen screen0 = (Screen)layout.screens.iterator().next();
  364. screen0.dimensions.tl.x = 0;
  365. screen0.dimensions.tl.y = 0;
  366. screen0.dimensions.br.x = width;
  367. screen0.dimensions.br.y = height;
  368. writer().writeSetDesktopSize(width, height, layout);
  369. }
  370. firstUpdate = false;
  371. }
  372. // A format change has been scheduled and we are now past the update
  373. // with the old format. Time to active the new one.
  374. if (pendingPFChange) {
  375. desktop.setServerPF(pendingPF);
  376. cp.setPF(pendingPF);
  377. pendingPFChange = false;
  378. }
  379. // Compute new settings based on updated bandwidth values
  380. if (autoSelect)
  381. autoSelectFormatAndEncoding();
  382. }
  383. // The rest of the callbacks are fairly self-explanatory...
  384. public void setColourMapEntries(int firstColour, int nColours, int[] rgbs) {
  385. desktop.setColourMapEntries(firstColour, nColours, rgbs);
  386. }
  387. public void bell() {
  388. if (viewer.acceptBell.getValue())
  389. desktop.getToolkit().beep();
  390. }
  391. public void serverCutText(String str, int len) {
  392. if (viewer.acceptClipboard.getValue())
  393. clipboardDialog.serverCutText(str, len);
  394. }
  395. // We start timing on beginRect and stop timing on endRect, to
  396. // avoid skewing the bandwidth estimation as a result of the server
  397. // being slow or the network having high latency
  398. public void beginRect(Rect r, int encoding) {
  399. sock.inStream().startTiming();
  400. if (encoding != Encodings.encodingCopyRect) {
  401. lastServerEncoding = encoding;
  402. }
  403. }
  404. public void endRect(Rect r, int encoding) {
  405. sock.inStream().stopTiming();
  406. }
  407. public void fillRect(Rect r, int p) {
  408. desktop.fillRect(r.tl.x, r.tl.y, r.width(), r.height(), p);
  409. }
  410. public void imageRect(Rect r, Object p) {
  411. desktop.imageRect(r.tl.x, r.tl.y, r.width(), r.height(), p);
  412. }
  413. public void copyRect(Rect r, int sx, int sy) {
  414. desktop.copyRect(r.tl.x, r.tl.y, r.width(), r.height(), sx, sy);
  415. }
  416. public void setCursor(int width, int height, Point hotspot,
  417. int[] data, byte[] mask) {
  418. desktop.setCursor(width, height, hotspot, data, mask);
  419. }
  420. public void fence(int flags, int len, byte[] data)
  421. {
  422. // can't call super.super.fence(flags, len, data);
  423. cp.supportsFence = true;
  424. if ((flags & fenceTypes.fenceFlagRequest) != 0) {
  425. // We handle everything synchronously so we trivially honor these modes
  426. flags = flags & (fenceTypes.fenceFlagBlockBefore | fenceTypes.fenceFlagBlockAfter);
  427. writer().writeFence(flags, len, data);
  428. return;
  429. }
  430. if (len == 0) {
  431. // Initial probe
  432. if ((flags & fenceTypes.fenceFlagSyncNext) != 0) {
  433. supportsSyncFence = true;
  434. if (cp.supportsContinuousUpdates) {
  435. vlog.info("Enabling continuous updates");
  436. continuousUpdates = true;
  437. writer().writeEnableContinuousUpdates(true, 0, 0, cp.width, cp.height);
  438. }
  439. }
  440. } else {
  441. // Pixel format change
  442. MemInStream memStream = new MemInStream(data, 0, len);
  443. PixelFormat pf = new PixelFormat();
  444. pf.read(memStream);
  445. desktop.setServerPF(pf);
  446. cp.setPF(pf);
  447. }
  448. }
  449. private void resizeFramebuffer()
  450. {
  451. if (desktop == null)
  452. return;
  453. if (continuousUpdates)
  454. writer().writeEnableContinuousUpdates(true, 0, 0, cp.width, cp.height);
  455. if ((cp.width == 0) && (cp.height == 0))
  456. return;
  457. if ((desktop.width() == cp.width) && (desktop.height() == cp.height))
  458. return;
  459. desktop.resize();
  460. if (viewer.embed.getValue()) {
  461. desktop.setScaledSize();
  462. setupEmbeddedFrame();
  463. } else {
  464. recreateViewport();
  465. }
  466. }
  467. public void setEmbeddedFeatures(boolean s) {
  468. menu.fullScreen.setEnabled(s);
  469. menu.newConn.setEnabled(s);
  470. options.fullScreen.setEnabled(s);
  471. options.fullScreenAllMonitors.setEnabled(s);
  472. options.scalingFactor.setEnabled(s);
  473. }
  474. // recreateViewport() recreates our top-level window. This seems to be
  475. // better than attempting to resize the existing window, at least with
  476. // various X window managers.
  477. public void recreateViewport() {
  478. if (viewer.embed.getValue())
  479. return;
  480. if (viewport != null) viewport.dispose();
  481. viewport = new Viewport(cp.name(), this);
  482. viewport.setUndecorated(fullScreen);
  483. desktop.setViewport(viewport);
  484. reconfigureViewport();
  485. if ((cp.width > 0) && (cp.height > 0))
  486. viewport.setVisible(true);
  487. desktop.requestFocusInWindow();
  488. }
  489. private void reconfigureViewport() {
  490. boolean pack = true;
  491. Dimension dpySize = viewport.getScreenSize();
  492. desktop.setScaledSize();
  493. int w = desktop.scaledWidth;
  494. int h = desktop.scaledHeight;
  495. if (fullScreen) {
  496. if (!viewer.fullScreenAllMonitors.getValue())
  497. viewport.setExtendedState(JFrame.MAXIMIZED_BOTH);
  498. viewport.setBounds(viewport.getScreenBounds());
  499. if (!viewer.fullScreenAllMonitors.getValue())
  500. Viewport.setFullScreenWindow(viewport);
  501. } else {
  502. int wmDecorationWidth = viewport.getInsets().left + viewport.getInsets().right;
  503. int wmDecorationHeight = viewport.getInsets().top + viewport.getInsets().bottom;
  504. if (w + wmDecorationWidth >= dpySize.width) {
  505. w = dpySize.width - wmDecorationWidth;
  506. pack = false;
  507. }
  508. if (h + wmDecorationHeight >= dpySize.height) {
  509. h = dpySize.height - wmDecorationHeight;
  510. pack = false;
  511. }
  512. if (viewport.getExtendedState() == JFrame.MAXIMIZED_BOTH) {
  513. w = viewport.getSize().width;
  514. h = viewport.getSize().height;
  515. int x = viewport.getLocation().x;
  516. int y = viewport.getLocation().y;
  517. viewport.setGeometry(x, y, w, h, pack);
  518. } else {
  519. int x = (dpySize.width - w - wmDecorationWidth) / 2;
  520. int y = (dpySize.height - h - wmDecorationHeight)/2;
  521. viewport.setExtendedState(JFrame.NORMAL);
  522. viewport.setGeometry(x, y, w, h, pack);
  523. }
  524. Viewport.setFullScreenWindow(null);
  525. }
  526. }
  527. // autoSelectFormatAndEncoding() chooses the format and encoding appropriate
  528. // to the connection speed:
  529. //
  530. // First we wait for at least one second of bandwidth measurement.
  531. //
  532. // Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
  533. // which should be perceptually lossless.
  534. //
  535. // If the bandwidth is below that, we choose a more lossy JPEG quality.
  536. //
  537. // If the bandwidth drops below 256 Kbps, we switch to palette mode.
  538. //
  539. // Note: The system here is fairly arbitrary and should be replaced
  540. // with something more intelligent at the server end.
  541. //
  542. private void autoSelectFormatAndEncoding() {
  543. long kbitsPerSecond = sock.inStream().kbitsPerSecond();
  544. long timeWaited = sock.inStream().timeWaited();
  545. boolean newFullColour = fullColour;
  546. int newQualityLevel = cp.qualityLevel;
  547. // Always use Tight
  548. if (currentEncoding != Encodings.encodingTight) {
  549. currentEncoding = Encodings.encodingTight;
  550. encodingChange = true;
  551. }
  552. // Check that we have a decent bandwidth measurement
  553. if ((kbitsPerSecond == 0) || (timeWaited < 100))
  554. return;
  555. // Select appropriate quality level
  556. if (!cp.noJpeg) {
  557. if (kbitsPerSecond > 16000)
  558. newQualityLevel = 8;
  559. else
  560. newQualityLevel = 6;
  561. if (newQualityLevel != cp.qualityLevel) {
  562. vlog.info("Throughput "+kbitsPerSecond+
  563. " kbit/s - changing to quality "+newQualityLevel);
  564. cp.qualityLevel = newQualityLevel;
  565. viewer.qualityLevel.setParam(Integer.toString(newQualityLevel));
  566. encodingChange = true;
  567. }
  568. }
  569. if (cp.beforeVersion(3, 8)) {
  570. // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
  571. // cursors "asynchronously". If this happens in the middle of a
  572. // pixel format change, the server will encode the cursor with
  573. // the old format, but the client will try to decode it
  574. // according to the new format. This will lead to a
  575. // crash. Therefore, we do not allow automatic format change for
  576. // old servers.
  577. return;
  578. }
  579. // Select best color level
  580. newFullColour = (kbitsPerSecond > 256);
  581. if (newFullColour != fullColour) {
  582. vlog.info("Throughput "+kbitsPerSecond+
  583. " kbit/s - full color is now "+
  584. (newFullColour ? "enabled" : "disabled"));
  585. fullColour = newFullColour;
  586. formatChange = true;
  587. forceNonincremental = true;
  588. }
  589. }
  590. // requestNewUpdate() requests an update from the server, having set the
  591. // format and encoding appropriately.
  592. private void requestNewUpdate()
  593. {
  594. if (formatChange) {
  595. PixelFormat pf;
  596. /* Catch incorrect requestNewUpdate calls */
  597. assert(!pendingUpdate || supportsSyncFence);
  598. if (fullColour) {
  599. pf = fullColourPF;
  600. } else {
  601. if (lowColourLevel == 0) {
  602. pf = verylowColourPF;
  603. } else if (lowColourLevel == 1) {
  604. pf = lowColourPF;
  605. } else {
  606. pf = mediumColourPF;
  607. }
  608. }
  609. if (supportsSyncFence) {
  610. // We let the fence carry the pixel format and switch once we
  611. // get the response back. That way we will be synchronised with
  612. // when the server switches.
  613. MemOutStream memStream = new MemOutStream();
  614. pf.write(memStream);
  615. writer().writeFence(fenceTypes.fenceFlagRequest | fenceTypes.fenceFlagSyncNext,
  616. memStream.length(), (byte[])memStream.data());
  617. } else {
  618. // New requests are sent out at the start of processing the last
  619. // one, so we cannot switch our internal format right now (doing so
  620. // would mean misdecoding the current update).
  621. pendingPFChange = true;
  622. pendingPF = pf;
  623. }
  624. String str = pf.print();
  625. vlog.info("Using pixel format " + str);
  626. writer().writeSetPixelFormat(pf);
  627. formatChange = false;
  628. }
  629. checkEncodings();
  630. if (forceNonincremental || !continuousUpdates) {
  631. pendingUpdate = true;
  632. writer().writeFramebufferUpdateRequest(new Rect(0, 0, cp.width, cp.height),
  633. !forceNonincremental);
  634. }
  635. forceNonincremental = false;
  636. }
  637. ////////////////////////////////////////////////////////////////////
  638. // The following methods are all called from the GUI thread
  639. // close() shuts down the socket, thus waking up the RFB thread.
  640. public void close() {
  641. if (closeListener != null) {
  642. viewer.embed.setParam(true);
  643. if (VncViewer.nViewers == 1) {
  644. JFrame f = (JFrame)JOptionPane.getFrameForComponent(viewer);
  645. if (f != null)
  646. f.dispatchEvent(new WindowEvent(f, WindowEvent.WINDOW_CLOSING));
  647. }
  648. }
  649. deleteWindow();
  650. shuttingDown = true;
  651. try {
  652. if (sock != null)
  653. sock.shutdown();
  654. } catch (java.lang.Exception e) {
  655. throw new Exception(e.getMessage());
  656. }
  657. }
  658. // Menu callbacks. These are guaranteed only to be called after serverInit()
  659. // has been called, since the menu is only accessible from the DesktopWindow
  660. private void initMenu() {
  661. menu = new F8Menu(this);
  662. }
  663. void showMenu(int x, int y) {
  664. String os = System.getProperty("os.name");
  665. if (os.startsWith("Windows"))
  666. com.sun.java.swing.plaf.windows.WindowsLookAndFeel.setMnemonicHidden(false);
  667. menu.show(desktop, x, y);
  668. }
  669. void showAbout() {
  670. String pkgDate = "";
  671. String pkgTime = "";
  672. try {
  673. Manifest manifest = new Manifest(VncViewer.timestamp);
  674. Attributes attributes = manifest.getMainAttributes();
  675. pkgDate = attributes.getValue("Package-Date");
  676. pkgTime = attributes.getValue("Package-Time");
  677. } catch (java.lang.Exception e) { }
  678. Window fullScreenWindow = Viewport.getFullScreenWindow();
  679. if (fullScreenWindow != null)
  680. Viewport.setFullScreenWindow(null);
  681. String msg =
  682. String.format(VncViewer.aboutText, VncViewer.version, VncViewer.build,
  683. VncViewer.buildDate, VncViewer.buildTime);
  684. JOptionPane op =
  685. new JOptionPane(msg, JOptionPane.INFORMATION_MESSAGE,
  686. JOptionPane.DEFAULT_OPTION, VncViewer.logoIcon);
  687. JDialog dlg = op.createDialog(desktop, "About TigerVNC Viewer for Java");
  688. dlg.setIconImage(VncViewer.frameIcon);
  689. dlg.setAlwaysOnTop(true);
  690. dlg.setVisible(true);
  691. if (fullScreenWindow != null)
  692. Viewport.setFullScreenWindow(fullScreenWindow);
  693. }
  694. void showInfo() {
  695. Window fullScreenWindow = Viewport.getFullScreenWindow();
  696. if (fullScreenWindow != null)
  697. Viewport.setFullScreenWindow(null);
  698. String info = new String("Desktop name: %s%n"+
  699. "Host: %s:%d%n"+
  700. "Size: %dx%d%n"+
  701. "Pixel format: %s%n"+
  702. " (server default: %s)%n"+
  703. "Requested encoding: %s%n"+
  704. "Last used encoding: %s%n"+
  705. "Line speed estimate: %d kbit/s%n"+
  706. "Protocol version: %d.%d%n"+
  707. "Security method: %s [%s]%n");
  708. String msg =
  709. String.format(info, cp.name(),
  710. sock.getPeerName(), sock.getPeerPort(),
  711. cp.width, cp.height,
  712. desktop.getPF().print(),
  713. serverPF.print(),
  714. Encodings.encodingName(currentEncoding),
  715. Encodings.encodingName(lastServerEncoding),
  716. sock.inStream().kbitsPerSecond(),
  717. cp.majorVersion, cp.minorVersion,
  718. Security.secTypeName(csecurity.getType()),
  719. csecurity.description());
  720. JOptionPane op = new JOptionPane(msg, JOptionPane.PLAIN_MESSAGE,
  721. JOptionPane.DEFAULT_OPTION);
  722. JDialog dlg = op.createDialog(desktop, "VNC connection info");
  723. dlg.setIconImage(VncViewer.frameIcon);
  724. dlg.setAlwaysOnTop(true);
  725. dlg.setVisible(true);
  726. if (fullScreenWindow != null)
  727. Viewport.setFullScreenWindow(fullScreenWindow);
  728. }
  729. public void refresh() {
  730. writer().writeFramebufferUpdateRequest(new Rect(0,0,cp.width,cp.height), false);
  731. pendingUpdate = true;
  732. }
  733. // OptionsDialogCallback. setOptions() sets the options dialog's checkboxes
  734. // etc to reflect our flags. getOptions() sets our flags according to the
  735. // options dialog's checkboxes. They are both called from the GUI thread.
  736. // Some of the flags are also accessed by the RFB thread. I believe that
  737. // reading and writing boolean and int values in java is atomic, so there is
  738. // no need for synchronization.
  739. public void setOptions() {
  740. int digit;
  741. options.autoSelect.setSelected(autoSelect);
  742. options.fullColour.setSelected(fullColour);
  743. options.veryLowColour.setSelected(!fullColour && lowColourLevel == 0);
  744. options.lowColour.setSelected(!fullColour && lowColourLevel == 1);
  745. options.mediumColour.setSelected(!fullColour && lowColourLevel == 2);
  746. options.tight.setSelected(currentEncoding == Encodings.encodingTight);
  747. options.zrle.setSelected(currentEncoding == Encodings.encodingZRLE);
  748. options.hextile.setSelected(currentEncoding == Encodings.encodingHextile);
  749. options.raw.setSelected(currentEncoding == Encodings.encodingRaw);
  750. options.customCompressLevel.setSelected(viewer.customCompressLevel.getValue());
  751. digit = 0 + viewer.compressLevel.getValue();
  752. if (digit >= 0 && digit <= 9) {
  753. options.compressLevel.setSelectedItem(digit);
  754. } else {
  755. options.compressLevel.setSelectedItem(Integer.parseInt(viewer.compressLevel.getDefaultStr()));
  756. }
  757. options.noJpeg.setSelected(!viewer.noJpeg.getValue());
  758. digit = 0 + viewer.qualityLevel.getValue();
  759. if (digit >= 0 && digit <= 9) {
  760. options.qualityLevel.setSelectedItem(digit);
  761. } else {
  762. options.qualityLevel.setSelectedItem(Integer.parseInt(viewer.qualityLevel.getDefaultStr()));
  763. }
  764. options.viewOnly.setSelected(viewer.viewOnly.getValue());
  765. options.acceptClipboard.setSelected(viewer.acceptClipboard.getValue());
  766. options.sendClipboard.setSelected(viewer.sendClipboard.getValue());
  767. options.menuKey.setSelectedItem(KeyEvent.getKeyText(MenuKey.getMenuKeyCode()));
  768. options.sendLocalUsername.setSelected(viewer.sendLocalUsername.getValue());
  769. if (state() == RFBSTATE_NORMAL) {
  770. options.shared.setEnabled(false);
  771. options.secVeNCrypt.setEnabled(false);
  772. options.encNone.setEnabled(false);
  773. options.encTLS.setEnabled(false);
  774. options.encX509.setEnabled(false);
  775. options.ca.setEnabled(false);
  776. options.crl.setEnabled(false);
  777. options.secIdent.setEnabled(false);
  778. options.secNone.setEnabled(false);
  779. options.secVnc.setEnabled(false);
  780. options.secPlain.setEnabled(false);
  781. options.sendLocalUsername.setEnabled(false);
  782. options.cfLoadButton.setEnabled(false);
  783. options.cfSaveAsButton.setEnabled(true);
  784. } else {
  785. options.shared.setSelected(viewer.shared.getValue());
  786. options.sendLocalUsername.setSelected(viewer.sendLocalUsername.getValue());
  787. options.cfSaveAsButton.setEnabled(false);
  788. /* Process non-VeNCrypt sectypes */
  789. java.util.List<Integer> secTypes = new ArrayList<Integer>();
  790. secTypes = Security.GetEnabledSecTypes();
  791. for (Iterator<Integer> i = secTypes.iterator(); i.hasNext();) {
  792. switch ((Integer)i.next()) {
  793. case Security.secTypeVeNCrypt:
  794. options.secVeNCrypt.setSelected(UserPreferences.getBool("viewer", "secVeNCrypt", true));
  795. break;
  796. case Security.secTypeNone:
  797. options.encNone.setSelected(true);
  798. options.secNone.setSelected(UserPreferences.getBool("viewer", "secTypeNone", true));
  799. break;
  800. case Security.secTypeVncAuth:
  801. options.encNone.setSelected(true);
  802. options.secVnc.setSelected(UserPreferences.getBool("viewer", "secTypeVncAuth", true));
  803. break;
  804. }
  805. }
  806. /* Process VeNCrypt subtypes */
  807. if (options.secVeNCrypt.isSelected()) {
  808. java.util.List<Integer> secTypesExt = new ArrayList<Integer>();
  809. secTypesExt = Security.GetEnabledExtSecTypes();
  810. for (Iterator<Integer> iext = secTypesExt.iterator(); iext.hasNext();) {
  811. switch ((Integer)iext.next()) {
  812. case Security.secTypePlain:
  813. options.encNone.setSelected(UserPreferences.getBool("viewer", "encNone", true));
  814. options.secPlain.setSelected(UserPreferences.getBool("viewer", "secPlain", true));
  815. break;
  816. case Security.secTypeIdent:
  817. options.encNone.setSelected(UserPreferences.getBool("viewer", "encNone", true));
  818. options.secIdent.setSelected(UserPreferences.getBool("viewer", "secIdent", true));
  819. break;
  820. case Security.secTypeTLSNone:
  821. options.encTLS.setSelected(UserPreferences.getBool("viewer", "encTLS", true));
  822. options.secNone.setSelected(UserPreferences.getBool("viewer", "secNone", true));
  823. break;
  824. case Security.secTypeTLSVnc:
  825. options.encTLS.setSelected(UserPreferences.getBool("viewer", "encTLS", true));
  826. options.secVnc.setSelected(UserPreferences.getBool("viewer", "secVnc", true));
  827. break;
  828. case Security.secTypeTLSPlain:
  829. options.encTLS.setSelected(UserPreferences.getBool("viewer", "encTLS", true));
  830. options.secPlain.setSelected(UserPreferences.getBool("viewer", "secPlain", true));
  831. break;
  832. case Security.secTypeTLSIdent:
  833. options.encTLS.setSelected(UserPreferences.getBool("viewer", "encTLS", true));
  834. options.secIdent.setSelected(UserPreferences.getBool("viewer", "secIdent", true));
  835. break;
  836. case Security.secTypeX509None:
  837. options.encX509.setSelected(UserPreferences.getBool("viewer", "encX509", true));
  838. options.secNone.setSelected(UserPreferences.getBool("viewer", "secNone", true));
  839. break;
  840. case Security.secTypeX509Vnc:
  841. options.encX509.setSelected(UserPreferences.getBool("viewer", "encX509", true));
  842. options.secVnc.setSelected(UserPreferences.getBool("viewer", "secVnc", true));
  843. break;
  844. case Security.secTypeX509Plain:
  845. options.encX509.setSelected(UserPreferences.getBool("viewer", "encX509", true));
  846. options.secPlain.setSelected(UserPreferences.getBool("viewer", "secPlain", true));
  847. break;
  848. case Security.secTypeX509Ident:
  849. options.encX509.setSelected(UserPreferences.getBool("viewer", "encX509", true));
  850. options.secIdent.setSelected(UserPreferences.getBool("viewer", "secIdent", true));
  851. break;
  852. }
  853. }
  854. }
  855. options.encNone.setEnabled(options.secVeNCrypt.isSelected());
  856. options.encTLS.setEnabled(options.secVeNCrypt.isSelected());
  857. options.encX509.setEnabled(options.secVeNCrypt.isSelected());
  858. options.ca.setEnabled(options.secVeNCrypt.isSelected());
  859. options.crl.setEnabled(options.secVeNCrypt.isSelected());
  860. options.secIdent.setEnabled(options.secVeNCrypt.isSelected());
  861. options.secPlain.setEnabled(options.secVeNCrypt.isSelected());
  862. options.sendLocalUsername.setEnabled(options.secPlain.isSelected()||
  863. options.secIdent.isSelected());
  864. }
  865. options.fullScreen.setSelected(fullScreen);
  866. options.fullScreenAllMonitors.setSelected(viewer.fullScreenAllMonitors.getValue());
  867. options.useLocalCursor.setSelected(viewer.useLocalCursor.getValue());
  868. options.acceptBell.setSelected(viewer.acceptBell.getValue());
  869. String scaleString = viewer.scalingFactor.getValue();
  870. if (scaleString.equalsIgnoreCase("Auto")) {
  871. options.scalingFactor.setSelectedItem("Auto");
  872. } else if(scaleString.equalsIgnoreCase("FixedRatio")) {
  873. options.scalingFactor.setSelectedItem("Fixed Aspect Ratio");
  874. } else {
  875. digit = Integer.parseInt(scaleString);
  876. if (digit >= 1 && digit <= 1000) {
  877. options.scalingFactor.setSelectedItem(digit+"%");
  878. } else {
  879. digit = Integer.parseInt(viewer.scalingFactor.getDefaultStr());
  880. options.scalingFactor.setSelectedItem(digit+"%");
  881. }
  882. int scaleFactor =
  883. Integer.parseInt(scaleString.substring(0, scaleString.length()));
  884. if (desktop != null)
  885. desktop.setScaledSize();
  886. }
  887. if (viewer.desktopSize.getValue() != null &&
  888. viewer.desktopSize.getValue().split("x").length == 2) {
  889. options.desktopSize.setSelected(true);
  890. String desktopWidth = viewer.desktopSize.getValue().split("x")[0];
  891. options.desktopWidth.setText(desktopWidth);
  892. String desktopHeight = viewer.desktopSize.getValue().split("x")[1];
  893. options.desktopHeight.setText(desktopHeight);
  894. }
  895. }
  896. public void getOptions() {
  897. autoSelect = options.autoSelect.isSelected();
  898. if (fullColour != options.fullColour.isSelected()) {
  899. formatChange = true;
  900. forceNonincremental = true;
  901. }
  902. fullColour = options.fullColour.isSelected();
  903. if (!fullColour) {
  904. int newLowColourLevel = (options.veryLowColour.isSelected() ? 0 :
  905. options.lowColour.isSelected() ? 1 : 2);
  906. if (newLowColourLevel != lowColourLevel) {
  907. lowColourLevel = newLowColourLevel;
  908. formatChange = true;
  909. forceNonincremental = true;
  910. }
  911. }
  912. int newEncoding = (options.zrle.isSelected() ? Encodings.encodingZRLE :
  913. options.hextile.isSelected() ? Encodings.encodingHextile :
  914. options.tight.isSelected() ? Encodings.encodingTight :
  915. Encodings.encodingRaw);
  916. if (newEncoding != currentEncoding) {
  917. currentEncoding = newEncoding;
  918. encodingChange = true;
  919. }
  920. viewer.customCompressLevel.setParam(options.customCompressLevel.isSelected());
  921. if (cp.customCompressLevel != viewer.customCompressLevel.getValue()) {
  922. cp.customCompressLevel = viewer.customCompressLevel.getValue();
  923. encodingChange = true;
  924. }
  925. if (Integer.parseInt(options.compressLevel.getSelectedItem().toString()) >= 0 &&
  926. Integer.parseInt(options.compressLevel.getSelectedItem().toString()) <= 9) {
  927. viewer.compressLevel.setParam(options.compressLevel.getSelectedItem().toString());
  928. } else {
  929. viewer.compressLevel.setParam(viewer.compressLevel.getDefaultStr());
  930. }
  931. if (cp.compressLevel != viewer.compressLevel.getValue()) {
  932. cp.compressLevel = viewer.compressLevel.getValue();
  933. encodingChange = true;
  934. }
  935. viewer.noJpeg.setParam(!options.noJpeg.isSelected());
  936. if (cp.noJpeg != viewer.noJpeg.getValue()) {
  937. cp.noJpeg = viewer.noJpeg.getValue();
  938. encodingChange = true;
  939. }
  940. viewer.qualityLevel.setParam(options.qualityLevel.getSelectedItem().toString());
  941. if (cp.qualityLevel != viewer.qualityLevel.getValue()) {
  942. cp.qualityLevel = viewer.qualityLevel.getValue();
  943. encodingChange = true;
  944. }
  945. viewer.sendLocalUsername.setParam(options.sendLocalUsername.isSelected());
  946. viewer.viewOnly.setParam(options.viewOnly.isSelected());
  947. viewer.acceptClipboard.setParam(options.acceptClipboard.isSelected());
  948. viewer.sendClipboard.setParam(options.sendClipboard.isSelected());
  949. viewer.acceptBell.setParam(options.acceptBell.isSelected());
  950. String scaleString =
  951. options.scalingFactor.getSelectedItem().toString();
  952. String oldScaleFactor = viewer.scalingFactor.getValue();
  953. if (scaleString.equalsIgnoreCase("Fixed Aspect Ratio")) {
  954. scaleString = new String("FixedRatio");
  955. } else if (scaleString.equalsIgnoreCase("Auto")) {
  956. scaleString = new String("Auto");
  957. } else {
  958. scaleString=scaleString.substring(0, scaleString.length()-1);
  959. }
  960. if (!oldScaleFactor.equals(scaleString)) {
  961. viewer.scalingFactor.setParam(scaleString);
  962. if ((options.fullScreen.isSelected() == fullScreen) &&
  963. (desktop != null))
  964. recreateViewport();
  965. }
  966. clipboardDialog.setSendingEnabled(viewer.sendClipboard.getValue());
  967. viewer.menuKey.setParam(MenuKey.getMenuKeySymbols()[options.menuKey.getSelectedIndex()].name);
  968. F8Menu.f8.setText("Send "+KeyEvent.getKeyText(MenuKey.getMenuKeyCode()));
  969. setShared(options.shared.isSelected());
  970. viewer.useLocalCursor.setParam(options.useLocalCursor.isSelected());
  971. if (cp.supportsLocalCursor != viewer.useLocalCursor.getValue()) {
  972. cp.supportsLocalCursor = viewer.useLocalCursor.getValue();
  973. encodingChange = true;
  974. if (desktop != null)
  975. desktop.resetLocalCursor();
  976. }
  977. checkEncodings();
  978. if (state() != RFBSTATE_NORMAL) {
  979. /* Process security types which don't use encryption */
  980. if (options.encNone.isSelected()) {
  981. if (options.secNone.isSelected())
  982. Security.EnableSecType(Security.secTypeNone);
  983. if (options.secVnc.isSelected())
  984. Security.EnableSecType(Security.secTypeVncAuth);
  985. if (options.secPlain.isSelected())
  986. Security.EnableSecType(Security.secTypePlain);
  987. if (options.secIdent.isSelected())
  988. Security.EnableSecType(Security.secTypeIdent);
  989. } else {
  990. Security.DisableSecType(Security.secTypeNone);
  991. Security.DisableSecType(Security.secTypeVncAuth);
  992. Security.DisableSecType(Security.secTypePlain);
  993. Security.DisableSecType(Security.secTypeIdent);
  994. }
  995. /* Process security types which use TLS encryption */
  996. if (options.encTLS.isSelected()) {
  997. if (options.secNone.isSelected())
  998. Security.EnableSecType(Security.secTypeTLSNone);
  999. if (options.secVnc.isSelected())
  1000. Security.EnableSecType(Security.secTypeTLSVnc);
  1001. if (options.secPlain.isSelected())
  1002. Security.EnableSecType(Security.secTypeTLSPlain);
  1003. if (options.secIdent.isSelected())
  1004. Security.EnableSecType(Security.secTypeTLSIdent);
  1005. } else {
  1006. Security.DisableSecType(Security.secTypeTLSNone);
  1007. Security.DisableSecType(Security.secTypeTLSVnc);
  1008. Security.DisableSecType(Security.secTypeTLSPlain);
  1009. Security.DisableSecType(Security.secTypeTLSIdent);
  1010. }
  1011. /* Process security types which use X509 encryption */
  1012. if (options.encX509.isSelected()) {
  1013. if (options.secNone.isSelected())
  1014. Security.EnableSecType(Security.secTypeX509None);
  1015. if (options.secVnc.isSelected())
  1016. Security.EnableSecType(Security.secTypeX509Vnc);
  1017. if (options.secPlain.isSelected())
  1018. Security.EnableSecType(Security.secTypeX509Plain);
  1019. if (options.secIdent.isSelected())
  1020. Security.EnableSecType(Security.secTypeX509Ident);
  1021. } else {
  1022. Security.DisableSecType(Security.secTypeX509None);
  1023. Security.DisableSecType(Security.secTypeX509Vnc);
  1024. Security.DisableSecType(Security.secTypeX509Plain);
  1025. Security.DisableSecType(Security.secTypeX509Ident);
  1026. }
  1027. /* Process *None security types */
  1028. if (options.secNone.isSelected()) {
  1029. if (options.encNone.isSelected())
  1030. Security.EnableSecType(Security.secTypeNone);
  1031. if (options.encTLS.isSelected())
  1032. Security.EnableSecType(Security.secTypeTLSNone);
  1033. if (options.encX509.isSelected())
  1034. Security.EnableSecType(Security.secTypeX509None);
  1035. } else {
  1036. Security.DisableSecType(Security.secTypeNone);
  1037. Security.DisableSecType(Security.secTypeTLSNone);
  1038. Security.DisableSecType(Security.secTypeX509None);
  1039. }
  1040. /* Process *Vnc security types */
  1041. if (options.secVnc.isSelected()) {
  1042. if (options.encNone.isSelected())
  1043. Security.EnableSecType(Security.secTypeVncAuth);
  1044. if (options.encTLS.isSelected())
  1045. Security.EnableSecType(Security.secTypeTLSVnc);
  1046. if (options.encX509.isSelected())
  1047. Security.EnableSecType(Security.secTypeX509Vnc);
  1048. } else {
  1049. Security.DisableSecType(Security.secTypeVncAuth);
  1050. Security.DisableSecType(Security.secTypeTLSVnc);
  1051. Security.DisableSecType(Security.secTypeX509Vnc);
  1052. }
  1053. /* Process *Plain security types */
  1054. if (options.secPlain.isSelected()) {
  1055. if (options.encNone.isSelected())
  1056. Security.EnableSecType(Security.secTypePlain);
  1057. if (options.encTLS.isSelected())
  1058. Security.EnableSecType(Security.secTypeTLSPlain);
  1059. if (options.encX509.isSelected())
  1060. Security.EnableSecType(Security.secTypeX509Plain);
  1061. } else {
  1062. Security.DisableSecType(Security.secTypePlain);
  1063. Security.DisableSecType(Security.secTypeTLSPlain);
  1064. Security.DisableSecType(Security.secTypeX509Plain);
  1065. }
  1066. /* Process *Ident security types */
  1067. if (options.secIdent.isSelected()) {
  1068. if (options.encNone.isSelected())
  1069. Security.EnableSecType(Security.secTypeIdent);
  1070. if (options.encTLS.isSelected())
  1071. Security.EnableSecType(Security.secTypeTLSIdent);
  1072. if (options.encX509.isSelected())
  1073. Security.EnableSecType(Security.secTypeX509Ident);
  1074. } else {
  1075. Security.DisableSecType(Security.secTypeIdent);
  1076. Security.DisableSecType(Security.secTypeTLSIdent);
  1077. Security.DisableSecType(Security.secTypeX509Ident);
  1078. }
  1079. }
  1080. String desktopSize = (options.desktopSize.isSelected()) ?
  1081. options.desktopWidth.getText() + "x" + options.desktopHeight.getText() : "";
  1082. viewer.desktopSize.setParam(desktopSize);
  1083. if (options.fullScreen.isSelected() ^ fullScreen) {
  1084. viewer.fullScreenAllMonitors.setParam(options.fullScreenAllMonitors.isSelected());
  1085. toggleFullScreen();
  1086. } else {
  1087. if (viewer.fullScreenAllMonitors.getValue() !=
  1088. options.fullScreenAllMonitors.isSelected()) {
  1089. viewer.fullScreenAllMonitors.setParam(options.fullScreenAllMonitors.isSelected());
  1090. if (desktop != null)
  1091. recreateViewport();
  1092. } else {
  1093. viewer.fullScreenAllMonitors.setParam(options.fullScreenAllMonitors.isSelected());
  1094. }
  1095. }
  1096. }
  1097. public void toggleFullScreen() {
  1098. if (viewer.embed.getValue())
  1099. return;
  1100. fullScreen = !fullScreen;
  1101. menu.fullScreen.setSelected(fullScreen);
  1102. if (viewport != null) {
  1103. if (!viewport.lionFSSupported()) {
  1104. recreateViewport();
  1105. } else {
  1106. viewport.toggleLionFS();
  1107. }
  1108. }
  1109. }
  1110. // writeClientCutText() is called from the clipboard dialog
  1111. public void writeClientCutText(String str, int len) {
  1112. if (state() != RFBSTATE_NORMAL || shuttingDown)
  1113. return;
  1114. writer().writeClientCutText(str, len);
  1115. }
  1116. public void writeKeyEvent(int keysym, boolean down) {
  1117. if (state() != RFBSTATE_NORMAL || shuttingDown)
  1118. return;
  1119. writer().writeKeyEvent(keysym, down);
  1120. }
  1121. public void writeKeyEvent(KeyEvent ev) {
  1122. if (viewer.viewOnly.getValue() || shuttingDown)
  1123. return;
  1124. boolean down = (ev.getID() == KeyEvent.KEY_PRESSED);
  1125. int keySym, keyCode = ev.getKeyCode();
  1126. // If neither the keyCode or keyChar are defined, then there's
  1127. // really nothing that we can do with this. The fn key on OS-X
  1128. // fires events like this when pressed but does not fire a
  1129. // corresponding release event.
  1130. if (keyCode == 0 && ev.getKeyChar() == KeyEvent.CHAR_UNDEFINED)
  1131. return;
  1132. if (!down) {
  1133. Integer iter = downKeySym.get(keyCode);
  1134. if (iter == null) {
  1135. // Note that dead keys will raise this sort of error falsely
  1136. // See https://bugs.openjdk.java.net/browse/JDK-6534883
  1137. vlog.error("Unexpected key release of keyCode "+keyCode);
  1138. String fmt = ev.paramString().replaceAll("%","%%");
  1139. vlog.error(String.format(fmt.replaceAll(",","%n ")));
  1140. return;
  1141. }
  1142. vlog.debug(String.format("Key released: 0x%04x => 0x%04x",
  1143. keyCode, iter));
  1144. writeKeyEvent(iter, false);
  1145. downKeySym.remove(keyCode);
  1146. return;
  1147. }
  1148. keySym = Keysyms.translateKeyEvent(ev);
  1149. if (keySym == Keysyms.VoidSymbol)
  1150. return;
  1151. boolean need_cheat = true;
  1152. if (VncViewer.os.startsWith("windows")) {
  1153. // Windows doesn't have a proper AltGr, but handles it using fake
  1154. // Ctrl+Alt. Unfortunately X11 doesn't generally like the combination
  1155. // Ctrl+Alt+AltGr, which we usually end up with when Xvnc tries to
  1156. // get everything in the correct state. Cheat and temporarily release
  1157. // Ctrl and Alt whenever we get a key with a symbol.
  1158. if (KeyEvent.getKeyText(keyCode).isEmpty())
  1159. need_cheat = false;
  1160. else if (!downKeySym.containsValue(Keysyms.Control_L) &&
  1161. !downKeySym.containsValue(Keysyms.Control_R))
  1162. need_cheat = false;
  1163. else if (!downKeySym.containsValue(Keysyms.Alt_L) &&
  1164. !downKeySym.containsValue(Keysyms.Alt_R))
  1165. need_cheat = false;
  1166. if (need_cheat) {
  1167. vlog.info("Faking release of AltGr (Ctrl+Alt)");
  1168. if (downKeySym.containsValue(Keysyms.Control_L))
  1169. writeKeyEvent(Keysyms.Control_L, false);
  1170. if (downKeySym.containsValue(Keysyms.Control_R))
  1171. writeKeyEvent(Keysyms.Control_R, false);
  1172. if (downKeySym.containsValue(Keysyms.Alt_L))
  1173. writeKeyEvent(Keysyms.Alt_L, false);
  1174. if (downKeySym.containsValue(Keysyms.Alt_R))
  1175. writeKeyEvent(Keysyms.Alt_R, false);
  1176. }
  1177. }
  1178. vlog.debug(String.format("Key pressed: 0x%04x '%s' => 0x%04x",
  1179. keyCode, Character.toString(ev.getKeyChar()), keySym));
  1180. downKeySym.put(keyCode, keySym);
  1181. writeKeyEvent(keySym, down);
  1182. if (VncViewer.os.startsWith("windows")) {
  1183. if (need_cheat) {
  1184. vlog.debug("Restoring AltGr state");
  1185. if (downKeySym.containsValue(Keysyms.Control_L))
  1186. writeKeyEvent(Keysyms.Control_L, true);
  1187. if (downKeySym.containsValue(Keysyms.Control_R))
  1188. writeKeyEvent(Keysyms.Control_R, true);
  1189. if (downKeySym.containsValue(Keysyms.Alt_L))
  1190. writeKeyEvent(Keysyms.Alt_L, true);
  1191. if (downKeySym.containsValue(Keysyms.Alt_R))
  1192. writeKeyEvent(Keysyms.Alt_R, true);
  1193. }
  1194. }
  1195. }
  1196. public void writePointerEvent(MouseEvent ev) {
  1197. if (state() != RFBSTATE_NORMAL || shuttingDown)
  1198. return;
  1199. switch (ev.getID()) {
  1200. case MouseEvent.MOUSE_PRESSED:
  1201. buttonMask = 1;
  1202. if ((ev.getModifiers() & KeyEvent.ALT_MASK) != 0) buttonMask = 2;
  1203. if ((ev.getModifiers() & KeyEvent.META_MASK) != 0) buttonMask = 4;
  1204. break;
  1205. case MouseEvent.MOUSE_RELEASED:
  1206. buttonMask = 0;
  1207. break;
  1208. }
  1209. if (cp.width != desktop.scaledWidth ||
  1210. cp.height != desktop.scaledHeight) {
  1211. int sx = (desktop.scaleWidthRatio == 1.00) ?
  1212. ev.getX() : (int)Math.floor(ev.getX() / desktop.scaleWidthRatio);
  1213. int sy = (desktop.scaleHeightRatio == 1.00) ?
  1214. ev.getY() : (int)Math.floor(ev.getY() / desktop.scaleHeightRatio);
  1215. ev.translatePoint(sx - ev.getX(), sy - ev.getY());
  1216. }
  1217. writer().writePointerEvent(new Point(ev.getX(), ev.getY()), buttonMask);
  1218. }
  1219. public void writeWheelEvent(MouseWheelEvent ev) {
  1220. if (state() != RFBSTATE_NORMAL || shuttingDown)
  1221. return;
  1222. int x, y;
  1223. int clicks = ev.getWheelRotation();
  1224. if (clicks < 0) {
  1225. buttonMask = 8;
  1226. } else {
  1227. buttonMask = 16;
  1228. }
  1229. for (int i = 0; i < Math.abs(clicks); i++) {
  1230. x = ev.getX();
  1231. y = ev.getY();
  1232. writer().writePointerEvent(new Point(x, y), buttonMask);
  1233. buttonMask = 0;
  1234. writer().writePointerEvent(new Point(x, y), buttonMask);
  1235. }
  1236. }
  1237. synchronized void releaseDownKeys() {
  1238. for (Map.Entry<Integer, Integer> entry : downKeySym.entrySet())
  1239. writeKeyEvent(entry.getValue(), false);
  1240. downKeySym.clear();
  1241. }
  1242. // this is a special ActionListener passed in by the
  1243. // Java Plug-in software to control applet's close behavior
  1244. public void setCloseListener(ActionListener cl) {
  1245. closeListener = cl;
  1246. }
  1247. public void actionPerformed(ActionEvent e) {}
  1248. ////////////////////////////////////////////////////////////////////
  1249. // The following methods are called from both RFB and GUI threads
  1250. // checkEncodings() sends a setEncodings message if one is needed.
  1251. private void checkEncodings() {
  1252. if (encodingChange && (writer() != null)) {
  1253. vlog.info("Requesting " + Encodings.encodingName(currentEncoding) +
  1254. " encoding");
  1255. writer().writeSetEncodings(currentEncoding, true);
  1256. encodingChange = false;
  1257. }
  1258. }
  1259. // the following never change so need no synchronization:
  1260. // viewer object is only ever accessed by the GUI thread so needs no
  1261. // synchronization (except for one test in DesktopWindow - see comment
  1262. // there).
  1263. VncViewer viewer;
  1264. // access to desktop by different threads is specified in DesktopWindow
  1265. // the following need no synchronization:
  1266. public static UserPasswdGetter upg;
  1267. public UserMsgBox msg;
  1268. // shuttingDown is set by the GUI thread and only ever tested by the RFB
  1269. // thread after the window has been destroyed.
  1270. boolean shuttingDown = false;
  1271. // reading and writing int and boolean is atomic in java, so no
  1272. // synchronization of the following flags is needed:
  1273. int lowColourLevel;
  1274. // All menu, options, about and info stuff is done in the GUI thread (apart
  1275. // from when constructed).
  1276. F8Menu menu;
  1277. OptionsDialog options;
  1278. // clipboard sync issues?
  1279. ClipboardDialog clipboardDialog;
  1280. // the following are only ever accessed by the GUI thread:
  1281. int buttonMask;
  1282. private String serverHost;
  1283. private int serverPort;
  1284. private Socket sock;
  1285. protected DesktopWindow desktop;
  1286. // FIXME: should be private
  1287. public PixelFormat serverPF;
  1288. private PixelFormat fullColourPF;
  1289. private boolean pendingPFChange;
  1290. private PixelFormat pendingPF;
  1291. private int currentEncoding, lastServerEncoding;
  1292. private boolean formatChange;
  1293. private boolean encodingChange;
  1294. private boolean firstUpdate;
  1295. private boolean pendingUpdate;
  1296. private boolean continuousUpdates;
  1297. private boolean forceNonincremental;
  1298. private boolean supportsSyncFence;
  1299. public int menuKeyCode;
  1300. Viewport viewport;
  1301. private boolean fullColour;
  1302. private boolean autoSelect;
  1303. boolean fullScreen;
  1304. private HashMap<Integer, Integer> downKeySym;
  1305. public ActionListener closeListener = null;
  1306. static LogWriter vlog = new LogWriter("CConn");
  1307. }