iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IGraphicsIOS_view.mm
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11#if !__has_feature(objc_arc)
12#error This file must be compiled with Arc. Use -fobjc-arc flag
13#endif
14
15#import <QuartzCore/QuartzCore.h>
16#import <Metal/Metal.h>
17#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
18
19#import "IGraphicsIOS_view.h"
20
21#include "IGraphicsCoreText.h"
22#include "IControl.h"
23#include "IPlugParameter.h"
24
25extern StaticStorage<CoreTextFontDescriptor> sFontDescriptorCache;
26
27@implementation IGRAPHICS_UITABLEVC
28
29- (int) menuIndexFromIndexPath: (NSIndexPath*) indexPath
30{
31 return [self.items[indexPath.row][1] intValue];
32}
33
34- (void) viewDidLoad
35{
36 [super viewDidLoad];
37 self.tableView = [[UITableView alloc] initWithFrame:self.view.frame];
38 self.tableView.dataSource = self;
39 self.tableView.delegate = self;
40 self.tableView.scrollEnabled = YES;
41 self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
42 self.items = [[NSMutableArray alloc] init];
43
44 int numItems = mMenu->NItems();
45
46 NSMutableString* elementTitle;
47
48 for (int i = 0; i < numItems; ++i)
49 {
50 IPopupMenu::Item* pMenuItem = mMenu->GetItem(i);
51
52 elementTitle = [[NSMutableString alloc] initWithUTF8String: pMenuItem->GetText()];
53
54 if (mMenu->GetPrefix())
55 {
56 NSString* prefixString = nil;
57
58 switch (mMenu->GetPrefix())
59 {
60 case 1: prefixString = [NSString stringWithFormat:@"%1d: ", i+1]; break;
61 case 2: prefixString = [NSString stringWithFormat:@"%02d: ", i+1]; break;
62 case 3: prefixString = [NSString stringWithFormat:@"%03d: ", i+1]; break;
63 case 0:
64 default:
65 prefixString = [NSString stringWithUTF8String:""]; break;
66 }
67
68 [elementTitle insertString:prefixString atIndex:0];
69 }
70
71 [self.items addObject: @[elementTitle, [NSNumber numberWithInt:i]]];
72 }
73
74 [self.view addSubview:self.tableView];
75}
76
77- (id) initWithIPopupMenuAndIGraphics: (IPopupMenu*) pMenu : (IGraphicsIOS*) pGraphics
78{
79 self = [super init];
80
81 mGraphics = pGraphics;
82 mMenu = pMenu;
83
84 return self;
85}
86
87- (NSInteger) tableView: (UITableView*) tableView numberOfRowsInSection : (NSInteger) section
88{
89 return self.items.count;
90}
91
92- (NSInteger) numberOfSectionsInTableView: (UITableView*) tableView
93{
94 return 1;
95}
96
97- (UITableViewCell*) tableView: (UITableView*) tableView cellForRowAtIndexPath: (NSIndexPath*) indexPath
98{
99 static NSString *identifer = @"cell";
100 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
101
102 if (cell == nil)
103 {
104 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
105 }
106
107 cell.textLabel.text = [NSString stringWithFormat:@"%@", self.items[indexPath.row][0]];
108
109 IPopupMenu::Item* pItem = mMenu->GetItem([self menuIndexFromIndexPath:indexPath]);
110
111 if (pItem->GetChecked())
112 cell.accessoryType = UITableViewCellAccessoryCheckmark;
113 else
114 cell.accessoryType = pItem->GetSubmenu() ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
115
116 cell.textLabel.enabled = cell.userInteractionEnabled = pItem->GetEnabled();
117
118 return cell;
119}
120
121- (CGFloat) tableView:(UITableView*) tableView heightForRowAtIndexPath: (NSIndexPath*) indexPath
122{
123
124 IPopupMenu::Item* pItem = mMenu->GetItem([self menuIndexFromIndexPath:indexPath]);
125
126 if (pItem->GetIsSeparator())
127 return 0.5;
128 else
129 return self.tableView.rowHeight;
130}
131
132- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
133{
134 IPopupMenu::Item* pItem = mMenu->GetItem([self menuIndexFromIndexPath:indexPath]);
135
136 if (pItem->GetIsSeparator())
137 return 0.5;
138 else
139 return self.tableView.rowHeight;
140}
141
142- (void) tableView:(UITableView*) tableView didSelectRowAtIndexPath:(NSIndexPath*) indexPath
143{
144 int menuIdx = [self menuIndexFromIndexPath:indexPath];
145
146 IPopupMenu::Item* pItem = mMenu->GetItem(menuIdx);
147 IPopupMenu* pSubMenu = pItem->GetSubmenu();
148
149 if (pSubMenu)
150 {
151 IGRAPHICS_UITABLEVC* newViewController = [[IGRAPHICS_UITABLEVC alloc] initWithIPopupMenuAndIGraphics: pSubMenu : mGraphics];
152 [newViewController setTitle:[NSString stringWithUTF8String:CStringHasContents(pSubMenu->GetRootTitle()) ? pSubMenu->GetRootTitle() : pItem->GetText()]];
153 [self.navigationController pushViewController:newViewController animated:YES];
154
155 return;
156 }
157
158 if (pItem->GetIsChoosable())
159 {
160 [self dismissViewControllerAnimated:YES completion:nil];
161
162 mMenu->SetChosenItemIdx(menuIdx);
163
164 if (mMenu->GetFunction())
165 mMenu->ExecFunction();
166
167 mGraphics->SetControlValueAfterPopupMenu(mMenu);
168 }
169}
170
171- (CGSize) preferredContentSize
172{
173 if (self.presentingViewController && self.tableView != nil)
174 {
175 CGSize tempSize = self.presentingViewController.view.bounds.size;
176 tempSize.width = 300;
177 CGSize size = [self.tableView sizeThatFits:tempSize];
178 return size;
179 } else {
180 return [super preferredContentSize];
181 }
182}
183
184- (void) setPreferredContentSize:(CGSize)preferredContentSize
185{
186 super.preferredContentSize = preferredContentSize;
187}
188
189- (void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editingStyle forRowAtIndexPath: (NSIndexPath*) indexPath
190{
191 if (editingStyle == UITableViewCellEditingStyleDelete)
192 {
193 mGraphics->DeleteFromPopupMenu(mMenu, [self menuIndexFromIndexPath:indexPath]);
194 [self.items removeObjectAtIndex:indexPath.row];
195 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
196 }
197}
198
199- (BOOL) tableView: (UITableView *) tableView canEditRowAtIndexPath: (NSIndexPath*) indexPath
200{
201 return mMenu->GetItem([self menuIndexFromIndexPath:indexPath])->GetIsDeletable();
202}
203
204@end
205
206#ifdef IGRAPHICS_ACCESSKIT
207IGraphicsAccessibilityIOS::IGraphicsAccessibilityIOS(IGraphics& graphics, UIView* pView)
208: IGraphicsAccessibility(graphics)
209{
210 mAdapter = accesskit_ios_adapter_new((__bridge void*) pView, ActivationHandler, this, ActionHandler, this, DeactivationHandler, this);
211}
212
213IGraphicsAccessibilityIOS::~IGraphicsAccessibilityIOS()
214{
215 accesskit_ios_adapter_free(mAdapter);
216}
217
218void IGraphicsAccessibilityIOS::DeactivationHandler(void* pUserData)
219{
220 // The adapter has dropped its tree, so it needs all of it again if assistive technology is turned back on
221 static_cast<IGraphicsAccessibilityIOS*>(pUserData)->SetInactive();
222}
223
224void IGraphicsAccessibilityIOS::UpdateIfActive(accesskit_tree_update_factory factory, void* pUserData)
225{
226 if (accesskit_ios_queued_events* pEvents = accesskit_ios_adapter_update_if_active(mAdapter, factory, pUserData))
227 accesskit_ios_queued_events_raise(pEvents);
228}
229
230void IGraphicsAccessibilityIOS::ViewDidAppear()
231{
232 if (accesskit_ios_queued_events* pEvents = accesskit_ios_adapter_view_did_appear(mAdapter))
233 accesskit_ios_queued_events_raise(pEvents);
234}
235
236bool IGraphicsAccessibilityIOS::IsAccessibilityElement()
237{
238 return accesskit_ios_adapter_is_accessibility_element(mAdapter);
239}
240
241NSArray* IGraphicsAccessibilityIOS::GetElements()
242{
243 return (__bridge NSArray*) accesskit_ios_adapter_accessibility_elements(mAdapter);
244}
245
246id IGraphicsAccessibilityIOS::HitTest(CGPoint point)
247{
248 return (__bridge id) accesskit_ios_adapter_hit_test(mAdapter, point.x, point.y);
249}
250#endif
251
252@implementation IGRAPHICS_VIEW
253
254- (id) initWithIGraphics: (IGraphicsIOS*) pGraphics
255{
256 TRACE
257
258 mGraphics = pGraphics;
259 CGRect r = CGRectMake(0.f, 0.f, (float) pGraphics->WindowWidth(), (float) pGraphics->WindowHeight());
260 self = [super initWithFrame:r];
261
262 #if TARGET_OS_VISION
263 CGFloat scale = 2.0;
264 #else
265 CGFloat scale = [UIScreen mainScreen].scale;
266 #endif
267
268 self.layer.frame = self.frame;
269 self.layer.opaque = YES;
270 self.layer.contentsScale = scale;
271 self.contentScaleFactor = scale;
272
273 CAMetalLayer* mtlLayer = (CAMetalLayer*) self.layer;
274 mtlLayer.framebufferOnly = YES;
275 mtlLayer.device = MTLCreateSystemDefaultDevice();
276
277#if defined IGRAPHICS_GL
278 EGLDisplay display = eglGetPlatformDisplay(EGLenum(EGL_PLATFORM_ANGLE_ANGLE), 0, 0);
279
280 if (!display) {
281 DBGMSG("eglGetPlatformDisplay() returned error %i", eglGetError());
282 }
283
284 if (eglInitialize(display, nil, nil) == 0) {
285 DBGMSG("eglInitialize() returned error %i", eglGetError());
286 }
287
288 const EGLint configAttribs[9] = {
289 EGL_BLUE_SIZE, 8,
290 EGL_GREEN_SIZE, 8,
291 EGL_RED_SIZE, 8,
292 EGL_DEPTH_SIZE, 24,
293 EGL_NONE};
294 EGLint numConfigs = 0;
295 EGLConfig configs[1];
296
297 if (eglChooseConfig(display, configAttribs, configs, 1, &numConfigs) == 0) {
298 DBGMSG("eglChooseConfig() returned error %i", eglGetError());
299 }
300
301 if (!configs[0]) {
302 DBGMSG("Empty config returned in eglChooseConfig()");
303 }
304
305#if defined IGRAPHICS_GLES2
306 const EGLint contextAttribs [5] = {
307 EGL_CONTEXT_MAJOR_VERSION, 2,
308 EGL_CONTEXT_MINOR_VERSION, 0,
309 EGL_NONE,
310 };
311#elif defined IGRAPHICS_GLES3
312 const EGLint contextAttribs [5] = {
313 EGL_CONTEXT_MAJOR_VERSION, 3,
314 EGL_CONTEXT_MINOR_VERSION, 0,
315 EGL_NONE,
316 };
317#endif
318
319 EGLContext context = eglCreateContext(display, configs[0], nullptr, contextAttribs);
320
321 if (!context) {
322 DBGMSG("eglCreateContext() returned error %d", eglGetError());
323 }
324
325 EGLSurface surface = eglCreateWindowSurface(display, configs[0], (__bridge EGLNativeWindowType) [self layer], nullptr);
326
327 if (!surface) {
328 DBGMSG("eglCreateWindowSurface() returned error %d", eglGetError());
329 }
330
331 mEGLSurface = surface;
332 mEGLDisplay = display;
333 mEGLContext = context;
334#endif
335
336 self.multipleTouchEnabled = NO;
337
338 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackgroundNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];
339 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];
340 mColorPickerHandlerFunc = nullptr;
341
342 UIHoverGestureRecognizer* hoverGestureRecognizer =
343 [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(onHoverGesture:)];
344 [self addGestureRecognizer: hoverGestureRecognizer];
345
346 return self;
347}
348
349- (void) setFrame:(CGRect) frame
350{
351 [super setFrame:frame];
352
353#if TARGET_OS_VISION
354 CGFloat scale = 2.0;
355#else
356 CGFloat scale = [UIScreen mainScreen].scale;
357 if (self.window) {
358 scale = self.window.screen.scale;
359 }
360#endif
361
362 [CATransaction begin];
363 [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
364 [self.layer setFrame:frame];
365
366 // CAMetalLayer is correct for both Metal and GLES - ANGLE uses Metal backend on iOS
367 CAMetalLayer* mtlLayer = (CAMetalLayer*) self.layer;
368 CGSize drawableSize = self.bounds.size;
369 drawableSize.width *= scale;
370 drawableSize.height *= scale;
371 mtlLayer.drawableSize = drawableSize;
372
373 [CATransaction commit];
374}
375
376- (void) onTouchEvent:(ETouchEvent) eventType withTouches:(NSSet*) touches withEvent:(UIEvent*) event
377{
378 if(mGraphics == nullptr) //TODO: why?
379 return;
380
381 NSEnumerator* pEnumerator = [[event allTouches] objectEnumerator];
382 UITouch* pTouch;
383
384 std::vector<IMouseInfo> points;
385
386 while ((pTouch = [pEnumerator nextObject]))
387 {
388 CGPoint pos = [pTouch locationInView:pTouch.view];
389
390 IMouseInfo point;
391
392 auto ds = mGraphics->GetDrawScale();
393
394 point.ms.L = true;
395 point.ms.touchID = reinterpret_cast<ITouchID>(pTouch);
396 point.ms.touchRadius = [pTouch majorRadius];
397
398 point.x = pos.x / ds;
399 point.y = pos.y / ds;
400 CGPoint posPrev = [pTouch previousLocationInView: self];
401 point.dX = (pos.x - posPrev.x) / ds;
402 point.dY = (pos.y - posPrev.y) / ds;
403
404 if([touches containsObject:pTouch])
405 {
406 mPrevX = point.x;
407 mPrevY = point.y;
408 points.push_back(point);
409 }
410 }
411
412// DBGMSG("%lu\n", points[0].ms.idx);
413
414 if(eventType == ETouchEvent::Began)
415 mGraphics->OnMouseDown(points);
416
417 if(eventType == ETouchEvent::Moved)
418 mGraphics->OnMouseDrag(points);
419
420 if(eventType == ETouchEvent::Ended)
421 mGraphics->OnMouseUp(points);
422
423 if(eventType == ETouchEvent::Cancelled)
424 mGraphics->OnTouchCancelled(points);
425}
426
427- (void) touchesBegan:(NSSet*) touches withEvent:(UIEvent*) event
428{
429 [self onTouchEvent:ETouchEvent::Began withTouches:touches withEvent:event];
430}
431
432- (void) touchesMoved:(NSSet*) touches withEvent:(UIEvent*) event
433{
434 [self onTouchEvent:ETouchEvent::Moved withTouches:touches withEvent:event];
435}
436
437- (void) touchesEnded:(NSSet*) touches withEvent:(UIEvent*) event
438{
439 [self onTouchEvent:ETouchEvent::Ended withTouches:touches withEvent:event];
440}
441
442- (void) touchesCancelled:(NSSet*) touches withEvent:(UIEvent*) event
443{
444 [self onTouchEvent:ETouchEvent::Cancelled withTouches:touches withEvent:event];
445}
446
447+ (Class) layerClass
448{
449 return CAMetalLayer.class;
450}
451
452- (void) didMoveToSuperview
453{
454 [super didMoveToSuperview];
455 if (self.superview)
456 {
457 self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(redraw:)];
458 [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
459 self.displayLink.preferredFramesPerSecond = mGraphics->FPS();
460 }
461 else
462 {
463 [self.displayLink invalidate];
464 self.displayLink = nil;
465 }
466}
467
468#ifdef IGRAPHICS_ACCESSKIT
469- (void) didMoveToWindow
470{
471 [super didMoveToWindow];
472
473 if (self.window && mAccessibility)
474 mAccessibility->ViewDidAppear();
475}
476
477// UIKit asks the view for its accessibility elements, which are made by the AccessKit adapter from the IGraphics controls
478- (BOOL) isAccessibilityElement
479{
480 return mAccessibility ? mAccessibility->IsAccessibilityElement() : NO;
481}
482
483- (NSArray*) accessibilityElements
484{
485 return mAccessibility ? mAccessibility->GetElements() : nil;
486}
487
488- (id) accessibilityHitTest:(CGPoint) point
489{
490 return mAccessibility ? mAccessibility->HitTest(point) : nil;
491}
492#endif
493
494- (void) drawRect:(CGRect)rect
495{
496 IRECTList rects;
497
498 if(mGraphics)
499 {
500 mGraphics->SetPlatformContext(UIGraphicsGetCurrentContext());
501 IGraphics::ScopedGLContext scopedGLContext{mGraphics};
502
503 if (mGraphics->IsDirty(rects))
504 {
505 mGraphics->SetAllControlsClean();
506 mGraphics->Draw(rects);
507 }
508 [self swapBuffers];
509 }
510}
511
512- (void) redraw:(CADisplayLink*) displayLink
513{
514#ifdef IGRAPHICS_CPU
515 [self setNeedsDisplay];
516#else
517 [self drawRect:CGRect()];
518#endif
519}
520
521- (BOOL) isOpaque
522{
523 return YES;
524}
525
526- (BOOL) acceptsFirstResponder
527{
528 return YES;
529}
530
531- (BOOL) canBecomeFirstResponder
532{
533 return YES;
534}
535
536- (void) removeFromSuperview
537{
538 [self.displayLink invalidate];
539 self.displayLink = nil;
540 mTextField = nil;
541 mGraphics = nil;
542#ifdef IGRAPHICS_ACCESSKIT
543 mAccessibility = nullptr;
544#endif
545 mMenuTableController = nil;
546 mMenuNavigationController = nil;
547
548#if defined IGRAPHICS_GL
549 if (mEGLDisplay != EGL_NO_DISPLAY)
550 {
551 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
552 if (mEGLSurface != EGL_NO_SURFACE)
553 eglDestroySurface(mEGLDisplay, mEGLSurface);
554 if (mEGLContext != EGL_NO_CONTEXT)
555 eglDestroyContext(mEGLDisplay, mEGLContext);
556 eglTerminate(mEGLDisplay);
557 }
558 mEGLDisplay = EGL_NO_DISPLAY;
559 mEGLSurface = EGL_NO_SURFACE;
560 mEGLContext = EGL_NO_CONTEXT;
561#endif
562}
563
564- (BOOL) textFieldShouldReturn:(UITextField*) textField
565{
566 if (textField == mTextField)
567 {
568 mGraphics->SetControlValueAfterTextEdit([[mTextField text] UTF8String]);
569 mGraphics->SetAllControlsDirty();
570
571 [self endUserInput];
572 }
573 return YES;
574}
575
576- (BOOL) textField:(UITextField*) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*) string
577{
578 if (!string.length)
579 return YES;
580
581 // verify max length has not been exceeded
582 NSString* proposedText = [mTextField.text stringByReplacingCharactersInRange:range withString:string];
583
584 if (proposedText.length > mTextFieldLength)
585 return NO;
586
587 IControl* pInTextEntry = mGraphics->GetControlInTextEntry();
588
589 if(pInTextEntry)
590 {
591 const IParam* pParam = pInTextEntry->GetParam();
592
593 if (pParam)
594 {
595 NSMutableCharacterSet *characterSet = [[NSMutableCharacterSet alloc] init];
596
597 switch ( pParam->Type() )
598 {
599 case IParam::kTypeEnum:
600 case IParam::kTypeInt:
601 case IParam::kTypeBool:
602 [characterSet addCharactersInString:@"0123456789-+"];
603 break;
604 case IParam::kTypeDouble:
605 [characterSet addCharactersInString:@"0123456789.-+"];
606 break;
607 default:
608 break;
609 }
610
611 if ([string rangeOfCharacterFromSet:characterSet.invertedSet].location != NSNotFound)
612 return NO;
613 }
614 }
615
616 return YES;
617}
618
619- (UIModalPresentationStyle) adaptivePresentationStyleForPresentationController:(UIPresentationController*) controller
620{
621 return UIModalPresentationNone;
622}
623
624- (BOOL) presentationControllerShouldDismiss:(UIPopoverPresentationController*) popoverPresentationController
625{
626 return YES;
627}
628
629- (IPopupMenu*) createPopupMenu: (IPopupMenu&) menu : (CGRect) bounds;
630{
631 mMenuTableController = [[IGRAPHICS_UITABLEVC alloc] initWithIPopupMenuAndIGraphics:&menu : mGraphics];
632 [mMenuTableController setTitle: [NSString stringWithUTF8String:menu.GetRootTitle()]];
633
634 mMenuNavigationController = [[UINavigationController alloc] initWithRootViewController:mMenuTableController];
635
636 mMenuNavigationController.modalPresentationStyle = UIModalPresentationPopover;
637 mMenuNavigationController.popoverPresentationController.sourceView = self;
638 mMenuNavigationController.popoverPresentationController.sourceRect = bounds;
639// mMenuNavigationController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
640 mMenuNavigationController.popoverPresentationController.delegate = self;
641
642 [self.window.rootViewController presentViewController:mMenuNavigationController animated:YES completion:nil];
643
644 return nullptr;
645}
646
647- (void) createTextEntry: (int) paramIdx : (const IText&) text : (const char*) str : (int) length : (CGRect) areaRect
648{
649 if (mTextField)
650 return;
651
652 mAlertController = [UIAlertController alertControllerWithTitle:@"Input a value:" message:@"" preferredStyle:UIAlertControllerStyleAlert];
653
654 __weak IGRAPHICS_VIEW* weakSelf = self;
655
656 void (^cancelHandler)(UIAlertAction*) = ^(UIAlertAction *action)
657 {
658 __strong IGRAPHICS_VIEW* strongSelf = weakSelf;
659 strongSelf->mGraphics->SetAllControlsDirty();
660 [strongSelf endUserInput];
661 };
662
663 UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:cancelHandler];
664 [mAlertController addAction:cancelAction];
665
666 void (^okHandler)(UIAlertAction*) = ^(UIAlertAction *action)
667 {
668 __strong IGRAPHICS_VIEW* strongSelf = weakSelf;
669 strongSelf->mGraphics->SetControlValueAfterTextEdit([[strongSelf->mTextField text] UTF8String]);
670 strongSelf->mGraphics->SetAllControlsDirty();
671 [strongSelf endUserInput];
672 };
673
674 UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:okHandler];
675 [mAlertController addAction:okAction];
676 [mAlertController setPreferredAction:okAction];
677
678 [mAlertController addTextFieldWithConfigurationHandler:^(UITextField* aTextField) {
679 __strong IGRAPHICS_VIEW* strongSelf = weakSelf;
680 strongSelf->mTextField = aTextField;
681 strongSelf->mTextFieldLength = length;
682 aTextField.delegate = strongSelf;
683 [aTextField setText:[NSString stringWithUTF8String:str]];
684 }];
685 [self.window.rootViewController presentViewController:mAlertController animated:YES completion:nil];
686}
687
688- (void) endUserInput
689{
690 [self becomeFirstResponder];
691 [self.window.rootViewController dismissViewControllerAnimated:NO completion:nil];
692 [mTextField setDelegate: nil];
693 mAlertController = nullptr;
694 mTextField = nullptr;
695 mGraphics->ClearInTextEntryControl();
696}
697
698- (void) showMessageBox: (const char*) str : (const char*) title : (EMsgBoxType) type : (IMsgBoxCompletionHandlerFunc) completionHandler
699{
700 [self endUserInput];
701
702 NSString* message = [NSString stringWithUTF8String:str];
703 NSString* titleNs = [NSString stringWithUTF8String:title];
704
705 UIAlertController* alertController = [UIAlertController alertControllerWithTitle:titleNs message:message preferredStyle:UIAlertControllerStyleAlert];
706
707 void (^handlerBlock)(UIAlertAction*) =
708 ^(UIAlertAction* action) {
709
710 if (completionHandler != nullptr)
711 {
712 EMsgBoxResult result = EMsgBoxResult::kCANCEL;
713
714 if ([action.title isEqualToString:@"OK"])
715 result = EMsgBoxResult::kOK;
716 if ([action.title isEqualToString:@"Cancel"])
717 result = EMsgBoxResult::kCANCEL;
718 if ([action.title isEqualToString:@"Yes"])
719 result = EMsgBoxResult::kYES;
720 if ([action.title isEqualToString:@"No"])
721 result = EMsgBoxResult::kNO;
722 if ([action.title isEqualToString:@"Retry"])
723 result = EMsgBoxResult::kRETRY;
724
725 completionHandler(result);
726 }
727
728 };
729
730 if (type == kMB_OK || type == kMB_OKCANCEL)
731 {
732 UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:handlerBlock];
733 [alertController addAction:okAction];
734 }
735
736 if (type == kMB_YESNO || type == kMB_YESNOCANCEL)
737 {
738 UIAlertAction* yesAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:handlerBlock];
739 [alertController addAction:yesAction];
740
741 UIAlertAction* noAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:handlerBlock];
742 [alertController addAction:noAction];
743 }
744
745 if (type == kMB_RETRYCANCEL)
746 {
747 UIAlertAction* retryAction = [UIAlertAction actionWithTitle:@"Retry" style:UIAlertActionStyleDefault handler:handlerBlock];
748 [alertController addAction:retryAction];
749 }
750
751 if (type == kMB_OKCANCEL || type == kMB_YESNOCANCEL || type == kMB_RETRYCANCEL)
752 {
753 UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:handlerBlock];
754 [alertController addAction:cancelAction];
755 }
756
757 [[NSOperationQueue mainQueue] addOperationWithBlock:^{
758 [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
759 }];
760}
761
762- (void) promptForFile: (NSString*) fileName : (NSString*) path : (EFileAction) action : (NSArray*) contentTypes : (IFileDialogCompletionHandlerFunc) completionHandler
763{
764 [self endUserInput];
765
766 mFileDialogFunc = completionHandler;
767
768 UIDocumentPickerViewController* vc = NULL;
769 NSURL* url = [[NSURL alloc] initFileURLWithPath:path];
770
771 if (action == EFileAction::Open)
772 {
773 vc = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:contentTypes asCopy:YES];
774 [vc setDirectoryURL:url];
775 }
776 else
777 {
778 vc = [[UIDocumentPickerViewController alloc] initForExportingURLs:@[url]];
779 }
780
781 [vc setDelegate:self];
782
783 [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
784}
785
786- (void) promptForDirectory: (NSString*) path : (IFileDialogCompletionHandlerFunc) completionHandler
787{
788 [self endUserInput];
789
790 mFileDialogFunc = completionHandler;
791
792 UIDocumentPickerViewController* vc = NULL;
793 NSURL* url = [[NSURL alloc] initFileURLWithPath:path];
794
795 NSMutableArray* pFileTypes = [[NSMutableArray alloc] init];
796 UTType* directoryType = [UTType typeWithIdentifier:@"public.folder"];
797 [pFileTypes addObject:directoryType];
798
799 vc = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:pFileTypes];
800 [vc setDirectoryURL:url];
801
802 [vc setDelegate:self];
803
804 [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
805}
806
807- (BOOL) promptForColor: (IColor&) color : (const char*) str : (IColorPickerHandlerFunc) func
808{
809 [self endUserInput];
810
811 UIColorPickerViewController* colorSelectionController = [[UIColorPickerViewController alloc] init];
812
813 colorSelectionController.modalPresentationStyle = UIModalPresentationPopover;
814 colorSelectionController.popoverPresentationController.delegate = self;
815 colorSelectionController.popoverPresentationController.sourceView = self;
816
817 float x, y;
818 mGraphics->GetMouseLocation(x, y);
819 colorSelectionController.popoverPresentationController.sourceRect = CGRectMake(x, y, 1, 1);
820
821 colorSelectionController.delegate = self;
822 colorSelectionController.selectedColor = ToUIColor(color);
823 colorSelectionController.supportsAlpha = YES;
824
825 mColorPickerHandlerFunc = func;
826
827 [self.window.rootViewController presentViewController:colorSelectionController animated:YES completion:nil];
828
829 return false;
830}
831
832- (void) attachGestureRecognizer: (EGestureType) type
833{
834 UIGestureRecognizer* gestureRecognizer;
835
836 switch (type)
837 {
838 case EGestureType::DoubleTap:
839 case EGestureType::TripleTap:
840 {
841 gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapGesture:)];
842 [(UITapGestureRecognizer*) gestureRecognizer setNumberOfTapsRequired: type == EGestureType::DoubleTap ? 2 : 3];
843 [(UITapGestureRecognizer*) gestureRecognizer setNumberOfTouchesRequired:1];
844 break;
845 }
846 case EGestureType::LongPress1:
847 case EGestureType::LongPress2:
848 {
849 gestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressGesture:)];
850 [(UILongPressGestureRecognizer*) gestureRecognizer setNumberOfTouchesRequired: type == EGestureType::LongPress1 ? 1 : 2];
851 break;
852 }
853 case EGestureType::SwipeLeft:
854 {
855 gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipeGesture:)];
856 [(UISwipeGestureRecognizer*) gestureRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft];
857 break;
858 }
859 case EGestureType::SwipeRight:
860 {
861 gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipeGesture:)];
862 [(UISwipeGestureRecognizer*) gestureRecognizer setDirection:UISwipeGestureRecognizerDirectionRight];
863 break;
864 }
865 case EGestureType::SwipeUp:
866 {
867 gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipeGesture:)];
868 [(UISwipeGestureRecognizer*) gestureRecognizer setDirection:UISwipeGestureRecognizerDirectionUp];
869 break;
870 }
871 case EGestureType::SwipeDown:
872 {
873 gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipeGesture:)];
874 [(UISwipeGestureRecognizer*) gestureRecognizer setDirection:UISwipeGestureRecognizerDirectionDown];
875 break;
876 }
877 case EGestureType::Pinch:
878 {
879 gestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(onPinchGesture:)];
880 break;
881 }
882 case EGestureType::Rotate:
883 {
884 gestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(onRotateGesture:)];
885 break;
886 }
887 default:
888 return;
889 }
890
891 gestureRecognizer.delegate = self;
892 gestureRecognizer.cancelsTouchesInView = YES;
893 gestureRecognizer.delaysTouchesBegan = YES;
894 [self addGestureRecognizer:gestureRecognizer];
895}
896
897- (void) onTapGesture: (UITapGestureRecognizer*) recognizer
898{
899 CGPoint p = [recognizer locationInView:self];
900 auto ds = mGraphics->GetDrawScale();
901 IGestureInfo info;
902 info.x = p.x / ds;
903 info.y = p.y / ds;
904 info.type = recognizer.numberOfTapsRequired == 2 ? EGestureType::DoubleTap : EGestureType::TripleTap;
905
906 mGraphics->OnGestureRecognized(info);
907}
908
909- (void) onLongPressGesture: (UILongPressGestureRecognizer*) recognizer
910{
911 CGPoint p = [recognizer locationInView:self];
912 auto ds = mGraphics->GetDrawScale();
913 IGestureInfo info;
914 info.x = p.x / ds;
915 info.y = p.y / ds;
916 if(recognizer.state == UIGestureRecognizerStateBegan)
917 info.state = EGestureState::Began;
918 else if(recognizer.state == UIGestureRecognizerStateChanged)
919 info.state = EGestureState::InProcess;
920 else if(recognizer.state == UIGestureRecognizerStateEnded)
921 info.state = EGestureState::Ended;
922
923 info.type = recognizer.numberOfTouchesRequired == 1 ? EGestureType::LongPress1 : EGestureType::LongPress2;
924
925 mGraphics->OnGestureRecognized(info);
926}
927
928- (void) onSwipeGesture: (UISwipeGestureRecognizer*) recognizer
929{
930 CGPoint p = [recognizer locationInView:self];
931 auto ds = mGraphics->GetDrawScale();
932 IGestureInfo info;
933 info.x = p.x / ds;
934 info.y = p.y / ds;
935
936 switch (recognizer.direction) {
937 case UISwipeGestureRecognizerDirectionLeft: info.type = EGestureType::SwipeLeft; break;
938 case UISwipeGestureRecognizerDirectionRight: info.type = EGestureType::SwipeRight; break;
939 case UISwipeGestureRecognizerDirectionUp: info.type = EGestureType::SwipeUp; break;
940 case UISwipeGestureRecognizerDirectionDown: info.type = EGestureType::SwipeDown; break;
941 default:
942 break;
943 }
944
945 mGraphics->OnGestureRecognized(info);
946}
947
948- (void) onPinchGesture: (UIPinchGestureRecognizer*) recognizer
949{
950 CGPoint p = [recognizer locationInView:self];
951 auto ds = mGraphics->GetDrawScale();
952 IGestureInfo info;
953 info.x = p.x / ds;
954 info.y = p.y / ds;
955 info.velocity = recognizer.velocity;
956 info.scale = recognizer.scale;
957
958 if(recognizer.state == UIGestureRecognizerStateBegan)
959 info.state = EGestureState::Began;
960 else if(recognizer.state == UIGestureRecognizerStateChanged)
961 info.state = EGestureState::InProcess;
962 else if(recognizer.state == UIGestureRecognizerStateEnded)
963 info.state = EGestureState::Ended;
964
965 info.type = EGestureType::Pinch;
966
967 mGraphics->OnGestureRecognized(info);
968}
969
970- (void) onRotateGesture: (UIRotationGestureRecognizer*) recognizer
971{
972 CGPoint p = [recognizer locationInView:self];
973 auto ds = mGraphics->GetDrawScale();
974 IGestureInfo info;
975 info.x = p.x / ds;
976 info.y = p.y / ds;
977 info.velocity = recognizer.velocity;
978 info.angle = RadToDeg(recognizer.rotation);
979
980 if(recognizer.state == UIGestureRecognizerStateBegan)
981 info.state = EGestureState::Began;
982 else if(recognizer.state == UIGestureRecognizerStateChanged)
983 info.state = EGestureState::InProcess;
984 else if(recognizer.state == UIGestureRecognizerStateEnded)
985 info.state = EGestureState::Ended;
986
987 info.type = EGestureType::Rotate;
988
989 mGraphics->OnGestureRecognized(info);
990}
991
992- (void) onHoverGesture: (UIHoverGestureRecognizer*) recognizer
993{
994 CGPoint pos = [recognizer locationInView:self];
995
996 IMouseInfo info;
997
998 auto ds = mGraphics->GetDrawScale();
999 info.x = pos.x / ds;
1000 info.y = pos.y / ds;
1001
1002 if (mGraphics)
1003 mGraphics->OnMouseOver(info.x, info.y, info.ms);
1004}
1005
1006-(BOOL) gestureRecognizer:(UIGestureRecognizer*) gestureRecognizer shouldReceiveTouch:(UITouch*) touch
1007{
1008 CGPoint pos = [touch locationInView:touch.view];
1009
1010 if (mGraphics)
1011 {
1012 auto ds = mGraphics->GetDrawScale();
1013
1014 if (mGraphics->RespondsToGesture(pos.x / ds, pos.y / ds))
1015 {
1016 return TRUE;
1017 }
1018 }
1019
1020 return FALSE;
1021}
1022
1023- (void) applicationDidEnterBackgroundNotification:(NSNotification*) notification
1024{
1025 [self.displayLink setPaused:YES];
1026}
1027
1028- (void) applicationWillEnterForegroundNotification:(NSNotification*) notification
1029{
1030 [self.displayLink setPaused:NO];
1031}
1032
1033- (BOOL) delaysContentTouches
1034{
1035 return NO;
1036}
1037
1038- (void) presentationControllerDidDismiss: (UIPresentationController*) presentationController
1039{
1040 mGraphics->SetControlValueAfterPopupMenu(nullptr);
1041}
1042
1043- (void) documentPicker:(UIDocumentPickerViewController*) controller didPickDocumentsAtURLs:(NSArray <NSURL*>*) urls
1044{
1045 WDL_String fileName, path;
1046
1047 if (urls.count == 1)
1048 {
1049 NSURL* pSource = urls[0];
1050 NSString* pFullPath = [pSource path];
1051 fileName.Set([pFullPath UTF8String]);
1052
1053 NSString* pTruncatedPath = [pFullPath stringByDeletingLastPathComponent];
1054
1055 if (pTruncatedPath)
1056 {
1057 path.Set([pTruncatedPath UTF8String]);
1058 path.Append("/");
1059 }
1060
1061 if (mFileDialogFunc)
1062 mFileDialogFunc(fileName, path);
1063 }
1064 else
1065 {
1066 // call with empty values
1067 if (mFileDialogFunc)
1068 mFileDialogFunc(fileName, path);
1069 }
1070}
1071
1072- (void) documentPickerWasCancelled:(UIDocumentPickerViewController*) controller
1073{
1074 WDL_String fileName, path;
1075
1076 if (mFileDialogFunc)
1077 mFileDialogFunc(fileName, path);
1078}
1079
1080- (void) colorPickerViewControllerDidSelectColor:(UIColorPickerViewController*) viewController;
1081{
1082 if (mColorPickerHandlerFunc)
1083 {
1084 IColor c = FromUIColor([viewController selectedColor]);
1085 mColorPickerHandlerFunc(c);
1086 }
1087}
1088
1089- (void) colorPickerViewControllerDidFinish:(UIColorPickerViewController*) viewController;
1090{
1091 mColorPickerHandlerFunc = nullptr;
1092}
1093
1094- (void) traitCollectionDidChange: (UITraitCollection*) previousTraitCollection
1095{
1096 [super traitCollectionDidChange: previousTraitCollection];
1097
1098 if(mGraphics)
1099 {
1100 mGraphics->OnAppearanceChanged([self.traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? EUIAppearance::Dark
1101 : EUIAppearance::Light);
1102 }
1103}
1104
1105- (void) getLastTouchLocation: (float&) x : (float&) y
1106{
1107 const float scale = mGraphics->GetDrawScale();
1108 x = mPrevX * scale;
1109 y = mPrevY * scale;
1110}
1111
1112- (void) activateGLContext
1113{
1114#ifdef IGRAPHICS_GL
1115 if (mEGLDisplay != EGL_NO_DISPLAY && mEGLContext != EGL_NO_CONTEXT)
1116 eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
1117#endif
1118}
1119
1120- (void) deactivateGLContext
1121{
1122#ifdef IGRAPHICS_GL
1123 if (mEGLDisplay != EGL_NO_DISPLAY)
1124 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1125#endif
1126}
1127
1128- (void) swapBuffers
1129{
1130#ifdef IGRAPHICS_GL
1131 if (mEGLDisplay != EGL_NO_DISPLAY && mEGLSurface != EGL_NO_SURFACE)
1132 eglSwapBuffers(mEGLDisplay, mEGLSurface);
1133#endif
1134}
1135@end
1136
This file contains the base IControl implementation, along with some base classes for specific types ...
The lowest level base class of an IGraphics control.
Definition: IControl.h:49
const IParam * GetParam(int valIdx=0) const
Get a const pointer to the IParam object (owned by the editor delegate class), associated with this c...
Definition: IControl.cpp:122
The lowest level base class of an IGraphics context.
Definition: IGraphics.h:87
IGraphics platform class for IOS.
Definition: IGraphicsIOS.h:25
IPlug's parameter class.
EParamType Type() const
Get the parameter's type.
A class to specify an item of a pop up menu.
A class for setting the contents of a pop up menu.
Used to manage a list of rectangular areas and optimize them for drawing to the screen.
Used to describe a particular gesture.
Used to group mouse coordinates with mouse modifier information.
Used to manage color data, independent of draw class/platform.
IText is used to manage font and text/text entry style for a piece of text on the UI,...