FreeRDP
Loading...
Searching...
No Matches
SessionActivity.java
1/*
2 Android Session Activity
3
4 Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz
5 Copyright 2026 Ibrahim Sevinc <ibrahim.sevinc.mail@gmail.com>
6
7 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
8 If a copy of the MPL was not distributed with this file, You can obtain one at
9 http://mozilla.org/MPL/2.0/.
10 */
11
12package com.freerdp.freerdpcore.presentation;
13
14import android.Manifest;
15import android.content.Context;
16import android.content.Intent;
17import android.content.pm.PackageManager;
18import android.content.res.Configuration;
19import android.graphics.Bitmap;
20import android.graphics.Bitmap.Config;
21import android.graphics.Rect;
22import android.graphics.drawable.BitmapDrawable;
23import android.net.Uri;
24import android.os.Build;
25import android.os.Bundle;
26import android.os.Handler;
27import android.os.Looper;
28import android.os.Message;
29
30import androidx.activity.OnBackPressedCallback;
31import androidx.annotation.NonNull;
32import androidx.annotation.RequiresApi;
33import androidx.appcompat.app.AppCompatActivity;
34import androidx.core.graphics.Insets;
35import androidx.core.view.ViewCompat;
36import androidx.core.view.WindowCompat;
37import androidx.core.view.WindowInsetsCompat;
38import androidx.core.view.WindowInsetsControllerCompat;
39import androidx.lifecycle.ViewModelProvider;
40
41import android.util.Log;
42import android.view.KeyEvent;
43import android.view.MotionEvent;
44import android.view.ScaleGestureDetector;
45import android.view.View;
46import android.view.ViewGroup;
47import android.view.ViewTreeObserver.OnGlobalLayoutListener;
48import android.view.RoundedCorner;
49import android.view.WindowInsets;
50import android.view.WindowManager;
51import android.widget.Toast;
52
53import com.freerdp.freerdpcore.R;
54import com.freerdp.freerdpcore.application.GlobalApp;
55import com.freerdp.freerdpcore.application.SessionState;
56import com.freerdp.freerdpcore.domain.BookmarkBase;
57import com.freerdp.freerdpcore.domain.ConnectionReference;
58import com.freerdp.freerdpcore.services.LibFreeRDP;
59import com.freerdp.freerdpcore.utils.ClipboardManagerProxy;
60
61public class SessionActivity extends AppCompatActivity
62 implements LibFreeRDP.UIEventListener, ClipboardManagerProxy.OnClipboardChangedListener
63{
64 public static final String PARAM_CONNECTION_REFERENCE = "conRef";
65 public static final String PARAM_INSTANCE = "instance";
66 private static final String TAG = "FreeRDP.SessionActivity";
67 static volatile SessionActivity activeSession;
68 private Bitmap bitmap;
69 private SessionState session;
70 private SessionView sessionView;
71 private TouchPointerView touchPointerView;
72
73 private static final int REFRESH_SESSIONVIEW = 1;
74 private static final int DISPLAY_TOAST = 2;
75 private static final int GRAPHICS_CHANGED = 6;
76 private static final int POINTER_SET = 7;
77 private static final int REQUEST_MEDIA_PERMISSIONS = 100;
78
79 private RailWindowManager railManager;
80
81 private final Handler uiHandler = new Handler(Looper.getMainLooper()) {
82 @Override public void handleMessage(Message msg)
83 {
84 switch (msg.what)
85 {
86 case GRAPHICS_CHANGED:
87 {
88 sessionView.onSurfaceChange(session);
89 scrollView.requestLayout();
90 break;
91 }
92 case REFRESH_SESSIONVIEW:
93 {
94 sessionView.invalidateRegion();
95 break;
96 }
97 case DISPLAY_TOAST:
98 {
99 Toast errorToast = Toast.makeText(getApplicationContext(), msg.obj.toString(),
100 Toast.LENGTH_LONG);
101 errorToast.show();
102 break;
103 }
104 case POINTER_SET:
105 {
106 Bundle data = msg.getData();
107 if (data != null && data.containsKey("pixels"))
108 {
109 int[] pixels = data.getIntArray("pixels");
110 int width = data.getInt("width");
111 int height = data.getInt("height");
112 int hotX = data.getInt("hotX");
113 int hotY = data.getInt("hotY");
114 sessionView.setRemoteCursor(pixels, width, height, hotX, hotY);
115 if (touchPointerView != null)
116 touchPointerView.setRemoteCursor(pixels, width, height, hotX, hotY);
117 }
118 else
119 {
120 sessionView.setRemoteCursor(null, 0, 0, 0, 0);
121 if (touchPointerView != null)
122 touchPointerView.setRemoteCursor(null, 0, 0, 0, 0);
123 }
124 break;
125 }
126 }
127 }
128 };
129
130 private int screen_width;
131 private int screen_height;
132
133 private BookmarkBase pendingConnectBookmark = null;
134 private boolean connectCancelledByUser = false;
135 private boolean sessionRunning = false;
136 private long backPressedTime = 0;
137
138 private SessionViewModel sessionViewModel;
139 private ScrollView2D scrollView;
140 private ClipboardManagerProxy mClipboardManager;
141 private SessionInputManager inputManager;
142 private SessionDialogs dialogs;
143
144 private FloatingToolbar floatingToolbar;
145
146 void hideSystemBars()
147 {
148 boolean hideStatusBar = ApplicationSettingsActivity.getHideStatusBar(this);
149 boolean hideNavBar = ApplicationSettingsActivity.getHideNavigationBar(this);
150
151 if (inputManager != null && inputManager.isSoftInputActive())
152 {
153 // out of immersive mode while the IME is up, so the back gesture works right away
154 hideNavBar = false;
155 }
156
157 WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
158
159 if (getSupportActionBar() != null)
160 getSupportActionBar().hide();
161
162 WindowInsetsControllerCompat controller =
163 WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
164 controller.setAppearanceLightStatusBars(false);
165 controller.setAppearanceLightNavigationBars(false);
166
167 getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
168 getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);
169 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
170 getWindow().setNavigationBarContrastEnforced(false);
171
172 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
173 {
174 int toHide = 0;
175 int toShow = 0;
176 if (hideStatusBar)
177 toHide |= WindowInsetsCompat.Type.statusBars();
178 else
179 toShow |= WindowInsetsCompat.Type.statusBars();
180
181 if (hideNavBar)
182 toHide |= WindowInsetsCompat.Type.navigationBars();
183 else
184 toShow |= WindowInsetsCompat.Type.navigationBars();
185
186 if (toHide != 0)
187 {
188 // whatever stays hidden keeps immersive behaviour; BEHAVIOR_DEFAULT would let any
189 // tap on the session pull the bar back in
190 controller.setSystemBarsBehavior(
191 WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
192 controller.hide(toHide);
193 }
194
195 if (toShow != 0)
196 {
197 controller.show(toShow);
198 }
199 }
200 else
201 {
202 // API 29: layout flags must be set explicitly to keep drawing behind system bars.
203 int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
204 View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
205 if (hideStatusBar)
206 flags |= View.SYSTEM_UI_FLAG_FULLSCREEN;
207 if (hideNavBar)
208 flags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
209 if ((flags & (View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)) !=
210 0)
211 flags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
212
213 getWindow().getDecorView().setSystemUiVisibility(flags);
214 }
215
216 WindowManager.LayoutParams lp = getWindow().getAttributes();
217 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
218 lp.layoutInDisplayCutoutMode =
219 WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
220 else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
221 lp.layoutInDisplayCutoutMode =
222 WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
223 getWindow().setAttributes(lp);
224 }
225
226 @Override public void onCreate(Bundle savedInstanceState)
227 {
228 super.onCreate(savedInstanceState);
229
230 hideSystemBars();
231
232 this.setContentView(R.layout.session);
233
234 Log.v(TAG, "Session.onCreate");
235
236 // ATTENTION: We use the onGlobalLayout notification to start our
237 // session.
238 // This is because only then we can know the exact size of our session
239 // when using fit screen
240 // accounting for any status bars etc. that Android might throws on us.
241 // A bit weird looking
242 // but this is the only way ...
243 final View activityRootView = findViewById(R.id.session_root_view);
244 activityRootView.setFitsSystemWindows(false);
245 ViewCompat.setOnApplyWindowInsetsListener(activityRootView,
246 (v, insets) -> onWindowInsetsChanged(v, insets));
247 activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
248 new OnGlobalLayoutListener() {
249 @Override public void onGlobalLayout()
250 {
251 screen_width = scrollView.getWidth() - scrollView.getPaddingLeft() -
252 scrollView.getPaddingRight();
253 screen_height = scrollView.getHeight() - scrollView.getPaddingTop() -
254 scrollView.getPaddingBottom();
255
256 // start session
257 if (!sessionRunning && getIntent() != null)
258 {
259 processIntent(getIntent());
260 sessionRunning = true;
261 }
262 }
263 });
264
265 sessionView = findViewById(R.id.sessionView);
266 sessionView.requestFocus();
267
268 touchPointerView = findViewById(R.id.touchPointerView);
269
270 floatingToolbar = new FloatingToolbar(this, new FloatingToolbar.Listener() {
271 @Override public void onToggleTouchPointer()
272 {
273 if (inputManager != null)
274 inputManager.toggleTouchPointer();
275 }
276 @Override public void onToggleKeyboard()
277 {
278 if (inputManager != null)
279 inputManager.toggleKeyboard();
280 }
281 });
282
283 ExtendedKeyboardView keyboard = findViewById(R.id.extended_keyboard);
284
285 scrollView = findViewById(R.id.sessionScrollView);
286 scrollView.setScrollViewListener(null);
287 railManager = new RailWindowManager(this, findViewById(R.id.railContainer), sessionView);
288 sessionViewModel = new ViewModelProvider(this).get(SessionViewModel.class);
289 sessionViewModel.getState().observe(this, this::onConnectionStateChanged);
290
291 dialogs = new SessionDialogs(this, new SessionDialogs.OnUserCancelListener() {
292 @Override public void onUserCancel()
293 {
294 connectCancelledByUser = true;
295 }
296 });
297
298 // Wire up the input manager (instance is attached later in bindSession()).
299 inputManager =
300 new SessionInputManager(this, scrollView, sessionView, touchPointerView, keyboard);
301 sessionView.setSessionViewListener(inputManager);
302 touchPointerView.setTouchPointerListener(inputManager);
303 sessionView.setScaleGestureDetector(
304 new ScaleGestureDetector(this, inputManager.getPinchZoomListener()));
305
306 mClipboardManager = ClipboardManagerProxy.getClipboardManager(this);
307 mClipboardManager.addClipboardChangedListener(this);
308
309 getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
310 @Override public void handleOnBackPressed()
311 {
312 handleBackPressed();
313 }
314 });
315
316 hideSystemBars();
317 }
318
319 @Override public void onWindowFocusChanged(boolean hasFocus)
320 {
321 super.onWindowFocusChanged(hasFocus);
322 if (hasFocus)
323 {
324 hideSystemBars();
325 mClipboardManager.getPrimaryClipManually();
326 }
327 }
328
329 @Override protected void onStart()
330 {
331 super.onStart();
332 Log.v(TAG, "Session.onStart");
333 if (session != null)
334 LibFreeRDP.setForeground(session.getInstance(), true);
335 }
336
337 @Override protected void onRestart()
338 {
339 super.onRestart();
340 Log.v(TAG, "Session.onRestart");
341 }
342
343 @Override protected void onResume()
344 {
345 super.onResume();
346 Log.v(TAG, "Session.onResume");
347 activeSession = this;
348 }
349
350 @Override protected void onPause()
351 {
352 super.onPause();
353 Log.v(TAG, "Session.onPause");
354 if (activeSession == this)
355 activeSession = null;
356 // hide any visible keyboards
357 inputManager.hideKeyboards();
358 }
359
360 @Override protected void onStop()
361 {
362 super.onStop();
363 Log.v(TAG, "Session.onStop");
364 if (session != null)
365 LibFreeRDP.setForeground(session.getInstance(), false);
366 }
367
368 @Override protected void onDestroy()
369 {
370 if (connectThread != null)
371 {
372 connectThread.interrupt();
373 }
374 super.onDestroy();
375 Log.v(TAG, "Session.onDestroy");
376
377 // Cancel running disconnect timers.
378 GlobalApp.cancelDisconnectTimer();
379
380 // Disconnect only this activity's session.
381 if (session != null)
382 LibFreeRDP.disconnect(session.getInstance());
383
384 // unregister freerdp session listener
385 sessionViewModel.unregister();
386
387 // remove clipboard listener
388 mClipboardManager.removeClipboardboardChangedListener(this);
389
390 // free session
391 GlobalApp.freeSession(session.getInstance());
392
393 session = null;
394 }
395
396 @Override public void onConfigurationChanged(Configuration newConfig)
397 {
398 super.onConfigurationChanged(newConfig);
399
400 hideSystemBars();
401
402 // screen_width/screen_height will be updated by the next onGlobalLayout callback;
403 if (session != null && session.getBookmark() != null &&
404 session.getBookmark().getActiveScreenSettings().isFitScreen())
405 {
406 scrollView.post(() -> {
407 if (screen_width > 0 && screen_height > 0)
408 LibFreeRDP.sendMonitorLayout(session.getInstance(), screen_width,
409 screen_height);
410 });
411 }
412 }
413
414 private WindowInsetsCompat onWindowInsetsChanged(View rootView, WindowInsetsCompat windowInsets)
415 {
416 boolean fitSafeArea = ApplicationSettingsActivity.getFitRoundedCorners(this);
417 boolean hideStatusBar = ApplicationSettingsActivity.getHideStatusBar(this);
418 boolean hideNavBar = ApplicationSettingsActivity.getHideNavigationBar(this);
419
420 int insetsTop = windowInsets
421 .getInsets(WindowInsetsCompat.Type.statusBars() |
422 WindowInsetsCompat.Type.displayCutout())
423 .top;
424 rootView.setPadding(0, hideStatusBar ? 0 : insetsTop, 0, 0);
425 Insets navInsets = hideNavBar
426 ? Insets.NONE
427 : windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars());
428 if (floatingToolbar != null)
429 floatingToolbar.setInsets(navInsets.left, hideStatusBar ? 0 : insetsTop,
430 navInsets.right, navInsets.bottom);
431
432 int safeLeft = 0, safeTop = 0, safeRight = 0, safeBottom = 0;
433 if (fitSafeArea && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
434 {
435 WindowInsets platformInsets = windowInsets.toWindowInsets();
436 if (platformInsets != null)
437 {
438 boolean landscape = getResources().getConfiguration().orientation ==
439 Configuration.ORIENTATION_LANDSCAPE;
440
441 int radTL = cornerRadius(platformInsets, RoundedCorner.POSITION_TOP_LEFT);
442 int radBL = cornerRadius(platformInsets, RoundedCorner.POSITION_BOTTOM_LEFT);
443 int radTR = cornerRadius(platformInsets, RoundedCorner.POSITION_TOP_RIGHT);
444 int radBR = cornerRadius(platformInsets, RoundedCorner.POSITION_BOTTOM_RIGHT);
445
446 if (landscape)
447 {
448 safeLeft = Math.max(0, Math.max(radTL, radBL) - rootView.getPaddingLeft());
449 safeRight = Math.max(0, Math.max(radTR, radBR) - rootView.getPaddingRight());
450 }
451 else
452 {
453 safeTop = Math.max(0, Math.max(radTL, radTR) - rootView.getPaddingTop());
454 safeBottom = Math.max(0, Math.max(radBL, radBR) - rootView.getPaddingBottom());
455 }
456 }
457 }
458
459 int imeBottom = windowInsets.getInsets(WindowInsetsCompat.Type.ime()).bottom;
460
461 // the only reliable account of whether the IME is really on screen: it lets the input
462 // manager tell an external dismissal from a show request that has not animated in yet
463 if (inputManager != null)
464 inputManager.onImeVisibilityChanged(imeBottom > 0);
465
466 View extKeyboard = findViewById(R.id.extended_keyboard);
467 if (extKeyboard instanceof ExtendedKeyboardView)
468 {
469 // imeBottom already covers the nav bar, so don't pad for it twice
470 int kbdBottom = imeBottom > 0 ? 0 : navInsets.bottom;
471 ((ExtendedKeyboardView)extKeyboard)
472 .setInsets(Math.max(navInsets.left, safeLeft), Math.max(navInsets.right, safeRight),
473 kbdBottom);
474 }
475
476 // the keyboard reserves the bottom inset through its own margin, so the scroll view
477 // above it must not pad for the nav bar again
478 boolean kbdVisible = extKeyboard != null && extKeyboard.getVisibility() == View.VISIBLE;
479 int scrollBottom = kbdVisible ? 0 : Math.max(safeBottom, navInsets.bottom);
480 scrollView.setPadding(Math.max(safeLeft, navInsets.left), safeTop,
481 Math.max(safeRight, navInsets.right), scrollBottom);
482
483 // insets are consumed here, so lift the extended keyboard above the IME
484 if (extKeyboard != null)
485 {
486 ViewGroup.MarginLayoutParams lp =
487 (ViewGroup.MarginLayoutParams)extKeyboard.getLayoutParams();
488 if (lp.bottomMargin != imeBottom)
489 {
490 lp.bottomMargin = imeBottom;
491 extKeyboard.setLayoutParams(lp);
492 }
493 }
494
495 return WindowInsetsCompat.CONSUMED;
496 }
497
498 @RequiresApi(Build.VERSION_CODES.S)
499 private static int cornerRadius(WindowInsets insets, int position)
500 {
501 RoundedCorner corner = insets.getRoundedCorner(position);
502 return (corner != null) ? corner.getRadius() : 0;
503 }
504
505 private void processIntent(Intent intent)
506 {
507 // get either session instance or create one from a bookmark/uri
508 Bundle bundle = intent.getExtras();
509 Uri openUri = intent.getData();
510 if (openUri != null)
511 {
512 // Launched from URI, e.g:
513 // freerdp://user@ip:port/connect?sound=&rfx=&p=password&clipboard=%2b&themes=-
514 connect(openUri);
515 }
516 else if (bundle.containsKey(PARAM_INSTANCE))
517 {
518 int inst = bundle.getInt(PARAM_INSTANCE);
519 session = GlobalApp.getSession(inst);
520 bitmap = session.getSurface().getBitmap();
521 bindSession();
522 }
523 else if (bundle.containsKey(PARAM_CONNECTION_REFERENCE))
524 {
525 String refStr = bundle.getString(PARAM_CONNECTION_REFERENCE);
526 if (ConnectionReference.isHostnameReference(refStr))
527 {
528 BookmarkBase bookmark = new BookmarkBase();
529 bookmark.setHostname(ConnectionReference.getHostname(refStr));
530 connect(bookmark);
531 }
532 else if (ConnectionReference.isBookmarkReference(refStr))
533 {
534 sessionViewModel.loadBookmarkById(ConnectionReference.getBookmarkId(refStr),
535 bookmark -> {
536 if (bookmark != null)
537 connect(bookmark);
538 else
539 closeSessionActivity(RESULT_CANCELED);
540 });
541 }
542 else
543 {
544 closeSessionActivity(RESULT_CANCELED);
545 }
546 }
547 else
548 {
549 // no session found - exit
550 closeSessionActivity(RESULT_CANCELED);
551 }
552 }
553
554 private void connect(BookmarkBase bookmark)
555 {
556 session = GlobalApp.createSession(bookmark, getApplicationContext());
557
558 BookmarkBase.ScreenSettings screenSettings =
559 session.getBookmark().getActiveScreenSettings();
560 Log.v(TAG, "Screen Resolution: " + screenSettings.getResolutionString());
561 if (screenSettings.isAutomatic())
562 {
563 // Instead of enforcing obsolete ratios based on screen categories,
564 // directly map to actual device metrics without arbitrary multi-scaling.
565 screenSettings.setHeight(screen_height);
566 screenSettings.setWidth(screen_width);
567 }
568 if (screenSettings.isFitScreen())
569 {
570 screenSettings.setHeight(screen_height);
571 screenSettings.setWidth(screen_width);
572 }
573
574 // RECORD_AUDIO / CAMERA: only if the matching redirect is enabled.
575
576 java.util.ArrayList<String> needed = new java.util.ArrayList<>();
577 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CINNAMON_BUN)
578 {
579 final String permission = Manifest.permission.ACCESS_LOCAL_NETWORK;
580
581 if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
582 needed.add(permission);
583 }
584
585 if (bookmark.getAdvancedSettings().getRedirectMicrophone() &&
586 checkSelfPermission(Manifest.permission.RECORD_AUDIO) !=
587 PackageManager.PERMISSION_GRANTED)
588 needed.add(Manifest.permission.RECORD_AUDIO);
589 if (bookmark.getAdvancedSettings().getRedirectCamera() &&
590 checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
591 needed.add(Manifest.permission.CAMERA);
592
593 if (!needed.isEmpty())
594 {
595 pendingConnectBookmark = bookmark;
596 requestPermissions(needed.toArray(new String[0]), REQUEST_MEDIA_PERMISSIONS);
597 return;
598 }
599
600 connectWithTitle(bookmark.getLabel());
601 }
602
603 @Override
604 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
605 @NonNull int[] grantResults)
606 {
607 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
608 if (requestCode == REQUEST_MEDIA_PERMISSIONS && pendingConnectBookmark != null)
609 {
610 BookmarkBase bookmark = pendingConnectBookmark;
611 pendingConnectBookmark = null;
612 connectWithTitle(bookmark.getLabel());
613 }
614 }
615
616 private void connect(Uri openUri)
617 {
618 session = GlobalApp.createSession(openUri, getApplicationContext());
619
620 connectWithTitle(openUri.getAuthority());
621 }
622
623 static class ConnectThread extends Thread
624 {
625 private final SessionState runnableSession;
626 private final Context context;
627
628 public ConnectThread(@NonNull Context context, @NonNull SessionState session)
629 {
630 this.context = context;
631 runnableSession = session;
632 }
633
634 public void run()
635 {
636 runnableSession.connect(context.getApplicationContext());
637 }
638 }
639
640 private ConnectThread connectThread = null;
641
642 private void connectWithTitle(String title)
643 {
644 session.setUIEventListener(this);
645
646 sessionViewModel.register(session.getInstance());
647
648 dialogs.showProgress(title, () -> {
649 connectCancelledByUser = true;
650 LibFreeRDP.cancelConnection(session.getInstance());
651 });
652
653 connectThread = new ConnectThread(getApplicationContext(), session);
654 connectThread.start();
655 }
656
657 // binds the current session to the activity by wiring it up with the
658 // sessionView and updating all internal objects accordingly
659 private void bindSession()
660 {
661 Log.v(TAG, "bindSession called");
662 session.setUIEventListener(this);
663 sessionView.onSurfaceChange(session);
664 scrollView.requestLayout();
665
666 Bitmap surface = session.getSurface() != null ? session.getSurface().getBitmap() : null;
667 inputManager.attachSession(session.getInstance(), surface);
668 inputManager.setScreenSize(screen_width, screen_height);
669 hideSystemBars();
670 View rootView = findViewById(R.id.session_root_view);
671 if (rootView != null)
672 ViewCompat.requestApplyInsets(rootView);
673 }
674
675 private void closeSessionActivity(int resultCode)
676 {
677 // Go back to home activity (and send intent data back to home)
678 setResult(resultCode, getIntent());
679 finish();
680 }
681
682 public void handleBackPressed()
683 {
684 // hide keyboards (if any visible) or send alt+f4 to the session
685 if (inputManager != null)
686 {
687 if (inputManager.handleKeyboardBack())
688 return;
689 if (inputManager.handleBackAsAltF4())
690 return;
691 }
692 if (System.currentTimeMillis() - backPressedTime < 2000)
693 {
694 connectCancelledByUser = true;
695 LibFreeRDP.disconnect(session.getInstance());
696 }
697 else
698 {
699 backPressedTime = System.currentTimeMillis();
700 Toast.makeText(this, R.string.session_double_back_to_exit, Toast.LENGTH_SHORT).show();
701 }
702 }
703
704 @Override public boolean onKeyLongPress(int keyCode, KeyEvent event)
705 {
706 if (inputManager.onAndroidKeyLongPress(keyCode))
707 return true;
708 return super.onKeyLongPress(keyCode, event);
709 }
710
711 boolean handleKeyEvent(KeyEvent event)
712 {
713 return inputManager != null && inputManager.onAndroidKeyEvent(event);
714 }
715
716 // android keyboard input handling
717 // We always use the unicode value to process input from the android
718 // keyboard except if key modifiers
719 // (like Win, Alt, Ctrl) are activated. In this case we will send the
720 // virtual key code to allow key
721 // combinations (like Win + E to open the explorer).
722 @Override public boolean onKeyDown(int keycode, KeyEvent event)
723 {
724 if (keycode == KeyEvent.KEYCODE_BACK)
725 return super.onKeyDown(keycode, event);
726 return inputManager.onAndroidKeyEvent(event);
727 }
728
729 @Override public boolean onKeyUp(int keycode, KeyEvent event)
730 {
731 if (keycode == KeyEvent.KEYCODE_BACK)
732 return super.onKeyUp(keycode, event);
733 return inputManager.onAndroidKeyEvent(event);
734 }
735
736 // onKeyMultiple is called for input of some special characters like umlauts
737 // and some symbol characters
738 @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
739 {
740 return inputManager.onAndroidKeyEvent(event);
741 }
742
743 // ****************************************************************************
744 // KeyboardMapper.KeyProcessingListener — delegated to SessionInputManager
745
746 // ****************************************************************************
747 // LibFreeRDP UI event listener implementation
748 @Override public void OnSettingsChanged(int width, int height, int bpp)
749 {
750
751 if (bpp > 16)
752 bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
753 else
754 bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
755
756 session.setSurface(new BitmapDrawable(getResources(), bitmap));
757
758 if (inputManager != null)
759 inputManager.setBitmap(bitmap);
760
761 if (session.getBookmark() == null)
762 {
763 // Return immediately if we launch from URI
764 return;
765 }
766 // check this settings and initial settings - if they are not equal the
767 // server doesn't support our settings
768 // FIXME: the additional check (settings.getWidth() != width + 1) is for
769 // the RDVH bug fix to avoid accidental notifications
770 // (refer to android_freerdp.c for more info on this problem)
771 BookmarkBase.ScreenSettings settings = session.getBookmark().getActiveScreenSettings();
772 if ((settings.getWidth() != width && settings.getWidth() != width + 1) ||
773 settings.getHeight() != height || settings.getColors() != bpp)
774 uiHandler.sendMessage(Message.obtain(
775 null, DISPLAY_TOAST, getResources().getText(R.string.info_capabilities_changed)));
776 }
777
778 @Override public void OnGraphicsUpdate(int x, int y, int width, int height)
779 {
780 LibFreeRDP.updateGraphics(session.getInstance(), bitmap, x, y, width, height);
781
782 sessionView.addInvalidRegion(new Rect(x, y, x + width, y + height));
783
784 /*
785 * since sessionView can only be modified from the UI thread any
786 * modifications to it need to be scheduled
787 */
788
789 uiHandler.sendEmptyMessage(REFRESH_SESSIONVIEW);
790 }
791
792 @Override public void OnReconnecting()
793 {
794 railManager.onSessionEnd();
795 uiHandler.sendMessage(Message.obtain(null, DISPLAY_TOAST,
796 getResources().getText(R.string.info_reconnecting)));
797 }
798
799 @Override public void OnGraphicsResize(int width, int height, int bpp)
800 {
801 // replace bitmap
802 if (bpp > 16)
803 bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
804 else
805 bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
806 session.setSurface(new BitmapDrawable(getResources(), bitmap));
807
808 if (inputManager != null)
809 inputManager.setBitmap(bitmap);
810
811 /*
812 * since sessionView can only be modified from the UI thread any
813 * modifications to it need to be scheduled
814 */
815 uiHandler.sendEmptyMessage(GRAPHICS_CHANGED);
816 }
817
818 @Override
819 public boolean OnAuthenticate(StringBuilder username, StringBuilder domain,
820 StringBuilder password)
821 {
822 return dialogs.promptCredentials(username, domain, password);
823 }
824
825 @Override
826 public boolean OnGatewayAuthenticate(StringBuilder username, StringBuilder domain,
827 StringBuilder password)
828 {
829 return dialogs.promptCredentials(username, domain, password);
830 }
831
832 @Override
833 public int OnVerifiyCertificateEx(String host, long port, String commonName, String subject,
834 String issuer, String fingerprint, long flags)
835 {
836 if (ApplicationSettingsActivity.getAcceptAllCertificates(this))
837 return 0;
838 return dialogs.verifyCertificate(host, port, subject, issuer, fingerprint, flags);
839 }
840
841 @Override
842 public int OnVerifyChangedCertificateEx(String host, long port, String commonName,
843 String subject, String issuer, String fingerprint,
844 String oldSubject, String oldIssuer,
845 String oldFingerprint, long flags)
846 {
847 if (ApplicationSettingsActivity.getAcceptAllCertificates(this))
848 return 0;
849 return dialogs.verifyChangedCertificate(host, port, subject, issuer, fingerprint, flags);
850 }
851
852 @Override public boolean OnExperimentalFeature(int feature)
853 {
854 final String featureKey;
855 final String displayName;
856 switch (feature)
857 {
858 case LibFreeRDP.EXPERIMENTAL_REMOTEAPP:
859 featureKey = "remoteapp";
860 displayName = getString(R.string.experimental_feature_remoteapp);
861 break;
862 case LibFreeRDP.EXPERIMENTAL_CAMERA:
863 featureKey = "camera";
864 displayName = getString(R.string.experimental_feature_camera);
865 break;
866 default:
867 return true;
868 }
869 if (ApplicationSettingsActivity.isExperimentalEnabled(this, featureKey))
870 return true;
871 // suppress the generic failure toast; the dialog explains the abort
872 connectCancelledByUser = true;
873 dialogs.showExperimentalBlocked(displayName);
874 return false;
875 }
876
877 @Override public void OnRemoteClipboardChanged(String data)
878 {
879 Log.v(TAG, "OnRemoteClipboardChanged: " + data);
880 mClipboardManager.setClipboardData(data);
881 }
882
883 @Override public void OnRemoteClipboardImageChanged(byte[] data)
884 {
885 Log.v(TAG, "OnRemoteClipboardImageChanged: " + data.length + " bytes");
886 mClipboardManager.setClipboardImage(data);
887 }
888
889 @Override public void OnPointerSet(int[] pixels, int width, int height, int hotX, int hotY)
890 {
891 Bundle data = new Bundle();
892 data.putIntArray("pixels", pixels);
893 data.putInt("width", width);
894 data.putInt("height", height);
895 data.putInt("hotX", hotX);
896 data.putInt("hotY", hotY);
897 Message msg = uiHandler.obtainMessage(POINTER_SET);
898 msg.setData(data);
899 uiHandler.sendMessage(msg);
900 }
901
902 @Override public void OnPointerSetNull()
903 {
904 uiHandler.sendEmptyMessage(POINTER_SET);
905 }
906
907 @Override public void OnPointerSetDefault()
908 {
909 sessionView.setDefaultCursor();
910 }
911
912 @Override public void OnRailWindowUpdate(long windowId, int width, int height, int[] pixels)
913 {
914 railManager.onWindowUpdate(windowId, width, height, pixels);
915 }
916
917 @Override public void OnRailWindowMove(long windowId, int x, int y, int w, int h)
918 {
919 railManager.onWindowMove(windowId, x, y, w, h);
920 }
921
922 @Override public void OnRailWindowHide(long windowId)
923 {
924 railManager.onWindowHide(windowId);
925 }
926
927 @Override public void OnRailWindowDestroy(long windowId)
928 {
929 railManager.onWindowDestroy(windowId);
930 }
931
932 @Override public void OnRailSessionEnd()
933 {
934 railManager.onSessionEnd();
935 }
936
937 @Override public void OnRailMonitoredDesktop(long[] windowIds, long activeWindowId)
938 {
939 railManager.onMonitoredDesktop(windowIds, activeWindowId);
940 }
941
942 // ****************************************************************************
943 // SessionView.SessionViewListener and TouchPointerView.TouchPointerListener
944 // — delegated to SessionInputManager
945
946 @Override public boolean onGenericMotionEvent(MotionEvent e)
947 {
948 super.onGenericMotionEvent(e);
949 return inputManager != null && inputManager.onGenericMotionEvent(e);
950 }
951
952 // ****************************************************************************
953 // ClipboardManagerProxy.OnClipboardChangedListener
954 @Override public void onClipboardChanged(String data)
955 {
956 Log.v(TAG, "onClipboardChanged: " + data);
957 if (session != null)
958 LibFreeRDP.sendClipboardData(session.getInstance(), data);
959 }
960
961 @Override public void onClipboardImageChanged(byte[] data, String mimeType)
962 {
963 if (session != null && data != null)
964 LibFreeRDP.sendClipboardImageData(session.getInstance(), data, mimeType);
965 }
966
967 private void onConnectionStateChanged(SessionViewModel.ConnectionState state)
968 {
969 if (session == null)
970 return;
971 switch (state)
972 {
973 case CONNECTED:
974 onSessionConnected();
975 break;
976 case FAILED:
977 onSessionFailed();
978 break;
979 case DISCONNECTED:
980 onSessionDisconnected();
981 break;
982 default:
983 break;
984 }
985 }
986
987 private void onSessionConnected()
988 {
989 Log.v(TAG, "onSessionConnected");
990
991 if (connectCancelledByUser)
992 {
993 LibFreeRDP.disconnect(session.getInstance());
994 closeSessionActivity(RESULT_CANCELED);
995 return;
996 }
997
998 // bind session
999 bindSession();
1000
1001 if (ApplicationSettingsActivity.getKeepScreenOnWhenConnected(this))
1002 {
1003 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1004 }
1005
1006 dialogs.dismissProgress();
1007
1008 if (session.getBookmark() == null)
1009 {
1010 // Return immediately if we launch from URI
1011 return;
1012 }
1013
1014 // add hostname to history if quick connect was used
1015 Bundle bundle = getIntent().getExtras();
1016 if (bundle != null && bundle.containsKey(PARAM_CONNECTION_REFERENCE))
1017 {
1018 if (ConnectionReference.isHostnameReference(
1019 bundle.getString(PARAM_CONNECTION_REFERENCE)))
1020 {
1021 assert session.getBookmark().getType() == BookmarkBase.TYPE_MANUAL;
1022 sessionViewModel.recordQuickConnectHistory(session.getBookmark().getHostname());
1023 }
1024 }
1025 }
1026
1027 private void onSessionFailed()
1028 {
1029 Log.v(TAG, "onSessionFailed");
1030
1031 // cancel any pending input events
1032 if (inputManager != null)
1033 inputManager.cancelPendingEvents();
1034
1035 dialogs.dismissProgress();
1036
1037 // post error message on UI thread
1038 if (!connectCancelledByUser)
1039 uiHandler.sendMessage(Message.obtain(
1040 null, DISPLAY_TOAST, getResources().getText(R.string.error_connection_failure)));
1041
1042 closeSessionActivity(RESULT_CANCELED);
1043 }
1044
1045 private void onSessionDisconnected()
1046 {
1047 Log.v(TAG, "onSessionDisconnected");
1048
1049 // cancel any pending input events
1050 if (inputManager != null)
1051 inputManager.cancelPendingEvents();
1052
1053 if (ApplicationSettingsActivity.getKeepScreenOnWhenConnected(this))
1054 {
1055 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1056 }
1057
1058 dialogs.dismissProgress();
1059
1060 railManager.clear();
1061
1062 session.setUIEventListener(null);
1063 closeSessionActivity(RESULT_OK);
1064 }
1065}