FreeRDP
Loading...
Searching...
No Matches
RDPSessionViewController.m
1/*
2 RDP Session View Controller
3
4 Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz
5
6 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
7 If a copy of the MPL was not distributed with this file, You can obtain one at
8 http://mozilla.org/MPL/2.0/.
9 */
10
11#import <QuartzCore/QuartzCore.h>
12#import <GameController/GameController.h>
13#import <objc/runtime.h>
14#import "RDPSessionViewController.h"
15#import "RDPSessionToolbar.h"
16#import "RDPOverlayStyle.h"
17#import "RDPKeyboard.h"
18#import "Utils.h"
19#import "Toast+UIView.h"
20#import "ConnectionParams.h"
21
22#define TOOLBAR_HEIGHT 44
23#define KEYBOARD_CURSOR_MARGIN 44.0
24
25@interface RDPSessionViewController (Private)
26- (void)showSessionToolbar:(BOOL)show;
27- (void)initGestureRecognizers;
28- (void)suspendSession;
29- (void)fitSessionViewToViewport;
30- (void)centerSessionViewInViewport;
31- (void)setKeyboardOverlap:(CGFloat)overlap;
32- (CGRect)sessionViewportFrame;
33- (void)installHingeInteraction;
34- (BOOL)hasHinge;
35- (BOOL)isHingeOpen;
36- (void)showConnectingViewWithText:(NSString *)text;
37- (void)hideConnectingView;
38- (void)endBackgroundTask;
39- (void)scheduleRemoteResize;
40- (void)cancelRemoteResize;
41- (void)sendRemoteResize;
42- (CGPoint)remotePositionForSessionViewPosition:(CGPoint)position;
43- (CGPoint)sessionViewPositionForRemotePosition:(CGPoint)position;
44- (CGPoint)clampedSessionViewCursorPosition:(CGPoint)position;
45- (NSDictionary *)eventDescriptorForMouseEvent:(int)event position:(CGPoint)position;
46- (void)handleMouseMoveForPosition:(CGPoint)position;
47- (CGPoint)currentCursorViewPosition;
48- (void)moveCursorByViewportDelta:(CGPoint)delta;
49- (void)moveCursorToSessionViewPosition:(CGPoint)position;
50- (void)sendMouseButtonEvent:(int)event;
51- (BOOL)isKeyboardActive;
52- (BOOL)isLandscape;
53- (CGFloat)advancedKeyboardHeight;
54- (void)resetTextInput;
55- (void)commitTextInput;
56@end
57
58// dummy text field
59@interface RDPSessionTextField : UITextField
60@end
61
62@implementation RDPSessionTextField
63
64- (void)deleteBackward
65{
66 // send backspace to remote session if dummy text field is empty.
67 if ([[self text] length] == 0)
68 [[RDPKeyboard getSharedRDPKeyboard] sendBackspaceKeyStroke];
69 [super deleteBackward];
70}
71
72@end
73
74@implementation RDPSessionViewController
75
76#pragma mark class methods
77
78- (id)initWithNibName:(NSString *)nibNameOrNil
79 bundle:(NSBundle *)nibBundleOrNil
80 session:(RDPSession *)session
81{
82 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
83 if (self)
84 {
85 _session = [session retain];
86 [_session setDelegate:self];
87 _session_initilized = NO;
88
89 _advanced_keyboard_view = nil;
90 _sent_text = [@"" retain];
91 _last_session_viewport_size = CGSizeZero;
92
93 _session_toolbar_visible = NO;
94
95 _cursor_view_position = CGPointZero;
96 _last_mouse_pan_location = CGPointZero;
97 _has_cursor_view_position = NO;
98 _has_user_moved_cursor = NO;
99 _mouse_pan_active = NO;
100 _long_press_active = NO;
101 _mouse_drag_active = NO;
102 _pointer_is_indirect = NO;
103 }
104
105 return self;
106}
107
108// Implement loadView to create a view hierarchy programmatically, without using a nib.
109- (void)loadView
110{
111 // load default view and set background color and resizing mask
112 [super loadView];
113
114 // let pointer input pass through the session toolbar to the remote session
115 object_setClass(_session_toolbar, [RDPSessionToolbar class]);
116 [(RDPSessionToolbar *)_session_toolbar setPassthroughView:_session_scrollview];
117 if (RDPSupportLiquidGlass() == NO)
118 {
119 // before ios 26, the gray background has been displayed in toolbar
120 UIToolbarAppearance *appearance = [[[UIToolbarAppearance alloc] init] autorelease];
121
122 // set transparent background
123 [appearance configureWithTransparentBackground];
124 [_session_toolbar setStandardAppearance:appearance];
125 [_session_toolbar setCompactAppearance:appearance];
126 [_session_toolbar setScrollEdgeAppearance:appearance];
127 [_session_toolbar setCompactScrollEdgeAppearance:appearance];
128 }
129
130 // init keyboard toolbar
131 _keyboard_toolbar = [[RDPKeyboardToolbarView alloc] initWithTarget:self];
132 [_dummy_textfield setInputAccessoryView:_keyboard_toolbar];
133
134 // the text field must not alter when typed
135 [_dummy_textfield setAutocapitalizationType:UITextAutocapitalizationTypeNone];
136 [_dummy_textfield setSpellCheckingType:UITextSpellCheckingTypeNo];
137 [_dummy_textfield setSmartQuotesType:UITextSmartQuotesTypeNo];
138 [_dummy_textfield setSmartDashesType:UITextSmartDashesTypeNo];
139 [_dummy_textfield setSmartInsertDeleteType:UITextSmartInsertDeleteTypeNo];
140 [_dummy_textfield addTarget:self
141 action:@selector(textInputChanged:)
142 forControlEvents:UIControlEventEditingChanged];
143
144 // the undo/redo/paste shortcuts of the iPad keyboard act on the hidden text field, not on
145 // the remote session, so don't show them
146 [[_dummy_textfield inputAssistantItem] setLeadingBarButtonGroups:@[]];
147 [[_dummy_textfield inputAssistantItem] setTrailingBarButtonGroups:@[]];
148
149 // init gesture recognizers
150 [self initGestureRecognizers];
151
152 // hide session toolbar
153 [_session_toolbar
154 setFrame:CGRectMake(0.0, -TOOLBAR_HEIGHT, [[self view] bounds].size.width, TOOLBAR_HEIGHT)];
155}
156
157// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
158- (void)viewDidLoad
159{
160 [super viewDidLoad];
161
162 // shown around the session when it avoids the screen edges
163 [[self view] setBackgroundColor:[UIColor blackColor]];
164
165 [_session_scrollview setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
166 [_session_scrollview setContentInset:UIEdgeInsetsZero];
167 [_session_scrollview setScrollIndicatorInsets:UIEdgeInsetsZero];
168 [_session_scrollview setShowsHorizontalScrollIndicator:NO];
169 [_session_scrollview setShowsVerticalScrollIndicator:NO];
170 [_session_scrollview setAlwaysBounceHorizontal:NO];
171 [_session_scrollview setAlwaysBounceVertical:NO];
172 [_session_scrollview setBounces:NO];
173
174 [self installHingeInteraction];
175}
176
177- (void)viewDidLayoutSubviews
178{
179 [super viewDidLayoutSubviews];
180
181 CGRect viewportFrame = [self sessionViewportFrame];
182 [_session_scrollview setFrame:viewportFrame];
183
184 CGSize viewportSize = [_session_scrollview bounds].size;
185 if (!CGSizeEqualToSize(viewportSize, _last_session_viewport_size))
186 {
187 [self fitSessionViewToViewport];
188 [self scheduleRemoteResize];
189 }
190 else
191 [self centerSessionViewInViewport];
192}
193
194- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
195{
196 return YES;
197}
198
199- (BOOL)prefersStatusBarHidden
200{
201 return YES;
202}
203
204- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
205{
206 return UIStatusBarAnimationSlide;
207}
208
209- (void)viewWillTransitionToSize:(CGSize)size
210 withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
211{
212 [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
213
214 // the system keyboard changes its height with the orientation, so follow it
215 [coordinator
216 animateAlongsideTransition:nil
217 completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
218 if (!_advanced_keyboard_view)
219 return;
220 CGRect frame = [_advanced_keyboard_view frame];
221 frame.size.height = [self advancedKeyboardHeight];
222 [_advanced_keyboard_view setFrame:frame];
223 [_dummy_textfield reloadInputViews];
224 }];
225}
226
227- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
228{
229 (void)fromInterfaceOrientation;
230 [self centerSessionViewInViewport];
231}
232
233- (void)didReceiveMemoryWarning
234{
235 // Releases the view if it doesn't have a superview.
236 [super didReceiveMemoryWarning];
237
238 // Release any cached data, images, etc. that aren't in use.
239}
240
241- (void)viewDidUnload
242{
243 [super viewDidUnload];
244 // Release any retained subviews of the main view.
245 // e.g. self.myOutlet = nil;
246}
247
248- (void)viewWillAppear:(BOOL)animated
249{
250 [super viewWillAppear:animated];
251
252 // remote screen always fit in device screen
253 [self setNeedsStatusBarAppearanceUpdate];
254 [[self navigationController] setNeedsStatusBarAppearanceUpdate];
255 [[self navigationController] setNavigationBarHidden:YES animated:animated];
256 if (@available(iOS 18.0, *))
257 [[self tabBarController] setTabBarHidden:YES animated:animated];
258 else
259 [[[self tabBarController] tabBar] setHidden:YES];
260
261 // if session is suspended - notify that we got a new bitmap context
262 if ([_session isSuspended])
263 [self sessionBitmapContextWillChange:_session];
264
265 // init keyboard
266 [[RDPKeyboard getSharedRDPKeyboard] initWithSession:_session delegate:self];
267}
268
269- (void)viewDidAppear:(BOOL)animated
270{
271 [super viewDidAppear:animated];
272
273 if (!_session_initilized)
274 {
275 if ([_session isSuspended])
276 {
277 [_session resume];
278 [self sessionBitmapContextDidChange:_session];
279 [self scheduleRemoteResize];
280 }
281 else
282 [_session connect];
283
284 _session_initilized = YES;
285 }
286}
287
288- (void)viewWillDisappear:(BOOL)animated
289{
290 [super viewWillDisappear:animated];
291 if (_mouse_drag_active)
292 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(NO)];
293 _mouse_drag_active = NO;
294 _mouse_pan_active = NO;
295 _long_press_active = NO;
296
297 [[self navigationController] setNeedsStatusBarAppearanceUpdate];
298 [[self navigationController] setNavigationBarHidden:NO animated:animated];
299 if (@available(iOS 18.0, *))
300 [[self tabBarController] setTabBarHidden:NO animated:animated];
301 else
302 [[[self tabBarController] tabBar] setHidden:NO];
303
304 // reset all modifier keys on rdp keyboard
305 [[RDPKeyboard getSharedRDPKeyboard] reset];
306
307 // hide toolbar and keyboard
308 [self showSessionToolbar:NO];
309 [_dummy_textfield resignFirstResponder];
310}
311
312- (void)dealloc
313{
314 // remove any observers
315 [[NSNotificationCenter defaultCenter] removeObserver:self];
316
317 // the session lives on longer so set the delegate to nil
318 [_session setDelegate:nil];
319
320 [_advanced_keyboard_view release];
321 [_keyboard_toolbar release];
322 [_sent_text release];
323 [_session release];
324 [super dealloc];
325}
326
327#pragma mark -
328#pragma mark ScrollView delegate methods
329
330- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
331{
332 return _session_view;
333}
334
335- (void)scrollViewDidZoom:(UIScrollView *)scrollView
336{
337 [self centerSessionViewInViewport];
338}
339
340- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView
341 withView:(UIView *)view
342 atScale:(CGFloat)scale
343{
344 NSLog(@"New zoom scale: %f", scale);
345 [self centerSessionViewInViewport];
346 [_session_view setNeedsDisplayInRemoteRect:[_session_view bounds]];
347}
348
349#pragma mark -
350#pragma mark TextField delegate methods
351- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
352{
353 return YES;
354}
355
356- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
357{
358 [self destroyAdvancedKeyboard];
359 return YES;
360}
361
362- (void)textFieldDidEndEditing:(UITextField *)textField
363{
364 [self commitTextInput];
365}
366
367- (BOOL)textFieldShouldReturn:(UITextField *)textField
368{
369 [self commitTextInput];
370 [[RDPKeyboard getSharedRDPKeyboard] sendEnterKeyStroke];
371
372 // turn off default action
373 return NO;
374}
375
376// sends what changed in the text field since the last time
377- (void)textInputChanged:(UITextField *)textField
378{
379 // send marked text (chinese, japanese) only once committed, sending every change
380 // arrives out of order on the server
381 if ([textField markedTextRange] != nil)
382 return;
383
384 // a letter typed with a toolbar modifier is a shortcut (e.g. ctrl+a). read it before
385 // sending, which releases the modifiers
386 RDPKeyboard *keyboard = [RDPKeyboard getSharedRDPKeyboard];
387 BOOL modifierPressed = [keyboard ctrlPressed] || [keyboard altPressed] ||
388 [keyboard winPressed] || [keyboard altGrPressed];
389
390 NSString *text = [textField text] != nil ? [textField text] : @"";
391 NSUInteger length = MIN([text length], [_sent_text length]);
392 NSUInteger common = 0;
393
394 while (common < length)
395 {
396 if ([text characterAtIndex:common] != [_sent_text characterAtIndex:common])
397 {
398 break;
399 }
400 common++;
401 }
402
403 // don't split a multi code point character (e.g. emoji)
404 if (common < [_sent_text length])
405 common = MIN(common, [_sent_text rangeOfComposedCharacterSequenceAtIndex:common].location);
406 if (common < [text length])
407 common = MIN(common, [text rangeOfComposedCharacterSequenceAtIndex:common].location);
408
409 for (NSUInteger i = common; i < [_sent_text length];)
410 {
411 NSRange range = [_sent_text rangeOfComposedCharacterSequenceAtIndex:i];
412 [keyboard sendBackspaceKeyStroke];
413 i = NSMaxRange(range);
414 }
415
416 for (NSUInteger i = common; i < [text length]; i++)
417 {
418 [keyboard sendUnicode:[text characterAtIndex:i]];
419 }
420
421 BOOL isLastCharLetter = NO;
422 if ([text length] > 0)
423 {
424 isLastCharLetter = [[NSCharacterSet letterCharacterSet]
425 characterIsMember:[text characterAtIndex:[text length] - 1]];
426 }
427
428 // some keyboard (korean) composes with the letters before the cursor
429 // keep it
430 if (modifierPressed || !isLastCharLetter)
431 {
432 [self resetTextInput];
433 }
434 else
435 {
436 [_sent_text release];
437 _sent_text = [text copy];
438 }
439}
440
441#pragma mark -
442#pragma mark AdvancedKeyboardDelegate functions
443- (void)advancedKeyPressedVKey:(NSInteger)key
444{
445 [self commitTextInput];
446 [[RDPKeyboard getSharedRDPKeyboard] sendVirtualKeyCode:key];
447}
448
449#pragma mark - RDP keyboard handler
450
451- (void)modifiersChangedForKeyboard:(RDPKeyboard *)keyboard
452{
453 [_keyboard_toolbar updateModifiersWithKeyboard:keyboard];
454}
455
456#pragma mark -
457#pragma mark RDPSessionDelegate functions
458
459- (void)session:(RDPSession *)session didFailToConnect:(int)reason
460{
461 [self hideConnectingView];
462
463 // return to bookmark list
464 [[self navigationController] popViewControllerAnimated:YES];
465}
466
467- (void)sessionWillConnect:(RDPSession *)session
468{
469 [self showConnectingViewWithText:NSLocalizedString(@"Connecting",
470 @"Connecting progress view - label")];
471}
472
473- (void)sessionWillReconnect:(RDPSession *)session
474{
475 (void)session;
476 [self showConnectingViewWithText:NSLocalizedString(
477 @"Reconnecting",
478 @"Connecting progress view - reconnect label")];
479}
480
481- (void)sessionDidReconnect:(RDPSession *)session
482{
483 (void)session;
484 [self hideConnectingView];
485}
486
487- (void)sessionDidActivateDisplayControl:(RDPSession *)session
488{
489 (void)session;
490 // a request made before the (re)connected channel was ready got dropped
491 _requested_remote_size = CGSizeZero;
492 [self scheduleRemoteResize];
493}
494
495- (void)sessionDidConnect:(RDPSession *)session
496{
497 // register keyboard notification handlers
498 [[NSNotificationCenter defaultCenter] addObserver:self
499 selector:@selector(keyboardWillShow:)
500 name:UIKeyboardWillShowNotification
501 object:nil];
502 [[NSNotificationCenter defaultCenter] addObserver:self
503 selector:@selector(keyboardWillHide:)
504 name:UIKeyboardWillHideNotification
505 object:nil];
506 [[NSNotificationCenter defaultCenter] addObserver:self
507 selector:@selector(keyboardDidHide:)
508 name:UIKeyboardDidHideNotification
509 object:nil];
510
511 // register hardware keyboard connection handlers (for ipad magic keyboard)
512 [[NSNotificationCenter defaultCenter] addObserver:self
513 selector:@selector(hardwareKeyboardChanged:)
514 name:GCKeyboardDidConnectNotification
515 object:nil];
516 [[NSNotificationCenter defaultCenter] addObserver:self
517 selector:@selector(hardwareKeyboardChanged:)
518 name:GCKeyboardDidDisconnectNotification
519 object:nil];
520 [self hardwareKeyboardChanged:nil];
521
522 // another app may have changed the clipboard while this one was inactive
523 [[NSNotificationCenter defaultCenter] addObserver:self
524 selector:@selector(localClipboardChanged:)
525 name:UIApplicationDidBecomeActiveNotification
526 object:nil];
527 [self localClipboardChanged:nil];
528
529 // ios can suspends the app soon after it switched to the background and may then take its
530 // socket away
531 [[NSNotificationCenter defaultCenter] addObserver:self
532 selector:@selector(applicationDidEnterBackground:)
533 name:UIApplicationDidEnterBackgroundNotification
534 object:nil];
535 [[NSNotificationCenter defaultCenter] addObserver:self
536 selector:@selector(applicationWillEnterForeground:)
537 name:UIApplicationWillEnterForegroundNotification
538 object:nil];
539
540 [self hideConnectingView];
541
542 // not on every bitmap change: with dynamic resolution that happens whenever the view resizes
543 [_session setToolbarVisible:YES];
544 [self showSessionToolbar:[_session toolbarVisible]];
545
546 // check if session settings changed ...
547 // The 2nd width check is to ignore changes in resolution settings due to the RDVH display bug
548 // (refer to RDPSEssion.m for more details)
549 ConnectionParams *orig_params = [session params];
550 rdpSettings *sess_params = [session getSessionParams];
551 const UINT32 width = freerdp_settings_get_uint32(sess_params, FreeRDP_DesktopWidth);
552 const UINT32 height = freerdp_settings_get_uint32(sess_params, FreeRDP_DesktopHeight);
553 const UINT32 depth = freerdp_settings_get_uint32(sess_params, FreeRDP_ColorDepth);
554
555 if (([orig_params intForKey:@"width"] != width &&
556 [orig_params intForKey:@"width"] != (width + 1ul)) ||
557 [orig_params intForKey:@"height"] != height || [orig_params intForKey:@"colors"] != depth)
558 {
559 // display notification that the session params have been changed by the server
560 NSString *message =
561 [NSString stringWithFormat:NSLocalizedString(
562 @"The server changed the screen settings to %dx%dx%d",
563 @"Screen settings not supported message with width, "
564 @"height and colors parameter"),
565 width, height, depth];
566 [[self view] makeToast:message duration:ToastDurationNormal position:@"bottom"];
567 }
568}
569
570- (void)sessionWillDisconnect:(RDPSession *)session
571{
572}
573
574- (void)sessionDidDisconnect:(RDPSession *)session
575{
576 [self hideConnectingView];
577 [self endBackgroundTask];
578 [self cancelRemoteResize];
579
580 // return to bookmark list
581 [[self navigationController] popViewControllerAnimated:YES];
582}
583
584- (void)sessionBitmapContextWillChange:(RDPSession *)session
585{
586 [_session_view prepareForBitmapContextChange];
587
588 // calc new view frame
589 rdpSettings *sess_params = [session getSessionParams];
590 CGRect view_rect =
591 CGRectMake(0, 0, freerdp_settings_get_uint32(sess_params, FreeRDP_DesktopWidth),
592 freerdp_settings_get_uint32(sess_params, FreeRDP_DesktopHeight));
593
594 // set session view to its native (remote) size and update content size
595 [_session_scrollview setZoomScale:1.0];
596 [_session_view setFrame:view_rect];
597 [_session_scrollview setContentSize:view_rect.size];
598 _has_cursor_view_position = NO;
599 _has_user_moved_cursor = NO;
600 _last_session_viewport_size = CGSizeZero;
601 _requested_remote_size = CGSizeZero;
602 [self fitSessionViewToViewport];
603}
604
605- (void)sessionBitmapContextDidChange:(RDPSession *)session
606{
607 // associate view with session
608 [_session_view setSession:session];
609 [_session_view setDefaultRemoteCursor];
610 if (!_has_cursor_view_position)
611 (void)[self currentCursorViewPosition];
612
613 // Upload the new desktop once; subsequent EndPaint callbacks update only dirty regions.
614 [_session_view setNeedsDisplayInRemoteRect:[_session_view bounds]];
615}
616
617- (void)session:(RDPSession *)session needsRedrawInRect:(CGRect)rect
618{
619 [_session_view setNeedsDisplayInRemoteRect:rect];
620}
621
622- (void)session:(RDPSession *)session didSetRemoteCursor:(RDPCursor *)cursor
623{
624 (void)session;
625 [_session_view setRemoteCursor:cursor];
626
627 if (!_has_user_moved_cursor &&
628 (!_has_cursor_view_position || CGPointEqualToPoint(_cursor_view_position, CGPointZero)))
629 {
630 _has_cursor_view_position = NO;
631 (void)[self currentCursorViewPosition];
632 }
633}
634
635- (void)session:(RDPSession *)session didMoveRemoteCursor:(CGPoint)position
636{
637 (void)session;
638 if (_mouse_pan_active || _long_press_active)
639 return;
640 CGPoint viewPosition = [self sessionViewPositionForRemotePosition:position];
641 if (!_has_user_moved_cursor && CGPointEqualToPoint(position, CGPointZero) &&
642 _has_cursor_view_position && !CGPointEqualToPoint(_cursor_view_position, CGPointZero))
643 return;
644
645 _cursor_view_position = viewPosition;
646 _has_cursor_view_position = YES;
647 [_session_view setRemoteCursorPosition:viewPosition];
648}
649
650- (void)sessionDidHideRemoteCursor:(RDPSession *)session
651{
652 (void)session;
653 [_session_view hideRemoteCursor];
654}
655
656- (void)sessionDidSetDefaultRemoteCursor:(RDPSession *)session
657{
658 (void)session;
659 [_session_view setDefaultRemoteCursor];
660}
661
662- (void)session:(RDPSession *)session didChangeRemoteClipboardText:(NSString *)text
663{
664 (void)session;
665 UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
666 [pasteboard setString:text];
667
668 // don't announce the server's own text back to it
669 _pasteboard_change_count = [pasteboard changeCount];
670}
671
672- (void)session:(RDPSession *)session requestsClipboardTextWithParams:(NSMutableDictionary *)params
673{
674 (void)session;
675 NSString *text = [[UIPasteboard generalPasteboard] string];
676 if (text)
677 [params setObject:text forKey:@"text"];
678}
679
680- (void)session:(RDPSession *)session requestsAuthenticationWithParams:(NSMutableDictionary *)params
681{
682 // custom view --> stock UIAlertController
683 __block UIAlertController *alert = [UIAlertController
684 alertControllerWithTitle:NSLocalizedString(@"Credentials", @"Credentials title")
685 message:NSLocalizedString(@"Please provide the missing user information.",
686 @"Credentials input view message")
687 preferredStyle:UIAlertControllerStyleAlert];
688
689 // username input field
690 [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
691 [textField
692 setPlaceholder:NSLocalizedString(@"Username", @"Credentials Input Username hint")];
693 [textField setText:[params valueForKey:@"username"]];
694 [textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
695 [textField setAutocorrectionType:UITextAutocorrectionTypeNo];
696 }];
697
698 // password input field
699 [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
700 [textField
701 setPlaceholder:NSLocalizedString(@"Password", @"Credentials Input Password hint")];
702 [textField setText:[params valueForKey:@"password"]];
703 [textField setSecureTextEntry:YES];
704 }];
705
706 // domain input field
707 [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
708 [textField setPlaceholder:NSLocalizedString(@"Domain", @"Credentials Input Domain hint")];
709 [textField setText:[params valueForKey:@"domain"]];
710 [textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
711 [textField setAutocorrectionType:UITextAutocorrectionTypeNo];
712 }];
713
714 // cancel btn
715 UIAlertAction *cancelAction =
716 [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel Button")
717 style:UIAlertActionStyleCancel
718 handler:^(UIAlertAction *action) {
719 [params setValue:[NSNumber numberWithBool:NO] forKey:@"result"];
720 [[session uiRequestCompleted] signal];
721 }];
722 [alert addAction:cancelAction];
723
724 // login btn
725 UIAlertAction *loginAction = [UIAlertAction
726 actionWithTitle:NSLocalizedString(@"Login", @"Login Button")
727 style:UIAlertActionStyleDefault
728 handler:^(UIAlertAction *action) {
729 NSArray *fields = [alert textFields];
730 [params setValue:[[fields objectAtIndex:0] text] forKey:@"username"];
731 [params setValue:[[fields objectAtIndex:1] text] forKey:@"password"];
732 [params setValue:[[fields objectAtIndex:2] text] forKey:@"domain"];
733 [params setValue:[NSNumber numberWithBool:YES] forKey:@"result"];
734 [[session uiRequestCompleted] signal];
735 }];
736 [alert addAction:loginAction];
737
738 [alert setPreferredAction:loginAction];
739
740 [self presentViewController:alert animated:YES completion:nil];
741}
742
743- (void)session:(RDPSession *)session verifyCertificateWithParams:(NSMutableDictionary *)params
744{
745 NSString *message = [NSString
746 stringWithFormat:@"%@\n\n%@ %@",
747 NSLocalizedString(@"The identity of the remote computer cannot be "
748 @"verified. Do you want to connect anyway?",
749 @"Verify certificate view message"),
750 NSLocalizedString(@"Issuer:", @"Verify certificate view issuer label"),
751 [params valueForKey:@"issuer"]];
752 UIAlertController *alert =
753 [UIAlertController alertControllerWithTitle:nil
754 message:message
755 preferredStyle:UIAlertControllerStyleAlert];
756
757 [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"No", @"No Button")
758 style:UIAlertActionStyleCancel
759 handler:^(UIAlertAction *action) {
760 [params setValue:[NSNumber numberWithBool:NO]
761 forKey:@"result"];
762 [[session uiRequestCompleted] signal];
763 }]];
764
765 [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Yes", @"Yes Button")
766 style:UIAlertActionStyleDefault
767 handler:^(UIAlertAction *action) {
768 [params setValue:[NSNumber numberWithBool:YES]
769 forKey:@"result"];
770 [[session uiRequestCompleted] signal];
771 }]];
772
773 [self presentViewController:alert animated:YES completion:nil];
774}
775
776- (CGSize)sizeForFitScreenForSession:(RDPSession *)session
777{
778 // set remote resolution that matches the on-screen viewport.
779 CGSize size = [self sessionViewportFrame].size;
780 // not the main screen: the scene can move between displays (iphone duo, external display)
781 UIScreen *screen = [[[[self view] window] windowScene] screen];
782 CGFloat scale = screen ? [screen nativeScale] : [[self traitCollection] displayScale];
783 if (scale <= 0.0f)
784 scale = 1.0f;
785
786 // 'Automatic (75%/50%)': a smaller remote desktop drawn scaled up, so its text looks larger
787 scale *= FitScreenScale([[session params] intForKey:@"screen_resolution_type"]);
788
789 size.width = ceilf(size.width * scale);
790 size.height = ceilf(size.height * scale);
791
792 CGFloat maxDimension = MAX(size.width, size.height);
793 if (maxDimension > 4096.0f)
794 {
795 CGFloat downscale = 4096.0f / maxDimension;
796 size.width = floorf(size.width * downscale);
797 size.height = floorf(size.height * downscale);
798 }
799
800 size.width = (UINT32)MAX(200.0f, size.width) & ~1u;
801 size.height = (UINT32)MAX(200.0f, size.height) & ~1u;
802
803 return size;
804}
805
806#pragma mark - Keyboard Toolbar Handlers
807
808- (void)showAdvancedKeyboardAnimated
809{
810 // already advanced keyboard activated
811 if (_advanced_keyboard_view)
812 return;
813
814 CGRect rect = CGRectMake(0, 0, [[self view] bounds].size.width, [self advancedKeyboardHeight]);
815 _advanced_keyboard_view = [[AdvancedKeyboardView alloc] initWithFrame:rect delegate:self];
816
817 [_dummy_textfield setInputView:_advanced_keyboard_view];
818 [_dummy_textfield reloadInputViews];
819 [_keyboard_toolbar setExtendedKeyboardActive:YES];
820}
821
822- (void)destroyAdvancedKeyboard
823{
824 // advanced keyboard not activated
825 if (!_advanced_keyboard_view)
826 return;
827
828 [_dummy_textfield setInputView:nil];
829 [_advanced_keyboard_view autorelease];
830 _advanced_keyboard_view = nil;
831 [_keyboard_toolbar setExtendedKeyboardActive:NO];
832}
833
834// toggle advanced keyboard (not keyboard)
835- (IBAction)toggleKeyboardWhenOtherVisible:(id)sender
836{
837 if (!_advanced_keyboard_view)
838 {
839 // show advanced keyboard
840 [self showAdvancedKeyboardAnimated];
841 }
842 else
843 {
844 // close advanced keyboard
845 [self destroyAdvancedKeyboard];
846 [_dummy_textfield reloadInputViews];
847 }
848}
849
850- (IBAction)toggleWinKey:(id)sender
851{
852 [[RDPKeyboard getSharedRDPKeyboard] toggleWinKey];
853}
854
855- (IBAction)toggleShiftKey:(id)sender
856{
857 [[RDPKeyboard getSharedRDPKeyboard] toggleShiftKey];
858}
859
860- (IBAction)toggleCtrlKey:(id)sender
861{
862 [[RDPKeyboard getSharedRDPKeyboard] toggleCtrlKey];
863}
864
865- (IBAction)toggleAltKey:(id)sender
866{
867 [[RDPKeyboard getSharedRDPKeyboard] toggleAltKey];
868}
869
870- (IBAction)toggleAltGrKey:(id)sender
871{
872 [[RDPKeyboard getSharedRDPKeyboard] toggleAltGrKey];
873}
874
875- (IBAction)pressEscKey:(id)sender
876{
877 [self commitTextInput];
878 [[RDPKeyboard getSharedRDPKeyboard] sendEscapeKeyStroke];
879}
880
881- (IBAction)pressDeleteKey:(id)sender
882{
883 [self commitTextInput];
884 [[RDPKeyboard getSharedRDPKeyboard] sendDeleteKeyStroke];
885}
886
887- (IBAction)pressTabKey:(id)sender
888{
889 [self commitTextInput];
890 [[RDPKeyboard getSharedRDPKeyboard] sendTabKeyStroke];
891}
892
893#pragma mark -
894#pragma mark event handlers
895
896- (IBAction)switchSession:(id)sender
897{
898 [self suspendSession];
899}
900
901- (IBAction)toggleKeyboard:(id)sender
902{
903 if (![self isKeyboardActive])
904 [_dummy_textfield becomeFirstResponder];
905 else
906 [_dummy_textfield resignFirstResponder];
907}
908
909- (IBAction)disconnectSession:(id)sender
910{
911 [_session disconnect];
912}
913
914- (IBAction)cancelButtonPressed:(id)sender
915{
916 [_session disconnect];
917}
918
919#pragma mark -
920#pragma mark iOS Keyboard Notification Handlers
921
922- (void)keyboardWillShow:(NSNotification *)notification
923{
924 // remember the system keyboard's height (to show advanced keyboard view)
925 if (!_advanced_keyboard_view)
926 {
927 CGRect frame =
928 [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
929 CGFloat height = frame.size.height - [_keyboard_toolbar bounds].size.height;
930
931 // 100.0 is heuristic value.
932 if (height >= 100.0)
933 {
934 if ([self isLandscape])
935 _keyboard_height_landscape = height;
936 else
937 _keyboard_height_portrait = height;
938 }
939 }
940
941 [self centerSessionViewInViewport];
942
943 // get covered area (keyboard)
944 CGRect keyboardFrame =
945 [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
946 keyboardFrame = [[self view] convertRect:keyboardFrame fromView:nil];
947
948 CGRect coveredArea = CGRectIntersection([_session_scrollview frame], keyboardFrame);
949
950 [self setKeyboardOverlap:CGRectGetHeight(coveredArea)];
951}
952
953- (void)keyboardWillHide:(NSNotification *)notification
954{
955 (void)notification;
956 [self centerSessionViewInViewport];
957 [self setKeyboardOverlap:0.0];
958}
959
960- (void)keyboardDidHide:(NSNotification *)notification
961{
962 // release adanced keyboard view
963 if (![self isKeyboardActive])
964 [self destroyAdvancedKeyboard];
965
966 // resume capturing the hardware keyboard once the on-screen keyboard is gone
967 if (![self isKeyboardActive] && [_session_view hardwareKeyboardActive])
968 [_session_view becomeFirstResponder];
969}
970
971- (void)hardwareKeyboardChanged:(NSNotification *)notification
972{
973 BOOL connected = (GCKeyboard.coalescedKeyboard != nil);
974 [_session_view setHardwareKeyboardActive:connected];
975
976 if (connected && ![self isKeyboardActive])
977 [_session_view becomeFirstResponder];
978 else if (!connected)
979 [_session_view resignFirstResponder];
980}
981
982- (void)localClipboardChanged:(NSNotification *)notification
983{
984 // hasStrings does not show the paste permission alert, unlike reading the string
985 UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
986 if ([pasteboard changeCount] == _pasteboard_change_count)
987 return;
988
989 _pasteboard_change_count = [pasteboard changeCount];
990 [_session sendClipboardHasText:[pasteboard hasStrings]];
991}
992
993- (void)applicationDidEnterBackground:(NSNotification *)notification
994{
995 // keeps the connection alive for a short visit to another app
996 // after a longer one the session will reconnect
997 [self endBackgroundTask];
998 _background_task =
999 [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
1000 [self endBackgroundTask];
1001 }];
1002
1003 // ios lays the window out in other orientations for the app switcher snapshots
1004 [self cancelRemoteResize];
1005}
1006
1007- (void)applicationWillEnterForeground:(NSNotification *)notification
1008{
1009 [self endBackgroundTask];
1010
1011 // the device may have been rotated while the app was in the background
1012 [self scheduleRemoteResize];
1013}
1014
1015#pragma mark -
1016#pragma mark Gesture handlers
1017
1018- (void)handleSingleTap:(UITapGestureRecognizer *)gesture
1019{
1020 if (_pointer_is_indirect)
1021 [self moveCursorToSessionViewPosition:[gesture locationInView:_session_view]];
1022 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(YES)];
1023 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(NO)];
1024}
1025
1026- (void)handleSecondaryTap:(UITapGestureRecognizer *)gesture
1027{
1028 [self moveCursorToSessionViewPosition:[gesture locationInView:_session_view]];
1029 [self sendMouseButtonEvent:GetRightMouseButtonClickEvent(YES)];
1030 [self sendMouseButtonEvent:GetRightMouseButtonClickEvent(NO)];
1031}
1032
1033- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture
1034{
1035 if ([gesture state] == UIGestureRecognizerStateBegan)
1036 {
1037 _long_press_active = YES;
1038 _mouse_drag_active = NO;
1039 }
1040 else if ([gesture state] == UIGestureRecognizerStateEnded ||
1041 [gesture state] == UIGestureRecognizerStateCancelled ||
1042 [gesture state] == UIGestureRecognizerStateFailed)
1043 {
1044 if (_mouse_drag_active)
1045 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(NO)];
1046 else if ([gesture state] == UIGestureRecognizerStateEnded)
1047 {
1048 [self sendMouseButtonEvent:GetRightMouseButtonClickEvent(YES)];
1049 [self sendMouseButtonEvent:GetRightMouseButtonClickEvent(NO)];
1050 }
1051
1052 _mouse_drag_active = NO;
1053 _long_press_active = NO;
1054 }
1055}
1056
1057- (void)handleMousePan:(UIPanGestureRecognizer *)gesture
1058{
1059 // A mouse/trackpad drag holds a button down, so move the cursor absolutely and
1060 // keep the left button pressed for the duration of the drag.
1061 if (_pointer_is_indirect)
1062 {
1063 [self moveCursorToSessionViewPosition:[gesture locationInView:_session_view]];
1064
1065 if ([gesture state] == UIGestureRecognizerStateBegan)
1066 {
1067 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(YES)];
1068 _mouse_drag_active = YES;
1069 }
1070 else if ([gesture state] == UIGestureRecognizerStateEnded ||
1071 [gesture state] == UIGestureRecognizerStateCancelled ||
1072 [gesture state] == UIGestureRecognizerStateFailed)
1073 {
1074 if (_mouse_drag_active)
1075 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(NO)];
1076 _mouse_drag_active = NO;
1077 }
1078 return;
1079 }
1080
1081 CGPoint location = [gesture locationInView:_session_scrollview];
1082
1083 if ([gesture state] == UIGestureRecognizerStateBegan)
1084 {
1085 _mouse_pan_active = YES;
1086 _last_mouse_pan_location = location;
1087 if (_long_press_active && !_mouse_drag_active)
1088 {
1089 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(YES)];
1090 _mouse_drag_active = YES;
1091 }
1092 }
1093 else if ([gesture state] == UIGestureRecognizerStateChanged)
1094 {
1095 if (_long_press_active && !_mouse_drag_active)
1096 {
1097 [self sendMouseButtonEvent:GetLeftMouseButtonClickEvent(YES)];
1098 _mouse_drag_active = YES;
1099 }
1100
1101 CGPoint delta = CGPointMake(location.x - _last_mouse_pan_location.x,
1102 location.y - _last_mouse_pan_location.y);
1103 [self moveCursorByViewportDelta:delta];
1104 _last_mouse_pan_location = location;
1105 }
1106 else if ([gesture state] == UIGestureRecognizerStateEnded ||
1107 [gesture state] == UIGestureRecognizerStateCancelled ||
1108 [gesture state] == UIGestureRecognizerStateFailed)
1109 {
1110 _mouse_pan_active = NO;
1111 }
1112}
1113
1114- (void)handleHover:(UIHoverGestureRecognizer *)gesture
1115{
1116 if ([gesture state] != UIGestureRecognizerStateBegan &&
1117 [gesture state] != UIGestureRecognizerStateChanged)
1118 return;
1119
1120 [self moveCursorToSessionViewPosition:[gesture locationInView:_session_view]];
1121}
1122
1123- (void)handleDoubleLongPress:(UILongPressGestureRecognizer *)gesture
1124{
1125 // this point is mapped against the scroll view because we want to have relative movement to the
1126 // screen/scrollview
1127 CGPoint pos = [gesture locationInView:_session_scrollview];
1128 CGPoint session_view_pos = [self currentCursorViewPosition];
1129
1130 if ([gesture state] == UIGestureRecognizerStateBegan)
1131 _prev_long_press_position = pos;
1132 else if ([gesture state] == UIGestureRecognizerStateChanged)
1133 {
1134 int delta = _prev_long_press_position.y - pos.y;
1135
1136 if (delta > GetScrollGestureDelta())
1137 {
1138 [_session sendInputEvent:[self eventDescriptorForMouseEvent:GetMouseWheelEvent(YES)
1139 position:session_view_pos]];
1140 _prev_long_press_position = pos;
1141 }
1142 else if (delta < -GetScrollGestureDelta())
1143 {
1144 [_session sendInputEvent:[self eventDescriptorForMouseEvent:GetMouseWheelEvent(NO)
1145 position:session_view_pos]];
1146 _prev_long_press_position = pos;
1147 }
1148 }
1149}
1150
1151- (void)handleScroll:(UIPanGestureRecognizer *)gesture
1152{
1153 CGFloat delta = [gesture translationInView:_session_view].y;
1154 if (fabs(delta) < GetScrollGestureDelta())
1155 return;
1156
1157 CGPoint position = [self currentCursorViewPosition];
1158 [_session sendInputEvent:[self eventDescriptorForMouseEvent:GetMouseWheelEvent(delta > 0)
1159 position:position]];
1160 [gesture setTranslation:CGPointZero inView:_session_view];
1161}
1162
1163- (void)handleSingle3FingersTap:(UITapGestureRecognizer *)gesture
1164{
1165 [_session setToolbarVisible:![_session toolbarVisible]];
1166 [self showSessionToolbar:[_session toolbarVisible]];
1167}
1168
1169- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction
1170 styleForRegion:(UIPointerRegion *)region
1171{
1172 return [UIPointerStyle hiddenPointerStyle];
1173}
1174
1175- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
1176 shouldReceiveTouch:(UITouch *)touch
1177{
1178 // the scroll recognizer only handles pointer scroll events, never touches
1179 if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] &&
1180 [(UIPanGestureRecognizer *)gestureRecognizer allowedScrollTypesMask] != 0)
1181 return NO;
1182
1183 _pointer_is_indirect = ([touch type] == UITouchTypeIndirectPointer);
1184
1185 // the long press maps to a right-click / drag for touch input, which a connected
1186 // mouse handles through its own buttons instead
1187 if (_pointer_is_indirect &&
1188 [gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
1189 return NO;
1190
1191 return YES;
1192}
1193
1194- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
1195 shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
1196{
1197 BOOL panAndHold =
1198 ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] &&
1199 [otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) ||
1200 ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]] &&
1201 [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]);
1202 return panAndHold;
1203}
1204
1205@end
1206
1207@implementation RDPSessionViewController (Private)
1208
1209#pragma mark -
1210#pragma mark Helper functions
1211
1212- (void)showConnectingViewWithText:(NSString *)text
1213{
1214 [self hideConnectingView];
1215
1216 // load connecting view
1217 [[NSBundle mainBundle] loadNibNamed:@"RDPConnectingView" owner:self options:nil];
1218
1219 // set strings
1220 [_lbl_connecting setText:text];
1221 [_cancel_connect_button setTitle:NSLocalizedString(@"Cancel", @"Cancel Button")
1222 forState:UIControlStateNormal];
1223
1224 // center view and give it round corners
1225 [_connecting_view setCenter:[[self view] center]];
1226 [[_connecting_view layer] setCornerRadius:10];
1227
1228 // display connecting view and start indicator
1229 [[self view] addSubview:_connecting_view];
1230 [_connecting_indicator_view startAnimating];
1231}
1232
1233- (void)hideConnectingView
1234{
1235 if (!_connecting_view)
1236 return;
1237
1238 // remove and release connecting view
1239 [_connecting_indicator_view stopAnimating];
1240 [_connecting_view removeFromSuperview];
1241 [_connecting_view autorelease];
1242 _connecting_view = nil;
1243}
1244
1245- (void)endBackgroundTask
1246{
1247 if (_background_task == UIBackgroundTaskInvalid)
1248 return;
1249
1250 [[UIApplication sharedApplication] endBackgroundTask:_background_task];
1251 _background_task = UIBackgroundTaskInvalid;
1252}
1253
1254- (void)scheduleRemoteResize
1255{
1256 // a fixed resolution bookmark keeps its remote size
1257 if (!IsFitScreenOption([[_session params] intForKey:@"screen_resolution_type"]))
1258 return;
1259
1260 // wait until the size settles, e.g. while a window is dragged or the device unfolds
1261 [self cancelRemoteResize];
1262 [self performSelector:@selector(sendRemoteResize) withObject:nil afterDelay:0.5];
1263}
1264
1265- (void)cancelRemoteResize
1266{
1267 [NSObject cancelPreviousPerformRequestsWithTarget:self
1268 selector:@selector(sendRemoteResize)
1269 object:nil];
1270}
1271
1272- (void)sendRemoteResize
1273{
1274 UIWindowScene *scene = [[[self view] window] windowScene];
1275 if (!scene || [scene activationState] == UISceneActivationStateBackground)
1276 return;
1277
1278 CGSize size = [self sizeForFitScreenForSession:_session];
1279
1280 // check pending resize (server will resize soon)
1281 CGSize current = _requested_remote_size;
1282 if (CGSizeEqualToSize(current, CGSizeZero))
1283 {
1284 // no pending
1285 rdpSettings *settings = [_session getSessionParams];
1286 current = CGSizeMake(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth),
1287 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight));
1288 }
1289
1290 // ignore same size
1291 if (CGSizeEqualToSize(size, current))
1292 return;
1293
1294 _requested_remote_size = size;
1295 [_session sendMonitorLayoutWithSize:size];
1296}
1297
1298- (CGRect)sessionViewportFrame
1299{
1300 // use full screen (ipad or 'Avoid Screen Edges' disabled)
1301 if (IsPad() || ![[NSUserDefaults standardUserDefaults] boolForKey:@"ui.avoid_screen_edges"])
1302 return [[self view] bounds];
1303
1304 // if 'Avoid Screen Edges' enabled (only for iphone)
1305 UIEdgeInsets insets = [[self view] safeAreaInsets];
1306 CGRect bounds = [[self view] bounds];
1307
1308 // landscape or iphone duo --> fill the home indicator area
1309 if ([self hasHinge] || bounds.size.width > bounds.size.height)
1310 insets.bottom = 0.0f;
1311
1312 // opened iphone duo --> set gap at right side band
1313 if ([self isHingeOpen] && insets.right > insets.left)
1314 insets.left = insets.right;
1315
1316 return UIEdgeInsetsInsetRect(bounds, insets);
1317}
1318
1319- (void)installHingeInteraction
1320{
1321#if defined(__IPHONE_27_1) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_27_1)
1322 if (@available(iOS 27.1, *))
1323 {
1324 __block RDPSessionViewController *weakSelf = self;
1325 UIHingeInteraction *interaction = [[UIHingeInteraction alloc]
1326 initWithUpdateHandler:^(UIHingeInteraction *hingeInteraction,
1327 UIHingeInteractionUpdate *update) {
1328 (void)hingeInteraction;
1329 UIHinge *hinge = [update hinge];
1330
1331 // this device is not iphone duo
1332 if (!hinge)
1333 return;
1334
1335 weakSelf->_has_hinge = YES;
1336
1337 UIHingeStatus hingeStatus = [hinge status];
1338 BOOL open = (hingeStatus == UIHingeStatusPartiallyOpen ||
1339 hingeStatus == UIHingeStatusFullyOpen);
1340 if (weakSelf->_hinge_open == open)
1341 return;
1342
1343 weakSelf->_hinge_open = open;
1344 [[weakSelf view] setNeedsLayout];
1345 }];
1346
1347 [[self view] addInteraction:interaction];
1348 [interaction release];
1349 }
1350#endif
1351}
1352
1353// return YES (iphone duo)
1354// return NO (other devices)
1355- (BOOL)hasHinge
1356{
1357 return _has_hinge;
1358}
1359
1360- (BOOL)isHingeOpen
1361{
1362 return _hinge_open;
1363}
1364
1365- (void)fitSessionViewToViewport
1366{
1367 CGSize viewportSize = [_session_scrollview bounds].size;
1368 CGSize remoteSize = [_session_view bounds].size;
1369 if (viewportSize.width <= 0.0f || viewportSize.height <= 0.0f || remoteSize.width <= 0.0f ||
1370 remoteSize.height <= 0.0f)
1371 return;
1372
1373 CGFloat fitScale =
1374 MIN(viewportSize.width / remoteSize.width, viewportSize.height / remoteSize.height);
1375 [_session_scrollview setMinimumZoomScale:fitScale];
1376 [_session_scrollview setMaximumZoomScale:MAX(2.0f, fitScale)];
1377 [_session_scrollview setZoomScale:fitScale animated:NO];
1378 [_session_scrollview setContentOffset:CGPointZero animated:NO];
1379 _last_session_viewport_size = viewportSize;
1380 [self centerSessionViewInViewport];
1381}
1382
1383- (void)centerSessionViewInViewport
1384{
1385 CGSize viewportSize = [_session_scrollview bounds].size;
1386 CGRect sessionFrame = [_session_view frame];
1387 if (viewportSize.width <= 0.0f || viewportSize.height <= 0.0f ||
1388 sessionFrame.size.width <= 0.0f || sessionFrame.size.height <= 0.0f)
1389 return;
1390
1391 sessionFrame.origin.x = MAX((viewportSize.width - sessionFrame.size.width) * 0.5f, 0.0f);
1392 sessionFrame.origin.y = MAX((viewportSize.height - sessionFrame.size.height) * 0.5f, 0.0f);
1393 [_session_view setFrame:sessionFrame];
1394
1395 [_session_scrollview
1396 setContentSize:CGSizeMake(MAX(viewportSize.width, sessionFrame.size.width),
1397 MAX(viewportSize.height, sessionFrame.size.height))];
1398}
1399
1400- (void)setKeyboardOverlap:(CGFloat)overlap
1401{
1402 // extend the scrollable area to push up using 2 finger
1403 UIEdgeInsets inset = [_session_scrollview contentInset];
1404 inset.bottom = overlap;
1405 [_session_scrollview setContentInset:inset];
1406
1407 CGPoint offset = [_session_scrollview contentOffset];
1408 CGFloat viewportHeight = [_session_scrollview bounds].size.height;
1409
1410 // cursor is usually located in typing area
1411 if (overlap > 0.0 && _has_cursor_view_position)
1412 {
1413 CGPoint cursor = [_session_scrollview convertPoint:_cursor_view_position
1414 fromView:_session_view];
1415 CGFloat visibleBottom = offset.y + viewportHeight - overlap;
1416 CGFloat hiddenHeight = cursor.y + KEYBOARD_CURSOR_MARGIN - visibleBottom;
1417 if (hiddenHeight > 0.0)
1418 offset.y += hiddenHeight;
1419 }
1420
1421 // stay within the scrollable range or scrolls back once the keyboard hides
1422 CGFloat maxOffsetY = [_session_scrollview contentSize].height + overlap - viewportHeight;
1423 offset.y = MAX(MIN(offset.y, maxOffsetY), 0.0);
1424 [_session_scrollview setContentOffset:offset animated:YES];
1425}
1426
1427- (void)showSessionToolbar:(BOOL)show
1428{
1429 // already shown or hidden?
1430 if (_session_toolbar_visible == show)
1431 return;
1432
1433 // Offset by the safe-area insets so the toolbar/buttons are not hidden behind
1434 // the status bar / notch / Dynamic Island on modern devices (and side notch
1435 // in landscape).
1436 UIEdgeInsets safe = [[self view] safeAreaInsets];
1437 // devices without a notch (e.g. iPad) have no top inset once the status bar is hidden,
1438 // so keep at least the system margin to the top edge
1439 safe.top = MAX(safe.top, [self systemMinimumLayoutMargins].leading);
1440 CGFloat toolbarWidth = [[self view] bounds].size.width - safe.left - safe.right;
1441
1442 if (show)
1443 {
1444 [UIView animateWithDuration:0.4
1445 delay:0.0
1446 options:UIViewAnimationOptionCurveLinear
1447 animations:^{
1448 [_session_toolbar setFrame:CGRectMake(safe.left, safe.top,
1449 toolbarWidth, TOOLBAR_HEIGHT)];
1450 }
1451 completion:nil];
1452 _session_toolbar_visible = YES;
1453 }
1454 else
1455 {
1456 [UIView animateWithDuration:0.4
1457 delay:0.0
1458 options:UIViewAnimationOptionCurveLinear
1459 animations:^{
1460 [_session_toolbar setFrame:CGRectMake(safe.left, -TOOLBAR_HEIGHT,
1461 toolbarWidth, TOOLBAR_HEIGHT)];
1462 }
1463 completion:nil];
1464 _session_toolbar_visible = NO;
1465 }
1466}
1467
1468- (void)initGestureRecognizers
1469{
1470 // single tap recognizer. A double-click is just two quick taps, which the server
1471 // coalesces on its own, so we avoid the latency of waiting for a double-tap to fail.
1472 UITapGestureRecognizer *singleTapRecognizer =
1473 [[[UITapGestureRecognizer alloc] initWithTarget:self
1474 action:@selector(handleSingleTap:)] autorelease];
1475 [singleTapRecognizer setNumberOfTouchesRequired:1];
1476 [singleTapRecognizer setNumberOfTapsRequired:1];
1477 [singleTapRecognizer setDelegate:self];
1478
1479 // long press gesture recognizer
1480 UILongPressGestureRecognizer *longPressRecognizer = [[[UILongPressGestureRecognizer alloc]
1481 initWithTarget:self
1482 action:@selector(handleLongPress:)] autorelease];
1483 [longPressRecognizer setMinimumPressDuration:0.3];
1484 [longPressRecognizer setAllowableMovement:12.0];
1485 [longPressRecognizer setDelegate:self];
1486
1487 // One-finger movement behaves like a trackpad and moves the remote cursor relatively.
1488 UIPanGestureRecognizer *mousePanRecognizer =
1489 [[[UIPanGestureRecognizer alloc] initWithTarget:self
1490 action:@selector(handleMousePan:)] autorelease];
1491 [mousePanRecognizer setMinimumNumberOfTouches:1];
1492 [mousePanRecognizer setMaximumNumberOfTouches:1];
1493 [mousePanRecognizer setDelegate:self];
1494
1495 // A connected mouse/trackpad moves the remote cursor absolutely while hovering.
1496 UIHoverGestureRecognizer *hoverRecognizer =
1497 [[[UIHoverGestureRecognizer alloc] initWithTarget:self
1498 action:@selector(handleHover:)] autorelease];
1499 [hoverRecognizer setDelegate:self];
1500
1501 // Secondary mouse/trackpad button maps to a right-click. Standard tap recognizers
1502 // only track the primary button, so this needs its own recognizer.
1503 UITapGestureRecognizer *secondaryTapRecognizer = [[[UITapGestureRecognizer alloc]
1504 initWithTarget:self
1505 action:@selector(handleSecondaryTap:)] autorelease];
1506 [secondaryTapRecognizer setButtonMaskRequired:UIEventButtonMaskSecondary];
1507 [secondaryTapRecognizer setAllowedTouchTypes:@[@(UITouchTypeIndirectPointer)]];
1508 [secondaryTapRecognizer setDelegate:self];
1509
1510 // Mouse wheel and trackpad scrolling are forwarded as remote wheel events. Setting a
1511 // scroll type mask lets this pan recognizer receive pointer scroll device events.
1512 UIPanGestureRecognizer *scrollRecognizer =
1513 [[[UIPanGestureRecognizer alloc] initWithTarget:self
1514 action:@selector(handleScroll:)] autorelease];
1515 [scrollRecognizer setAllowedScrollTypesMask:UIScrollTypeMaskAll];
1516 [scrollRecognizer setDelegate:self];
1517
1518 // double long press gesture recognizer
1519 UILongPressGestureRecognizer *doubleLongPressRecognizer = [[[UILongPressGestureRecognizer alloc]
1520 initWithTarget:self
1521 action:@selector(handleDoubleLongPress:)] autorelease];
1522 [doubleLongPressRecognizer setNumberOfTouchesRequired:2];
1523 [doubleLongPressRecognizer setMinimumPressDuration:0.3];
1524
1525 // 3 finger, single tap gesture for showing/hiding the toolbar
1526 UITapGestureRecognizer *single3FingersTapRecognizer = [[[UITapGestureRecognizer alloc]
1527 initWithTarget:self
1528 action:@selector(handleSingle3FingersTap:)] autorelease];
1529 [single3FingersTapRecognizer setNumberOfTapsRequired:1];
1530 [single3FingersTapRecognizer setNumberOfTouchesRequired:3];
1531 [singleTapRecognizer requireGestureRecognizerToFail:longPressRecognizer];
1532
1533 // Reserve one finger for the mouse; two fingers still pan/zoom the viewport.
1534 [[_session_scrollview panGestureRecognizer] setMinimumNumberOfTouches:2];
1535
1536 // add gestures to scroll view
1537 [_session_scrollview addGestureRecognizer:singleTapRecognizer];
1538 [_session_scrollview addGestureRecognizer:longPressRecognizer];
1539 [_session_scrollview addGestureRecognizer:mousePanRecognizer];
1540 [_session_scrollview addGestureRecognizer:hoverRecognizer];
1541 [_session_scrollview addGestureRecognizer:secondaryTapRecognizer];
1542 [_session_scrollview addGestureRecognizer:scrollRecognizer];
1543 [_session_scrollview addGestureRecognizer:doubleLongPressRecognizer];
1544 [_session_scrollview addGestureRecognizer:single3FingersTapRecognizer];
1545
1546 // Hide the system pointer over the session so only the remote cursor is visible.
1547 UIPointerInteraction *pointerInteraction =
1548 [[[UIPointerInteraction alloc] initWithDelegate:self] autorelease];
1549 [_session_view addInteraction:pointerInteraction];
1550}
1551
1552- (void)suspendSession
1553{
1554 // suspend session and pop navigation controller
1555 [_session suspend];
1556
1557 // pop current view controller
1558 [[self navigationController] popViewControllerAnimated:YES];
1559}
1560
1561- (NSDictionary *)eventDescriptorForMouseEvent:(int)event position:(CGPoint)position
1562{
1563 CGPoint remote_position = [self remotePositionForSessionViewPosition:position];
1564 return [NSDictionary
1565 dictionaryWithObjectsAndKeys:@"mouse", @"type", [NSNumber numberWithUnsignedShort:event],
1566 @"flags",
1567 [NSNumber numberWithUnsignedShort:lrintf(remote_position.x)],
1568 @"coord_x",
1569 [NSNumber numberWithUnsignedShort:lrintf(remote_position.y)],
1570 @"coord_y", nil];
1571}
1572
1573- (CGPoint)remotePositionForSessionViewPosition:(CGPoint)position
1574{
1575 rdpSettings *settings = [_session getSessionParams];
1576 CGSize viewSize = [_session_view bounds].size;
1577 CGFloat desktopWidth =
1578 settings ? freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) : 0;
1579 CGFloat desktopHeight =
1580 settings ? freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) : 0;
1581
1582 if ((viewSize.width > 0.0f) && (desktopWidth > 0.0f))
1583 position.x = position.x * desktopWidth / viewSize.width;
1584 if ((viewSize.height > 0.0f) && (desktopHeight > 0.0f))
1585 position.y = position.y * desktopHeight / viewSize.height;
1586
1587 if (desktopWidth > 0.0f)
1588 position.x = MIN(MAX(position.x, 0.0f), desktopWidth - 1.0f);
1589 if (desktopHeight > 0.0f)
1590 position.y = MIN(MAX(position.y, 0.0f), desktopHeight - 1.0f);
1591
1592 return position;
1593}
1594
1595- (CGPoint)sessionViewPositionForRemotePosition:(CGPoint)position
1596{
1597 rdpSettings *settings = [_session getSessionParams];
1598 CGSize viewSize = [_session_view bounds].size;
1599 CGFloat desktopWidth =
1600 settings ? freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) : 0;
1601 CGFloat desktopHeight =
1602 settings ? freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) : 0;
1603
1604 if ((desktopWidth > 0.0f) && (viewSize.width > 0.0f))
1605 position.x = position.x * viewSize.width / desktopWidth;
1606 if ((desktopHeight > 0.0f) && (viewSize.height > 0.0f))
1607 position.y = position.y * viewSize.height / desktopHeight;
1608
1609 return [self clampedSessionViewCursorPosition:position];
1610}
1611
1612- (CGPoint)clampedSessionViewCursorPosition:(CGPoint)position
1613{
1614 CGSize viewSize = [_session_view bounds].size;
1615 if (viewSize.width > 0.0f)
1616 position.x = MIN(MAX(position.x, 0.0f), viewSize.width - 1.0f);
1617 if (viewSize.height > 0.0f)
1618 position.y = MIN(MAX(position.y, 0.0f), viewSize.height - 1.0f);
1619 return position;
1620}
1621
1622- (CGPoint)currentCursorViewPosition
1623{
1624 if (!_has_cursor_view_position)
1625 {
1626 CGSize viewSize = [_session_view bounds].size;
1627 _cursor_view_position = CGPointMake(MAX(viewSize.width - 1.0, 0.0) * 0.5,
1628 MAX(viewSize.height - 1.0, 0.0) * 0.5);
1629 _has_cursor_view_position = YES;
1630 [_session_view setRemoteCursorPosition:_cursor_view_position];
1631 }
1632 [_session_view showRemoteCursor];
1633
1634 return _cursor_view_position;
1635}
1636
1637- (void)moveCursorByViewportDelta:(CGPoint)delta
1638{
1639 CGPoint position = [self currentCursorViewPosition];
1640 CGFloat zoomScale = [_session_scrollview zoomScale];
1641 if (zoomScale <= 0.0)
1642 zoomScale = 1.0;
1643
1644 position.x += delta.x / zoomScale;
1645 position.y += delta.y / zoomScale;
1646 position = [self clampedSessionViewCursorPosition:position];
1647 _cursor_view_position = position;
1648 _has_cursor_view_position = YES;
1649 _has_user_moved_cursor = YES;
1650
1651 // Local prediction keeps the cursor responsive while the RDP event is in flight.
1652 [_session_view setRemoteCursorPosition:position];
1653 [self handleMouseMoveForPosition:position];
1654}
1655
1656- (void)moveCursorToSessionViewPosition:(CGPoint)position
1657{
1658 position = [self clampedSessionViewCursorPosition:position];
1659 _cursor_view_position = position;
1660 _has_cursor_view_position = YES;
1661 _has_user_moved_cursor = YES;
1662
1663 // Local prediction keeps the cursor responsive while the RDP event is in flight.
1664 [_session_view setRemoteCursorPosition:position];
1665 [_session_view showRemoteCursor];
1666 [self handleMouseMoveForPosition:position];
1667}
1668
1669- (void)sendMouseButtonEvent:(int)event
1670{
1671 // typed text can not be changed anymore.
1672 [self commitTextInput];
1673 CGPoint position = [self currentCursorViewPosition];
1674 [_session sendInputEvent:[self eventDescriptorForMouseEvent:event position:position]];
1675}
1676
1677- (void)handleMouseMoveForPosition:(CGPoint)position
1678{
1679 [_session sendInputEvent:[self eventDescriptorForMouseEvent:PTR_FLAGS_MOVE position:position]];
1680}
1681
1682- (BOOL)isKeyboardActive
1683{
1684 return [_dummy_textfield isFirstResponder];
1685}
1686
1687- (void)resetTextInput
1688{
1689 [_dummy_textfield setText:@""];
1690 [_sent_text release];
1691 _sent_text = [@"" retain];
1692}
1693
1694- (void)commitTextInput
1695{
1696 if ([[_dummy_textfield text] length] == 0)
1697 return;
1698
1699 // send the text being composed as it is
1700 [_dummy_textfield unmarkText];
1701 [self textInputChanged:_dummy_textfield];
1702 [self resetTextInput];
1703}
1704
1705- (BOOL)isLandscape
1706{
1707 CGSize size = [[self view] bounds].size;
1708 return size.width > size.height;
1709}
1710
1711- (CGFloat)advancedKeyboardHeight
1712{
1713 // before the system keyboard was shown in this orientation, use a typical height
1714 if ([self isLandscape])
1715 return (_keyboard_height_landscape > 0.0) ? _keyboard_height_landscape
1716 : (IsPad() ? 400.0 : 200.0);
1717 return (_keyboard_height_portrait > 0.0) ? _keyboard_height_portrait
1718 : (IsPad() ? 320.0 : 290.0);
1719}
1720
1721@end
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.