Repository navigation
Expand file tree
/
Copy pathClaudeRdpCommunicator.java
More file actions
689 lines (599 loc) · 28.2 KB
/
Copy pathClaudeRdpCommunicator.java
File metadata and controls
689 lines (599 loc) · 28.2 KB
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
package com.undatech.opaque;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.freerdp.freerdpcore.application.GlobalApp;
import com.freerdp.freerdpcore.application.SessionState;
import com.freerdp.freerdpcore.domain.BookmarkBase;
import com.freerdp.freerdpcore.domain.ManualBookmark;
import com.freerdp.freerdpcore.services.LibFreeRDP;
import com.undatech.opaque.input.RdpKeyboardMapper;
import com.undatech.opaque.input.RemoteKeyboard;
import com.undatech.opaque.input.RemotePointer;
import com.undatech.opaque.util.GeneralUtils;
import org.apache.commons.validator.routines.InetAddressValidator;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RdpCommunicator extends RfbConnectable implements RdpKeyboardMapper.KeyProcessingListener,
LibFreeRDP.UIEventListener, LibFreeRDP.EventListener {
static final String TAG = "RdpCommunicator";
// private final static int VK_CONTROL = 0x11;
private final static int VK_LCONTROL = 0xA2;
private final static int VK_RCONTROL = 0xA3;
private final static int VK_LMENU = 0xA4;
private final static int VK_RMENU = 0xA5;
private final static int VK_LSHIFT = 0xA0;
private final static int VK_RSHIFT = 0xA1;
private final static int VK_LWIN = 0x5B;
private final static int VK_RWIN = 0x5C;
private final static int VK_EXT_KEY = 0x00000100;
private final RdpCommunicator myself;
private final Viewable viewable;
private SessionState session;
private final BookmarkBase bookmark;
// Keeps track of libFreeRDP instance
private final GlobalApp freeRdpApp;
private final Context context;
private boolean isInNormalProtocol = false;
// This variable indicates whether or not the user has accepted an untrusted
// security certificate. Used to control progress while the dialog asking the user
// to confirm the authenticity of a certificate is displayed.
private boolean certificateAccepted = false;
private boolean reattemptWithoutCredentials = true;
private boolean authenticationAttempted = false;
private boolean gatewayAuthenticationAttempted = false;
private boolean disconnectRequested = false;
private final String username, password, domain;
private final Connection connection;
/**
* Applies Floyd-Steinberg 1-bit dithering to the rectangle defined by
* (x, y, width, height) inside bitmap.
*
* Each pixel's perceived luminance (BT.601) is quantised to black or white.
* The quantisation error is distributed to the four neighbours using standard FS weights:
*
* * 7/16
* 3/16 5/16 1/16
*
* The result is written back into the same mutable bitmap in-place.
*
* @param bitmap mutable ARGB_8888 bitmap that holds the framebuffer
* @param x left edge of the rectangle (pixels, inclusive)
* @param y top edge of the rectangle (pixels, inclusive)
* @param width width of the rectangle in pixels
* @param height height of the rectangle in pixels
*/
private static void applyFloydSteinbergDithering(
Bitmap bitmap, int x, int y, int width, int height) {
if (!bitmap.isMutable()) {
Log.w(TAG, "applyFloydSteinbergDithering: bitmap is not mutable – skipping.");
return;
}
// Pull the rectangle's pixels into a flat array for O(1) random access.
final int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, x, y, width, height);
// Two-row error accumulation buffers, alternated each row.
// Each row has (width + 2) slots; column `col` maps to slot `col + 1` so that
// left-edge (col-1) and right-edge (col+1) accesses need no bounds checks.
final float[][] err = new float[2][width + 2];
for (int row = 0; row < height; row++) {
final int cur = row & 1; // index of the current-row error buffer
final int nxt = cur ^ 1; // index of the next-row error buffer
// Clear the next-row buffer before we start diffusing into it.
java.util.Arrays.fill(err[nxt], 0f);
for (int col = 0; col < width; col++) {
final int pixel = pixels[row * width + col];
// BT.601 perceived luminance in [0, 255].
final float lum = 0.299f * Color.red(pixel)
+ 0.587f * Color.green(pixel)
+ 0.114f * Color.blue(pixel);
// Add accumulated neighbour error (slot col+1 due to 1-cell left padding).
final float adjusted = lum + err[cur][col + 1];
// Quantise to black or white.
final float quantised = (adjusted >= 128f) ? 255f : 0f;
pixels[row * width + col] = (quantised == 255f) ? Color.WHITE : Color.BLACK;
// Distribute quantisation error with FS weights.
final float error = adjusted - quantised;
if (col + 1 < width) err[cur][col + 2] += error * (7f / 16f); // right
if (row + 1 < height && col > 0) err[nxt][col] += error * (3f / 16f); // bottom-left
if (row + 1 < height) err[nxt][col + 1] += error * (5f / 16f); // bottom
if (row + 1 < height && col + 1 < width) err[nxt][col + 2] += error * (1f / 16f); // bottom-right
}
// Reset the current-row buffer so it is clean when it rotates to next-row.
java.util.Arrays.fill(err[cur], 0f);
}
// Write the dithered pixels back into the bitmap.
bitmap.setPixels(pixels, 0, width, x, y, width, height);
}
ExecutorService inputExecutor = Executors.newSingleThreadExecutor(
r -> {
Thread thread = new Thread(r);
thread.setName("SendRdpInputThread");
thread.setPriority(Thread.MAX_PRIORITY);
return thread;
}
);
public RdpCommunicator(Connection connection,
Context context, Handler handler, Viewable viewable,
String rdpFileName, String username, String domain, String password,
boolean debugLogging, boolean isRemoteToLocalClipboardIntegrationEnabled
) {
super(debugLogging, handler, isRemoteToLocalClipboardIntegrationEnabled);
this.connection = connection;
// This is necessary because it initializes a synchronizedMap referenced later.
this.freeRdpApp = new GlobalApp();
patchFreeRdpCore();
// Create a manual bookmark and populate it from settings.
this.bookmark = new ManualBookmark();
this.context = context;
this.viewable = viewable;
this.myself = this;
this.username = username;
this.domain = domain;
this.password = password;
modifierMap.put(RemoteKeyboard.CTRL_MASK, VK_LCONTROL);
modifierMap.put(RemoteKeyboard.RCTRL_MASK, (VK_RCONTROL | VK_EXT_KEY));
modifierMap.put(RemoteKeyboard.ALT_MASK, VK_LMENU);
modifierMap.put(RemoteKeyboard.RALT_MASK, (VK_RMENU | VK_EXT_KEY));
modifierMap.put(RemoteKeyboard.SUPER_MASK, (VK_LWIN | VK_EXT_KEY));
modifierMap.put(RemoteKeyboard.RSUPER_MASK, (VK_RWIN | VK_EXT_KEY));
modifierMap.put(RemoteKeyboard.SHIFT_MASK, VK_LSHIFT);
modifierMap.put(RemoteKeyboard.RSHIFT_MASK, VK_RSHIFT);
initSession(rdpFileName, username, domain, password);
}
private void patchFreeRdpCore() {
Class<? extends GlobalApp> cls = this.freeRdpApp.getClass();
try {
Log.i(TAG, "Initializing sessionMap in GlobalApp");
Field sessionMap = cls.getDeclaredField("sessionMap");
sessionMap.setAccessible(true);
sessionMap.set(this.freeRdpApp, Collections.synchronizedMap(new HashMap<Long, SessionState>()));
} catch (NoSuchFieldException e) {
Log.e(TAG, "There is no longer a sessionMap field in GlobalApp");
} catch (IllegalAccessException e) {
Log.e(TAG, "The field sessionMap in GlobalApp was not accessible despite our attempts");
}
}
@Override
public void setIsInNormalProtocol(boolean state) {
Log.d(TAG, "setIsInNormalProtocol: " + state);
isInNormalProtocol = state;
}
@Override
public int framebufferWidth() {
return session.getBookmark().getActiveScreenSettings().getWidth();
}
@Override
public int framebufferHeight() {
return session.getBookmark().getActiveScreenSettings().getHeight();
}
@Override
public String desktopName() {
return ((ManualBookmark) session.getBookmark()).getHostname();
}
@Override
public void requestUpdate(boolean incremental) {
// NOT USED for RDP.
}
@Override
public void writeClientCutText(String text) {
LibFreeRDP.sendClipboardData(session.getInstance(), text);
}
@Override
public boolean isInNormalProtocol() {
return isInNormalProtocol;
}
@Override
public String getEncoding() {
return "RDP";
}
@Override
public synchronized void writePointerEvent(int x, int y, int metaState, int pointerMask, boolean rel) {
this.metaState = metaState;
boolean down = (pointerMask & RemotePointer.POINTER_DOWN_MASK) != 0;
if (down) {
sendModifierKeys(true);
}
sendRemoteMouseEventOnNewThread(x, y, pointerMask);
if (!down) {
sendModifierKeys(false);
}
}
private void sendRemoteMouseEventOnNewThread(int x, int y, int pointerMask) {
runMethodOnInputThread(() -> sendRemoteMouseEvent(x, y, pointerMask));
}
private synchronized void sendRemoteMouseEvent(int x, int y, int pointerMask) {
sleepBetweenInputEvents(3);
LibFreeRDP.sendCursorEvent(session.getInstance(), x, y, pointerMask);
}
@Override
public synchronized void writeKeyEvent(int key, int metaState, boolean down) {
// Not used for actually sending keyboard events, but rather to record the current metastate.
// The key event is sent to the KeyboardMapper from RemoteRdpKeyboard, and
// when processed through the keyboard mapper, it ends up in one of the KeyProcessingListener
// methods defined here.
GeneralUtils.debugLog(this.debugLogging, TAG, "writeKeyEvent: setting metaState to: " + metaState);
this.metaState = metaState;
}
@Override
public void writeSetPixelFormat(int bitsPerPixel, int depth,
boolean bigEndian, boolean trueColour, int redMax, int greenMax,
int blueMax, int redShift, int greenShift, int blueShift,
boolean fGreyScale) {
// NOT USED for RDP.
}
@Override
public void writeFramebufferUpdateRequest(int x, int y, int w, int h,
boolean b) {
// NOT USED for RDP.
}
@Override
public void close() {
setIsInNormalProtocol(false);
disconnectRequested = true;
long instance = session.getInstance();
DisconnectThread d = new DisconnectThread(instance);
d.start();
}
@Override
public boolean isCertificateAccepted() {
return certificateAccepted;
}
@Override
public void setCertificateAccepted(boolean certificateAccepted) {
this.certificateAccepted = certificateAccepted;
}
private void sendModifierKeys(boolean down) {
for (int modifierMask : modifierMap.keySet()) {
if (remoteKeyboardState.shouldSendModifier(metaState, modifierMask, down)) {
Integer modifier = modifierMap.get(modifierMask);
if (modifier != null) {
GeneralUtils.debugLog(this.debugLogging, TAG, "sendModifierKeys, modifierMask:" +
modifierMask + ", sending: " + modifier + ", down: " + down);
sendKeyEventOnNewThread(modifier, down);
remoteKeyboardState.updateRemoteMetaState(modifierMask, down);
}
}
}
}
// ****************************************************************************
// KeyboardMapper.KeyProcessingListener implementation
@Override
public void processVirtualKey(int virtualKeyCode, boolean down) {
GeneralUtils.debugLog(this.debugLogging, TAG, "processVirtualKey: " +
"Processing VK key: " + virtualKeyCode + ". Is it down: " + down);
if (down) {
sendModifierKeys(true);
}
sendKeyEventOnNewThread(virtualKeyCode, down);
if (!down) {
sendModifierKeys(false);
}
}
private void sendKeyEventOnNewThread(int virtualKeyCode, boolean down) {
runMethodOnInputThread(() -> sendKeyEvent(virtualKeyCode, down));
}
private synchronized void sendKeyEvent(int virtualKeyCode, boolean down) {
sleepBetweenInputEvents(5);
LibFreeRDP.sendKeyEvent(session.getInstance(), virtualKeyCode, down);
}
@Override
public void processUnicodeKey(int unicodeKey, boolean down, boolean suppressMetaState) {
GeneralUtils.debugLog(this.debugLogging, TAG, "processUnicodeKey: " +
"Processing unicode key: " + unicodeKey + ", down: " + down +
", metaState: " + metaState + ", suppressMetaState: " + suppressMetaState);
if (down && !suppressMetaState) {
sendModifierKeys(true);
}
sendUnicodeKeyOnNewThread(unicodeKey, down);
if (!down && !suppressMetaState) {
sendModifierKeys(false);
}
}
private void sendUnicodeKeyOnNewThread(int unicodeKey, boolean down) {
runMethodOnInputThread(() -> sendUnicodeKey(unicodeKey, down));
}
private void runMethodOnInputThread(Runnable runnable) {
inputExecutor.submit(runnable);
}
private synchronized void sendUnicodeKey(int unicodeKey, boolean down) {
sleepBetweenInputEvents(5);
LibFreeRDP.sendUnicodeKeyEvent(session.getInstance(), unicodeKey, down);
}
private static void sleepBetweenInputEvents(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ignored) {
}
}
@Override
public void switchKeyboard(int keyboardType) {
// This is functionality specific to aFreeRDP.
}
@Override
public void modifiersChanged() {
// This is functionality specific to aFreeRDP.
}
@Override
public void requestResolution(int x, int y) {
// This functionality is not yet available for RDP
}
private void initSession(String rdpFileName, String username, String domain, String password) {
bookmark.setRdpFileName(rdpFileName);
bookmark.setUsername(username);
bookmark.setDomain(domain);
bookmark.setPassword(password);
session = GlobalApp.createSession(bookmark, context);
session.setUIEventListener(this);
LibFreeRDP.setEventListener(this);
}
public void setConnectionParameters(
String address, int rdpPort,
boolean gatewayEnabled, String gatewayHostname, int gatewayPort,
String gatewayUsername, String gatewayDomain, String gatewayPassword,
String nickname, int remoteWidth,
int remoteHeight, boolean wallpaper, boolean fontSmoothing,
boolean desktopComposition, boolean fullWindowDrag,
boolean menuAnimations, boolean theming, boolean redirectSdCard,
boolean consoleMode, int redirectSound, boolean enableRecording,
boolean enableRemoteFx, boolean enableGfx, boolean enableGfxH264,
int colors, int desktopScalePercentage, boolean debugLog
) {
// Set a writable data directory
//LibFreeRDP.setDataDirectory(session.getInstance(), getContext().getFilesDir().toString());
// Get the address and port (based on whether an SSH tunnel is being established or not).
bookmark.<ManualBookmark>get().setLabel(nickname);
bookmark.<ManualBookmark>get().setHostname(addBracketsToIpv6Address(address));
bookmark.<ManualBookmark>get().setPort(rdpPort);
bookmark.<ManualBookmark>get().setEnableGatewaySettings(gatewayEnabled);
ManualBookmark.GatewaySettings gatewaySettings = bookmark.<ManualBookmark>get().getGatewaySettings();
gatewaySettings.setUsername(gatewayUsername);
gatewaySettings.setDomain(gatewayDomain);
gatewaySettings.setPassword(gatewayPassword);
gatewaySettings.setHostname(gatewayHostname);
gatewaySettings.setPort(gatewayPort);
BookmarkBase.DebugSettings debugSettings = bookmark.getDebugSettings();
if (debugLog) {
debugSettings.setDebugLevel("DEBUG");
} else {
debugSettings.setDebugLevel("INFO");
}
//debugSettings.setAsyncUpdate(false);
//debugSettings.setAsyncInput(false);
//debugSettings.setAsyncChannel(false);
// Set screen settings to native res if instructed to, or if height or width are too small.
BookmarkBase.ScreenSettings screenSettings = bookmark.getActiveScreenSettings();
screenSettings.setDesktopScalePercentage(desktopScalePercentage);
updateScreenSettings(remoteWidth, remoteHeight, colors);
// Set performance flags.
BookmarkBase.PerformanceFlags performanceFlags = bookmark.getPerformanceFlags();
performanceFlags.setRemoteFX(enableRemoteFx);
performanceFlags.setWallpaper(wallpaper);
performanceFlags.setFontSmoothing(fontSmoothing);
performanceFlags.setDesktopComposition(desktopComposition);
performanceFlags.setFullWindowDrag(fullWindowDrag);
performanceFlags.setMenuAnimations(menuAnimations);
performanceFlags.setTheming(theming);
performanceFlags.setGfx(enableGfx);
performanceFlags.setH264(enableGfxH264);
performanceFlags.setGlyphCache(connection.getEnableGlyphCache());
BookmarkBase.AdvancedSettings advancedSettings = bookmark.getAdvancedSettings();
advancedSettings.setRedirectSDCard(redirectSdCard);
advancedSettings.setConsoleMode(consoleMode);
advancedSettings.setRedirectSound(redirectSound);
advancedSettings.setRedirectMicrophone(enableRecording);
advancedSettings.setSecurity(connection.getRdpSecurity());
}
/**
* Adds brackets around a valid IPv6 address that does not already start with [.
*
* @param address the address to potentially ad brackets to
* @return the address with brackets added if necessary
*/
private String addBracketsToIpv6Address(String address) {
InetAddressValidator validator = InetAddressValidator.getInstance();
if (validator.isValidInet6Address(address) && !address.startsWith("[")) {
address = "[" + address + "]";
}
return address;
}
public void connect() {
session.connect(context);
}
@Override
public void OnPreConnect(long instance) {
Log.v(TAG, "OnPreConnect");
}
//////////////////////////////////////////////////////////////////////////////////
// Implementation of LibFreeRDP.EventListener. Through the functions implemented
// below, FreeRDP communicates connection state information.
//////////////////////////////////////////////////////////////////////////////////
@Override
public void OnConnectionSuccess(long instance) {
Log.v(TAG, "OnConnectionSuccess");
reattemptWithoutCredentials = false;
authenticationAttempted = false;
myself.setIsInNormalProtocol(true);
}
@Override
public void OnConnectionFailure(long instance) {
Log.v(TAG, "OnConnectionFailure");
myself.setIsInNormalProtocol(false);
}
@Override
public void OnDisconnecting(long instance) {
Log.v(TAG, "OnDisconnecting, reattemptWithoutCredentials: " + reattemptWithoutCredentials +
", authenticationAttempted: " + authenticationAttempted +
", disconnectRequested: " + disconnectRequested +
", isInNormalProtocol: " + myself.isInNormalProtocol());
if (reattemptWithoutCredentials && !myself.isInNormalProtocol()) {
reattemptWithoutCredentials = false;
// It could be bad credentials that caused the disconnection, so trying to connect
// once again with no credentials before reporting the type of failure.
initSession(null, "", "", "");
connect();
} else if (authenticationAttempted && !myself.isInNormalProtocol()) {
Log.v(TAG, "Sending message: GET_RDP_CREDENTIALS");
handler.sendEmptyMessage(RemoteClientLibConstants.GET_RDP_CREDENTIALS);
} else if (gatewayAuthenticationAttempted && !myself.isInNormalProtocol()) {
Log.v(TAG, "Sending message: GET_RDP_GATEWAY_CREDENTIALS");
handler.sendEmptyMessage(RemoteClientLibConstants.GET_RDP_GATEWAY_CREDENTIALS);
} else if (!disconnectRequested && !myself.isInNormalProtocol()) {
Log.v(TAG, "Sending message: RDP_UNABLE_TO_CONNECT");
handler.sendEmptyMessage(RemoteClientLibConstants.RDP_UNABLE_TO_CONNECT);
} else if (!disconnectRequested) {
myself.setIsInNormalProtocol(false);
Log.v(TAG, "Sending message: RDP_CONNECT_FAILURE");
handler.sendEmptyMessage(RemoteClientLibConstants.RDP_CONNECT_FAILURE);
}
}
@Override
public void OnDisconnected(long instance) {
Log.v(TAG, "OnDisconnected");
if (!myself.isInNormalProtocol()) {
Log.v(TAG, "Sending message: RDP_UNABLE_TO_CONNECT");
handler.sendEmptyMessage(RemoteClientLibConstants.RDP_UNABLE_TO_CONNECT);
} else {
Log.v(TAG, "Sending message: RDP_CONNECT_FAILURE");
handler.sendEmptyMessage(RemoteClientLibConstants.RDP_CONNECT_FAILURE);
}
}
@Override
public void OnSettingsChanged(int width, int height, int bpp) {
Log.d(TAG, "OnSettingsChanged called, wxh: " + width + "x" + height);
handler.sendEmptyMessage(RemoteClientLibConstants.GRAPHICS_SETTINGS_RECEIVED);
BookmarkBase.ScreenSettings settings = session.getBookmark().getActiveScreenSettings();
if (settings.getWidth() != width || settings.getHeight() != height) {
Log.i(TAG, "OnSettingsChanged width and height do not match saved values, saving and reconnecting");
saveConnectionSettings(width, height, bpp);
handler.sendEmptyMessage(RemoteClientLibConstants.REINIT_SESSION);
} else {
viewable.reallocateDrawable(width, height);
}
}
private void saveConnectionSettings(int width, int height, int bpp) {
connection.setRdpResType(RemoteClientLibConstants.RDP_GEOM_SELECT_CUSTOM);
connection.setRdpWidth(width);
connection.setRdpHeight(height);
connection.setRdpColor(bpp);
connection.save(context);
updateScreenSettings(width, height, bpp);
}
private void updateScreenSettings(int width, int height, int bpp) {
BookmarkBase.ScreenSettings settings = session.getBookmark().getActiveScreenSettings();
settings.setWidth(width);
settings.setHeight(height);
settings.setColors(bpp);
settings.setDesktopScalePercentage(settings.getDesktopScalePercentage());
}
//////////////////////////////////////////////////////////////////////////////////
// Implementation of LibFreeRDP.UIEventListener. Through the functions implemented
// below, libspice and FreeRDP communicate remote desktop size and updates.
//////////////////////////////////////////////////////////////////////////////////
@Override
public boolean OnAuthenticate(StringBuilder username, StringBuilder domain, StringBuilder password) {
Log.d(TAG, "OnAuthenticate called.");
authenticationAttempted = true;
setCredentialsStringBuildersToValues(
username, domain, password, this.username, this.domain, this.password
);
return true;
}
private void setCredentialsStringBuildersToValues(
StringBuilder username, StringBuilder domain, StringBuilder password,
String fromUsername, String fromDomain, String fromPassword) {
username.setLength(0);
domain.setLength(0);
password.setLength(0);
username.append(fromUsername);
domain.append(fromDomain);
password.append(fromPassword);
}
@Override
public int OnVerifiyCertificate(String commonName, String subject,
String issuer, String fingerprint, boolean mismatch) {
Log.d(TAG, "OnVerifiyCertificate called.");
// Send a message containing the certificate to our handler.
Message m = new Message();
m.setTarget(handler);
m.what = RemoteClientLibConstants.DIALOG_RDP_CERT;
Bundle strings = new Bundle();
strings.putString("subject", subject);
strings.putString("issuer", issuer);
strings.putString("fingerprint", fingerprint);
m.obj = strings;
handler.sendMessage(m);
// Block while user decides whether to accept certificate or not.
// The activity ends if the user taps "No", so we block indefinitely here.
synchronized (this) {
while (!certificateAccepted) {
try {
this.wait();
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException: " + Log.getStackTraceString(e));
}
}
}
return 1;
}
@Override
public boolean OnGatewayAuthenticate(StringBuilder username,
StringBuilder domain, StringBuilder password) {
Log.d(TAG, "OnGatewayAuthenticate called.");
gatewayAuthenticationAttempted = true;
setCredentialsStringBuildersToValues(
username, domain, password, this.username, this.domain, this.password
);
return true;
}
@Override
public int OnVerifyChangedCertificate(String commonName, String subject,
String issuer, String fingerprint, String oldSubject,
String oldIssuer, String oldFingerprint) {
Log.d(TAG, "OnVerifyChangedCertificate called.");
return this.OnVerifiyCertificate(commonName, subject, issuer, fingerprint, true);
}
@Override
public void OnGraphicsUpdate(int x, int y, int width, int height) {
//Log.v(TAG, "OnGraphicsUpdate called: " + x +", " + y + " + " + width + "x" + height );
if (!receivedFirstGraphicsFrame) {
receivedFirstGraphicsFrame = true;
handler.sendEmptyMessage(RemoteClientLibConstants.GRAPHICS_FIRST_FRAME_RECEIVED);
}
if (viewable != null && session != null) {
Bitmap bitmap = viewable.getBitmap();
if (bitmap != null && x + width <= bitmap.getWidth() && y + height <= bitmap.getHeight()) {
LibFreeRDP.updateGraphics(session.getInstance(), bitmap, x, y, width, height);
applyFloydSteinbergDithering(bitmap, x, y, width, height);
viewable.reDraw(x, y, width, height);
}
}
}
@Override
public void OnGraphicsResize(int width, int height, int bpp) {
Log.d(TAG, "OnGraphicsResize called " + width + "x" + height + ", bpp:" + bpp);
OnSettingsChanged(width, height, bpp);
}
@Override
public void OnRemoteClipboardChanged(String data) {
Log.d(TAG, "OnRemoteClipboardChanged called.");
remoteClipboardChanged(data);
}
public static class DisconnectThread extends Thread {
long instance;
public DisconnectThread(long i) {
this.instance = i;
}
public void run() {
LibFreeRDP.disconnect(instance);
//LibFreeRDP.freeInstance(instance);
}
}
}