bump product version to 7.6.3.2-android
[LibreOffice.git] / vcl / osx / salinst.cxx
blobbe33e8ac9902fae0d18d9e0fcc68524e0cf83819
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/config.h>
21 #include <sal/log.hxx>
22 #include <osl/diagnose.h>
24 #include <condition_variable>
25 #include <mutex>
26 #include <utility>
28 #include <config_features.h>
30 #include <stdio.h>
32 #include <comphelper/solarmutex.hxx>
34 #include <comphelper/lok.hxx>
36 #include <osl/process.h>
38 #include <rtl/ustrbuf.hxx>
39 #include <vclpluginapi.h>
40 #include <vcl/QueueInfo.hxx>
41 #include <vcl/svapp.hxx>
42 #include <vcl/window.hxx>
43 #include <vcl/idle.hxx>
44 #include <vcl/svmain.hxx>
45 #include <vcl/opengl/OpenGLContext.hxx>
46 #include <vcl/commandevent.hxx>
47 #include <vcl/event.hxx>
49 #include <osx/saldata.hxx>
50 #include <osx/salinst.h>
51 #include <osx/salframe.h>
52 #include <osx/salobj.h>
53 #include <osx/salsys.h>
54 #include <quartz/salvd.h>
55 #include <quartz/salbmp.h>
56 #include <quartz/utils.h>
57 #include <osx/salprn.h>
58 #include <osx/saltimer.h>
59 #include <osx/vclnsapp.h>
60 #include <osx/runinmain.hxx>
62 #include <print.h>
63 #include <strings.hrc>
65 #include <comphelper/processfactory.hxx>
67 #include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
68 #include <com/sun/star/uno/XComponentContext.hpp>
70 #include <premac.h>
71 #include <Foundation/Foundation.h>
72 #include <ApplicationServices/ApplicationServices.h>
73 #import "apple_remote/RemoteMainController.h"
74 #include <apple_remote/RemoteControl.h>
75 #include <postmac.h>
77 #if HAVE_FEATURE_SKIA
78 #include <vcl/skia/SkiaHelper.hxx>
79 #include <skia/salbmp.hxx>
80 #include <skia/osx/gdiimpl.hxx>
81 #include <skia/osx/bitmap.hxx>
82 #endif
84 extern "C" {
85 #include <crt_externs.h>
88 using namespace ::com::sun::star;
90 static int* gpnInit = nullptr;
91 static NSMenu* pDockMenu = nil;
92 static bool bLeftMain = false;
94 namespace {
96 class AquaDelayedSettingsChanged : public Idle
98 bool mbInvalidate;
100 public:
101 AquaDelayedSettingsChanged( bool bInvalidate ) :
102 Idle("AquaSalInstance AquaDelayedSettingsChanged"),
103 mbInvalidate( bInvalidate )
107 virtual void Invoke() override
109 AquaSalInstance *pInst = GetSalData()->mpInstance;
110 SalFrame *pAnyFrame = pInst->anyFrame();
111 if( pAnyFrame )
112 pAnyFrame->CallCallback( SalEvent::SettingsChanged, nullptr );
114 if( mbInvalidate )
116 for( auto pSalFrame : pInst->getFrames() )
118 AquaSalFrame* pFrame = static_cast<AquaSalFrame*>( pSalFrame );
119 if( pFrame->mbShown )
120 pFrame->SendPaintEvent();
123 delete this;
129 static OUString& getFallbackPrinterName()
131 static OUString aFallbackPrinter;
133 if ( aFallbackPrinter.isEmpty() )
135 aFallbackPrinter = VclResId( SV_PRINT_DEFPRT_TXT );
136 if ( aFallbackPrinter.isEmpty() )
137 aFallbackPrinter = "Printer";
140 return aFallbackPrinter;
143 void AquaSalInstance::delayedSettingsChanged( bool bInvalidate )
145 osl::Guard< comphelper::SolarMutex > aGuard( *GetYieldMutex() );
146 AquaDelayedSettingsChanged* pIdle = new AquaDelayedSettingsChanged( bInvalidate );
147 pIdle->Start();
150 // the std::list<const ApplicationEvent*> must be available before any SalData/SalInst/etc. objects are ready
151 std::list<const ApplicationEvent*> AquaSalInstance::aAppEventList;
153 NSMenu* AquaSalInstance::GetDynamicDockMenu()
155 if( ! pDockMenu && ! bLeftMain )
156 pDockMenu = [[NSMenu alloc] initWithTitle: @""];
157 return pDockMenu;
160 bool AquaSalInstance::isOnCommandLine( const OUString& rArg )
162 sal_uInt32 nArgs = osl_getCommandArgCount();
163 for( sal_uInt32 i = 0; i < nArgs; i++ )
165 OUString aArg;
166 osl_getCommandArg( i, &aArg.pData );
167 if( aArg.equals( rArg ) )
168 return true;
170 return false;
173 void AquaSalInstance::AfterAppInit()
175 [[NSNotificationCenter defaultCenter] addObserver: NSApp
176 selector: @selector(systemColorsChanged:)
177 name: NSSystemColorsDidChangeNotification
178 object: nil ];
179 [[NSNotificationCenter defaultCenter] addObserver: NSApp
180 selector: @selector(screenParametersChanged:)
181 name: NSApplicationDidChangeScreenParametersNotification
182 object: nil ];
183 // add observers for some settings changes that affect vcl's settings
184 // scrollbar variant
185 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
186 selector: @selector(scrollbarVariantChanged:)
187 name: @"AppleAquaScrollBarVariantChanged"
188 object: nil ];
189 // scrollbar page behavior ("jump to here" or not)
190 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
191 selector: @selector(scrollbarSettingsChanged:)
192 name: @"AppleNoRedisplayAppearancePreferenceChanged"
193 object: nil ];
194 #if !HAVE_FEATURE_MACOSX_SANDBOX
195 // Initialize Apple Remote
196 GetSalData()->mpAppleRemoteMainController = [[AppleRemoteMainController alloc] init];
198 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
199 selector: @selector(applicationWillBecomeActive:)
200 name: @"AppleRemoteWillBecomeActive"
201 object: nil ];
203 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
204 selector: @selector(applicationWillResignActive:)
205 name: @"AppleRemoteWillResignActive"
206 object: nil ];
207 #endif
209 // HACK: When the first call to [NSSpellChecker sharedSpellChecker] (in
210 // lingucomponent/source/spellcheck/macosxspell/macspellimp.mm) is done both on a thread other
211 // than the main thread and with the SolarMutex erroneously locked, then that can lead to
212 // deadlock as [NSSpellChecker sharedSpellChecker] internally calls
213 // AppKit`-[NSSpellChecker init] ->
214 // AppKit`-[NSSpellChecker _fillSpellCheckerPopupButton:] ->
215 // AppKit`-[NSApplication(NSServicesMenuPrivate) _fillSpellCheckerPopupButton:] ->
216 // AppKit`-[NSMenu insertItem:atIndex:] ->
217 // Foundation`-[NSNotificationCenter postNotificationName:object:userInfo:] ->
218 // CoreFoundation`_CFXNotificationPost ->
219 // Foundation`-[NSOperation waitUntilFinished]
220 // waiting for work to be done on the main thread, but the main thread is typically already
221 // blocked (in some event handling loop) waiting to acquire the SolarMutex. The real solution
222 // would be to fix all the cases where a call to [NSSpellChecker sharedSpellChecker] in
223 // lingucomponent/source/spellcheck/macosxspell/macspellimp.mm is done while the SolarMutex is
224 // locked (somewhere up the call chain), but that appears to be rather difficult (see e.g.
225 // <https://bugs.documentfoundation.org/show_bug.cgi?id=151894> "FILEOPEN a Base Document with
226 // customized event for open a startform by 'open document' LO stuck"). So, at least for now,
227 // chicken out and do that first call to [NSSpellChecker sharedSpellChecker] upfront in a
228 // controlled environment:
229 [NSSpellChecker sharedSpellChecker];
232 SalYieldMutex::SalYieldMutex()
233 : m_aCodeBlock( nullptr )
237 SalYieldMutex::~SalYieldMutex()
241 void SalYieldMutex::doAcquire( sal_uInt32 nLockCount )
243 AquaSalInstance *pInst = GetSalData()->mpInstance;
244 if ( pInst && pInst->IsMainThread() )
246 if ( pInst->mbNoYieldLock )
247 return;
248 do {
249 RuninmainBlock block = nullptr;
251 std::unique_lock<std::mutex> g(m_runInMainMutex);
252 if (m_aMutex.tryToAcquire()) {
253 assert(m_aCodeBlock == nullptr);
254 m_wakeUpMain = false;
255 break;
257 // wait for doRelease() or RUNINMAIN_* to set the condition
258 m_aInMainCondition.wait(g, [this]() { return m_wakeUpMain; });
259 m_wakeUpMain = false;
260 std::swap(block, m_aCodeBlock);
262 if ( block )
264 assert( !pInst->mbNoYieldLock );
265 pInst->mbNoYieldLock = true;
266 block();
267 pInst->mbNoYieldLock = false;
268 Block_release( block );
269 std::scoped_lock<std::mutex> g(m_runInMainMutex);
270 assert(!m_resultReady);
271 m_resultReady = true;
272 m_aResultCondition.notify_all();
275 while ( true );
277 else
278 m_aMutex.acquire();
279 ++m_nCount;
280 --nLockCount;
282 comphelper::SolarMutex::doAcquire( nLockCount );
285 sal_uInt32 SalYieldMutex::doRelease( const bool bUnlockAll )
287 AquaSalInstance *pInst = GetSalData()->mpInstance;
288 if ( pInst->mbNoYieldLock && pInst->IsMainThread() )
289 return 1;
290 sal_uInt32 nCount;
292 std::scoped_lock<std::mutex> g(m_runInMainMutex);
293 // read m_nCount before doRelease
294 bool const isReleased(bUnlockAll || m_nCount == 1);
295 nCount = comphelper::SolarMutex::doRelease( bUnlockAll );
296 if (isReleased && !pInst->IsMainThread()) {
297 m_wakeUpMain = true;
298 m_aInMainCondition.notify_all();
301 return nCount;
304 bool SalYieldMutex::IsCurrentThread() const
306 if ( !GetSalData()->mpInstance->mbNoYieldLock )
307 return comphelper::SolarMutex::IsCurrentThread();
308 else
309 return GetSalData()->mpInstance->IsMainThread();
312 // some convenience functions regarding the yield mutex, aka solar mutex
314 bool ImplSalYieldMutexTryToAcquire()
316 AquaSalInstance* pInst = GetSalData()->mpInstance;
317 if ( pInst )
318 return pInst->GetYieldMutex()->tryToAcquire();
319 else
320 return false;
323 void ImplSalYieldMutexRelease()
325 AquaSalInstance* pInst = GetSalData()->mpInstance;
326 if ( pInst )
327 pInst->GetYieldMutex()->release();
330 extern "C" {
331 VCLPLUG_OSX_PUBLIC SalInstance* create_SalInstance()
333 SalData* pSalData = new SalData;
335 NSAutoreleasePool * pool = [ [ NSAutoreleasePool alloc ] init ];
336 unlink([[NSString stringWithFormat:@"%@/Library/Saved Application State/%s.savedState/restorecount.plist", NSHomeDirectory(), MACOSX_BUNDLE_IDENTIFIER] UTF8String]);
337 unlink([[NSString stringWithFormat:@"%@/Library/Saved Application State/%s.savedState/restorecount.txt", NSHomeDirectory(), MACOSX_BUNDLE_IDENTIFIER] UTF8String]);
338 [ pool drain ];
340 // create our cocoa NSApplication
341 [VCL_NSApplication sharedApplication];
343 SalData::ensureThreadAutoreleasePool();
345 // put cocoa into multithreaded mode
346 [NSThread detachNewThreadSelector:@selector(enableCocoaThreads:) toTarget:[[CocoaThreadEnabler alloc] init] withObject:nil];
348 // activate our delegate methods
349 [NSApp setDelegate: NSApp];
351 SAL_WARN_IF( pSalData->mpInstance != nullptr, "vcl", "more than one instance created" );
352 AquaSalInstance* pInst = new AquaSalInstance;
354 // init instance (only one instance in this version !!!)
355 pSalData->mpInstance = pInst;
356 // this one is for outside AquaSalInstance::Yield
357 SalData::ensureThreadAutoreleasePool();
358 // no focus rects on NWF
359 ImplGetSVData()->maNWFData.mbNoFocusRects = true;
360 ImplGetSVData()->maNWFData.mbNoActiveTabTextRaise = true;
361 ImplGetSVData()->maNWFData.mbCenteredTabs = true;
362 ImplGetSVData()->maNWFData.mnStatusBarLowerRightOffset = 10;
364 return pInst;
368 AquaSalInstance::AquaSalInstance()
369 : SalInstance(std::make_unique<SalYieldMutex>())
370 , mnActivePrintJobs( 0 )
371 , mbNoYieldLock( false )
372 , mbTimerProcessed( false )
374 maMainThread = osl::Thread::getCurrentIdentifier();
376 ImplSVData* pSVData = ImplGetSVData();
377 pSVData->maAppData.mxToolkitName = OUString("osx");
378 m_bSupportsOpenGL = true;
380 mpButtonCell = [[NSButtonCell alloc] init];
381 mpCheckCell = [[NSButtonCell alloc] init];
382 mpRadioCell = [[NSButtonCell alloc] init];
383 mpTextFieldCell = [[NSTextFieldCell alloc] initTextCell:@""];
384 mpComboBoxCell = [[NSComboBoxCell alloc] initTextCell:@""];
385 mpPopUpButtonCell = [[NSPopUpButtonCell alloc] init];
386 mpStepperCell = [[NSStepperCell alloc] init];
387 mpListNodeCell = [[NSButtonCell alloc] init];
389 #if HAVE_FEATURE_SKIA
390 AquaSkiaSalGraphicsImpl::prepareSkia();
391 #endif
394 AquaSalInstance::~AquaSalInstance()
396 [NSApp stop: NSApp];
397 bLeftMain = true;
398 if( pDockMenu )
400 [pDockMenu release];
401 pDockMenu = nil;
404 [mpListNodeCell release];
405 [mpStepperCell release];
406 [mpPopUpButtonCell release];
407 [mpComboBoxCell release];
408 [mpTextFieldCell release];
409 [mpRadioCell release];
410 [mpCheckCell release];
411 [mpButtonCell release];
413 #if HAVE_FEATURE_SKIA
414 SkiaHelper::cleanup();
415 #endif
418 void AquaSalInstance::TriggerUserEventProcessing()
420 dispatch_async(dispatch_get_main_queue(),^{
421 ImplNSAppPostEvent( AquaSalInstance::YieldWakeupEvent, NO );
425 void AquaSalInstance::ProcessEvent( SalUserEvent aEvent )
427 aEvent.m_pFrame->CallCallback( aEvent.m_nEvent, aEvent.m_pData );
428 maWaitingYieldCond.set();
431 bool AquaSalInstance::IsMainThread() const
433 return osl::Thread::getCurrentIdentifier() == maMainThread;
436 void AquaSalInstance::handleAppDefinedEvent( NSEvent* pEvent )
438 AquaSalTimer *pTimer = static_cast<AquaSalTimer*>( ImplGetSVData()->maSchedCtx.mpSalTimer );
439 int nSubtype = [pEvent subtype];
440 switch( nSubtype )
442 case AppStartTimerEvent:
443 if ( pTimer )
444 pTimer->handleStartTimerEvent( pEvent );
445 break;
446 case AppExecuteSVMain:
448 int nRet = ImplSVMain();
449 if (gpnInit)
450 *gpnInit = nRet;
451 [NSApp stop: NSApp];
452 break;
454 case DispatchTimerEvent:
456 AquaSalInstance *pInst = GetSalData()->mpInstance;
457 if ( pTimer && pInst )
458 pInst->mbTimerProcessed = pTimer->handleDispatchTimerEvent( pEvent );
459 break;
461 #if !HAVE_FEATURE_MACOSX_SANDBOX
462 case AppleRemoteControlEvent: // Defined in <apple_remote/RemoteMainController.h>
464 MediaCommand nCommand;
465 AquaSalInstance *pInst = GetSalData()->mpInstance;
466 bool bIsFullScreenMode = false;
468 for( auto pSalFrame : pInst->getFrames() )
470 const AquaSalFrame* pFrame = static_cast<const AquaSalFrame*>( pSalFrame );
471 if ( pFrame->mbFullScreen )
473 bIsFullScreenMode = true;
474 break;
478 switch ([pEvent data1])
480 case kRemoteButtonPlay:
481 nCommand = bIsFullScreenMode ? MediaCommand::PlayPause : MediaCommand::Play;
482 break;
484 // kept for experimentation purpose (scheduled for future implementation)
485 // case kRemoteButtonMenu: nCommand = MediaCommand::Menu; break;
487 case kRemoteButtonPlus: nCommand = MediaCommand::VolumeUp; break;
489 case kRemoteButtonMinus: nCommand = MediaCommand::VolumeDown; break;
491 case kRemoteButtonRight: nCommand = MediaCommand::NextTrack; break;
493 case kRemoteButtonRight_Hold: nCommand = MediaCommand::NextTrackHold; break;
495 case kRemoteButtonLeft: nCommand = MediaCommand::PreviousTrack; break;
497 case kRemoteButtonLeft_Hold: nCommand = MediaCommand::Rewind; break;
499 case kRemoteButtonPlay_Hold: nCommand = MediaCommand::PlayHold; break;
501 case kRemoteButtonMenu_Hold: nCommand = MediaCommand::Stop; break;
503 // FIXME : not detected
504 case kRemoteButtonPlus_Hold:
505 case kRemoteButtonMinus_Hold:
506 break;
508 default:
509 break;
511 AquaSalFrame* pFrame = static_cast<AquaSalFrame*>( pInst->anyFrame() );
512 vcl::Window* pWindow = pFrame ? pFrame->GetWindow() : nullptr;
513 if( pWindow )
515 const Point aPoint;
516 CommandMediaData aMediaData(nCommand);
517 CommandEvent aCEvt( aPoint, CommandEventId::Media, false, &aMediaData );
518 NotifyEvent aNCmdEvt( NotifyEventType::COMMAND, pWindow, &aCEvt );
520 if ( !ImplCallPreNotify( aNCmdEvt ) )
521 pWindow->Command( aCEvt );
525 break;
526 #endif
528 case YieldWakeupEvent:
529 // do nothing, fall out of Yield
530 break;
532 default:
533 OSL_FAIL( "unhandled NSEventTypeApplicationDefined event" );
534 break;
538 bool AquaSalInstance::RunInMainYield( bool bHandleAllCurrentEvents )
540 OSX_SALDATA_RUNINMAIN_UNION( DoYield( false, bHandleAllCurrentEvents), boolean )
542 // PrinterController::removeTransparencies() calls this frequently on the
543 // main thread so reduce the severity from an assert so that printing still
544 // works in a debug builds
545 SAL_WARN_IF( true, "vcl", "Don't call this from the main thread!" );
546 return false;
550 static bool isWakeupEvent( NSEvent *pEvent )
552 return NSEventTypeApplicationDefined == [pEvent type]
553 && AquaSalInstance::YieldWakeupEvent == static_cast<int>([pEvent subtype]);
556 bool AquaSalInstance::DoYield(bool bWait, bool bHandleAllCurrentEvents)
558 // Related: tdf#152703 Eliminate potential blocking during live resize
559 // Some events and timers call Application::Reschedule() or
560 // Application::Yield() so don't block and wait for events when a
561 // window is in live resize
562 if ( ImplGetSVData()->mpWinData->mbIsLiveResize )
563 bWait = false;
565 // ensure that the per thread autorelease pool is top level and
566 // will therefore not be destroyed by cocoa implicitly
567 SalData::ensureThreadAutoreleasePool();
569 // NSAutoreleasePool documentation suggests we should have
570 // an own pool for each yield level
571 ReleasePoolHolder aReleasePool;
573 // first, process current user events
574 // Related: tdf#152703 Eliminate potential blocking during live resize
575 // Only native events and timers need to be dispatched to redraw
576 // the window so skip dispatching user events when a window is in
577 // live resize
578 bool bHadEvent = ( !ImplGetSVData()->mpWinData->mbIsLiveResize && DispatchUserEvents( bHandleAllCurrentEvents ) );
579 if ( !bHandleAllCurrentEvents && bHadEvent )
580 return true;
582 // handle cocoa event queue
583 // cocoa events may be only handled in the thread the NSApp was created
584 if( IsMainThread() && mnActivePrintJobs == 0 )
586 // handle available events
587 NSEvent* pEvent = nil;
588 NSTimeInterval now = [[NSProcessInfo processInfo] systemUptime];
589 mbTimerProcessed = false;
593 SolarMutexReleaser aReleaser;
595 pEvent = [NSApp nextEventMatchingMask: NSEventMaskAny
596 untilDate: nil
597 inMode: NSDefaultRunLoopMode
598 dequeue: YES];
599 if( pEvent )
601 [NSApp sendEvent: pEvent];
602 if ( isWakeupEvent( pEvent ) )
603 continue;
604 bHadEvent = true;
607 [NSApp updateWindows];
609 if ( !bHandleAllCurrentEvents || !pEvent || now < [pEvent timestamp] )
610 break;
612 while( true );
614 AquaSalTimer *pTimer = static_cast<AquaSalTimer*>( ImplGetSVData()->maSchedCtx.mpSalTimer );
615 if ( !mbTimerProcessed && pTimer && pTimer->IsDirectTimeout() )
617 pTimer->handleTimerElapsed();
618 bHadEvent = true;
621 // if we had no event yet, wait for one if requested
622 if( bWait && ! bHadEvent )
624 SolarMutexReleaser aReleaser;
626 // attempt to fix macos jenkins hangs - part 3
627 // oox::xls::WorkbookFragment::finalizeImport() calls
628 // AquaSalInstance::DoYield() with bWait set to true. But
629 // since unit tests generally have no expected user generated
630 // events, we can end up blocking and waiting forever so
631 // don't block and wait when running unit tests.
632 pEvent = [NSApp nextEventMatchingMask: NSEventMaskAny
633 untilDate: SalInstance::IsRunningUnitTest() ? [NSDate distantPast] : [NSDate distantFuture]
634 inMode: NSDefaultRunLoopMode
635 dequeue: YES];
636 if( pEvent )
638 [NSApp sendEvent: pEvent];
639 if ( !isWakeupEvent( pEvent ) )
640 bHadEvent = true;
642 [NSApp updateWindows];
645 // collect update rectangles
646 for( auto pSalFrame : GetSalData()->mpInstance->getFrames() )
648 AquaSalFrame* pFrame = static_cast<AquaSalFrame*>( pSalFrame );
649 if( pFrame->mbShown && ! pFrame->maInvalidRect.IsEmpty() )
651 pFrame->Flush( pFrame->maInvalidRect );
652 pFrame->maInvalidRect.SetEmpty();
656 if ( bHadEvent )
657 maWaitingYieldCond.set();
659 else
661 bHadEvent = RunInMainYield( bHandleAllCurrentEvents );
662 if ( !bHadEvent && bWait )
664 // #i103162#
665 // wait until the main thread has dispatched an event
666 maWaitingYieldCond.reset();
667 SolarMutexReleaser aReleaser;
668 maWaitingYieldCond.wait();
672 // we get some apple events way too early
673 // before the application is ready to handle them,
674 // so their corresponding application events need to be delayed
675 // now is a good time to handle at least one of them
676 if( bWait && !aAppEventList.empty() && ImplGetSVData()->maAppData.mbInAppExecute )
678 // make sure that only one application event is active at a time
679 static bool bInAppEvent = false;
680 if( !bInAppEvent )
682 bInAppEvent = true;
683 // get the next delayed application event
684 const ApplicationEvent* pAppEvent = aAppEventList.front();
685 aAppEventList.pop_front();
686 // handle one application event (no recursion)
687 const ImplSVData* pSVData = ImplGetSVData();
688 pSVData->mpApp->AppEvent( *pAppEvent );
689 delete pAppEvent;
690 // allow the next delayed application event
691 bInAppEvent = false;
695 return bHadEvent;
698 bool AquaSalInstance::AnyInput( VclInputFlags nType )
700 if( nType & VclInputFlags::APPEVENT )
702 if( ! aAppEventList.empty() )
703 return true;
704 if( nType == VclInputFlags::APPEVENT )
705 return false;
708 OSX_INST_RUNINMAIN_UNION( AnyInput( nType ), boolean )
710 if( nType & VclInputFlags::TIMER )
712 AquaSalTimer *pTimer = static_cast<AquaSalTimer*>( ImplGetSVData()->maSchedCtx.mpSalTimer );
713 if (pTimer && pTimer->IsTimerElapsed())
714 return true;
717 unsigned/*NSUInteger*/ nEventMask = 0;
718 if( nType & VclInputFlags::MOUSE)
719 nEventMask |=
720 NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown |
721 NSEventMaskLeftMouseUp | NSEventMaskRightMouseUp | NSEventMaskOtherMouseUp |
722 NSEventMaskLeftMouseDragged | NSEventMaskRightMouseDragged | NSEventMaskOtherMouseDragged |
723 NSEventMaskScrollWheel |
724 // NSEventMaskMouseMoved |
725 NSEventMaskMouseEntered | NSEventMaskMouseExited;
726 if( nType & VclInputFlags::KEYBOARD)
727 nEventMask |= NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
728 if( nType & VclInputFlags::OTHER)
729 nEventMask |= NSEventMaskTabletPoint | NSEventMaskApplicationDefined;
730 // TODO: VclInputFlags::PAINT / more VclInputFlags::OTHER
731 if( !bool(nType) )
732 return false;
734 NSEvent* pEvent = [NSApp nextEventMatchingMask: nEventMask untilDate: nil
735 inMode: NSDefaultRunLoopMode dequeue: NO];
736 return (pEvent != nullptr);
739 SalFrame* AquaSalInstance::CreateChildFrame( SystemParentData*, SalFrameStyleFlags /*nSalFrameStyle*/ )
741 return nullptr;
744 SalFrame* AquaSalInstance::CreateFrame( SalFrame* pParent, SalFrameStyleFlags nSalFrameStyle )
746 OSX_INST_RUNINMAIN_POINTER( CreateFrame( pParent, nSalFrameStyle ), SalFrame* )
747 return new AquaSalFrame( pParent, nSalFrameStyle );
750 void AquaSalInstance::DestroyFrame( SalFrame* pFrame )
752 OSX_INST_RUNINMAIN( DestroyFrame( pFrame ) )
753 delete pFrame;
756 SalObject* AquaSalInstance::CreateObject( SalFrame* pParent, SystemWindowData* pWindowData, bool /* bShow */ )
758 if ( !pParent )
759 return nullptr;
761 OSX_INST_RUNINMAIN_POINTER( CreateObject( pParent, pWindowData, false ), SalObject* )
762 return new AquaSalObject( static_cast<AquaSalFrame*>(pParent), pWindowData );
765 void AquaSalInstance::DestroyObject( SalObject* pObject )
767 OSX_INST_RUNINMAIN( DestroyObject( pObject ) )
768 delete pObject;
771 std::unique_ptr<SalPrinter> AquaSalInstance::CreatePrinter( SalInfoPrinter* pInfoPrinter )
773 return std::unique_ptr<SalPrinter>(new AquaSalPrinter( dynamic_cast<AquaSalInfoPrinter*>(pInfoPrinter) ));
776 void AquaSalInstance::GetPrinterQueueInfo( ImplPrnQueueList* pList )
778 NSArray* pNames = [NSPrinter printerNames];
779 NSArray* pTypes = [NSPrinter printerTypes];
780 unsigned int nNameCount = pNames ? [pNames count] : 0;
781 unsigned int nTypeCount = pTypes ? [pTypes count] : 0;
782 SAL_WARN_IF( nTypeCount != nNameCount, "vcl", "type count not equal to printer count" );
783 for( unsigned int i = 0; i < nNameCount; i++ )
785 NSString* pName = [pNames objectAtIndex: i];
786 NSString* pType = i < nTypeCount ? [pTypes objectAtIndex: i] : nil;
787 if( pName )
789 std::unique_ptr<SalPrinterQueueInfo> pInfo(new SalPrinterQueueInfo);
790 pInfo->maPrinterName = GetOUString( pName );
791 if( pType )
792 pInfo->maDriver = GetOUString( pType );
793 pInfo->mnStatus = PrintQueueFlags::NONE;
794 pInfo->mnJobs = 0;
796 pList->Add( std::move(pInfo) );
800 // tdf#151700 Prevent the non-native LibreOffice PrintDialog from
801 // displaying by creating a fake printer if there are no printers. This
802 // will allow the LibreOffice printing code to proceed with native
803 // NSPrintOperation which will display the native print panel.
804 if ( !nNameCount )
806 std::unique_ptr<SalPrinterQueueInfo> pInfo(new SalPrinterQueueInfo);
807 pInfo->maPrinterName = getFallbackPrinterName();
808 pInfo->mnStatus = PrintQueueFlags::NONE;
809 pInfo->mnJobs = 0;
811 pList->Add( std::move(pInfo) );
815 void AquaSalInstance::GetPrinterQueueState( SalPrinterQueueInfo* )
819 OUString AquaSalInstance::GetDefaultPrinter()
821 // #i113170# may not be the main thread if called from UNO API
822 SalData::ensureThreadAutoreleasePool();
824 // WinSalInstance::GetDefaultPrinter() fetches current default printer
825 // on every call so do the same here
826 OUString aDefaultPrinter;
828 NSPrintInfo* pPI = [NSPrintInfo sharedPrintInfo];
829 SAL_WARN_IF( !pPI, "vcl", "no print info" );
830 if( pPI )
832 NSPrinter* pPr = [pPI printer];
833 SAL_WARN_IF( !pPr, "vcl", "no printer in default info" );
834 if( pPr )
836 // Related: tdf#151700 Return the name of the fake printer if
837 // there are no printers so that the LibreOffice printing code
838 // will be able to find the fake printer returned by
839 // AquaSalInstance::GetPrinterQueueInfo()
840 NSString* pDefName = [pPr name];
841 SAL_WARN_IF( !pDefName, "vcl", "printer has no name" );
842 if ( pDefName && [pDefName length])
843 aDefaultPrinter = GetOUString( pDefName );
844 else
845 aDefaultPrinter = getFallbackPrinterName();
849 return aDefaultPrinter;
852 SalInfoPrinter* AquaSalInstance::CreateInfoPrinter( SalPrinterQueueInfo* pQueueInfo,
853 ImplJobSetup* pSetupData )
855 // #i113170# may not be the main thread if called from UNO API
856 SalData::ensureThreadAutoreleasePool();
858 SalInfoPrinter* pNewInfoPrinter = nullptr;
859 if( pQueueInfo )
861 pNewInfoPrinter = new AquaSalInfoPrinter( *pQueueInfo );
862 if( pSetupData )
863 pNewInfoPrinter->SetPrinterData( pSetupData );
866 return pNewInfoPrinter;
869 void AquaSalInstance::DestroyInfoPrinter( SalInfoPrinter* pPrinter )
871 // #i113170# may not be the main thread if called from UNO API
872 SalData::ensureThreadAutoreleasePool();
874 delete pPrinter;
877 OUString AquaSalInstance::GetConnectionIdentifier()
879 return OUString();
882 // We need to re-encode file urls because osl_getFileURLFromSystemPath converts
883 // to UTF-8 before encoding non ascii characters, which is not what other apps expect.
884 static OUString translateToExternalUrl(const OUString& internalUrl)
886 uno::Reference< uno::XComponentContext > context(
887 comphelper::getProcessComponentContext());
888 return uri::ExternalUriReferenceTranslator::create(context)->translateToExternal(internalUrl);
891 // #i104525# many versions of OSX have problems with some URLs:
892 // when an app requests OSX to add one of these URLs to the "Recent Items" list
893 // then this app gets killed (TextEdit, Preview, etc. and also OOo)
894 static bool isDangerousUrl( const OUString& rUrl )
896 // use a heuristic that detects all known cases since there is no official comment
897 // on the exact impact and root cause of the OSX bug
898 const int nLen = rUrl.getLength();
899 const sal_Unicode* p = rUrl.getStr();
900 for( int i = 0; i < nLen-3; ++i, ++p ) {
901 if( p[0] != '%' )
902 continue;
903 // escaped percent?
904 if( (p[1] == '2') && (p[2] == '5') )
905 return true;
906 // escapes are considered to be UTF-8 encoded
907 // => check for invalid UTF-8 leading byte
908 if( (p[1] != 'f') && (p[1] != 'F') )
909 continue;
910 int cLowNibble = p[2];
911 if( (cLowNibble >= '0' ) && (cLowNibble <= '9'))
912 return false;
913 if( cLowNibble >= 'a' )
914 cLowNibble -= 'a' - 'A';
915 if( (cLowNibble < 'A') || (cLowNibble >= 'C'))
916 return true;
919 return false;
922 void AquaSalInstance::AddToRecentDocumentList(const OUString& rFileUrl, const OUString& /*rMimeType*/, const OUString& /*rDocumentService*/)
924 // Convert file URL for external use (see above)
925 OUString externalUrl = translateToExternalUrl(rFileUrl);
926 if( externalUrl.isEmpty() )
927 externalUrl = rFileUrl;
929 if( !externalUrl.isEmpty() && !isDangerousUrl( externalUrl ) )
931 NSString* pString = CreateNSString( externalUrl );
932 NSURL* pURL = [NSURL URLWithString: pString];
934 if( pURL )
936 NSDocumentController* pCtrl = [NSDocumentController sharedDocumentController];
937 [pCtrl noteNewRecentDocumentURL: pURL];
939 if( pString )
940 [pString release];
944 SalTimer* AquaSalInstance::CreateSalTimer()
946 return new AquaSalTimer();
949 SalSystem* AquaSalInstance::CreateSalSystem()
951 return new AquaSalSystem();
954 std::shared_ptr<SalBitmap> AquaSalInstance::CreateSalBitmap()
956 #if HAVE_FEATURE_SKIA
957 if (SkiaHelper::isVCLSkiaEnabled())
958 return std::make_shared<SkiaSalBitmap>();
959 else
960 #endif
961 return std::make_shared<QuartzSalBitmap>();
964 OUString AquaSalInstance::getOSVersion()
966 NSString * versionString = nullptr;
967 NSDictionary * sysVersionDict = [ NSDictionary dictionaryWithContentsOfFile: @"/System/Library/CoreServices/SystemVersion.plist" ];
968 if ( sysVersionDict )
969 versionString = [ sysVersionDict valueForKey: @"ProductVersion" ];
971 OUString aVersion = "Mac OS X ";
972 if ( versionString )
973 aVersion += OUString::fromUtf8( [ versionString UTF8String ] );
974 else
975 aVersion += "(unknown)";
977 return aVersion;
980 CGImageRef CreateCGImage( const Image& rImage )
982 #if HAVE_FEATURE_SKIA
983 if (SkiaHelper::isVCLSkiaEnabled())
984 return SkiaHelper::createCGImage( rImage );
985 #endif
987 BitmapEx aBmpEx( rImage.GetBitmapEx() );
988 Bitmap aBmp( aBmpEx.GetBitmap() );
990 if( aBmp.IsEmpty() || ! aBmp.ImplGetSalBitmap() )
991 return nullptr;
993 // simple case, no transparency
994 QuartzSalBitmap* pSalBmp = static_cast<QuartzSalBitmap*>(aBmp.ImplGetSalBitmap().get());
996 if( ! pSalBmp )
997 return nullptr;
999 CGImageRef xImage = nullptr;
1000 if( !aBmpEx.IsAlpha() )
1001 xImage = pSalBmp->CreateCroppedImage( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1002 else
1004 AlphaMask aAlphaMask( aBmpEx.GetAlphaMask() );
1005 Bitmap aMask( aAlphaMask.GetBitmap() );
1006 QuartzSalBitmap* pMaskBmp = static_cast<QuartzSalBitmap*>(aMask.ImplGetSalBitmap().get());
1007 if( pMaskBmp )
1008 xImage = pSalBmp->CreateWithMask( *pMaskBmp, 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1009 else
1010 xImage = pSalBmp->CreateCroppedImage( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1013 return xImage;
1016 NSImage* CreateNSImage( const Image& rImage )
1018 CGImageRef xImage = CreateCGImage( rImage );
1020 if( ! xImage )
1021 return nil;
1023 Size aSize( rImage.GetSizePixel() );
1024 NSImage* pImage = [[NSImage alloc] initWithSize: NSMakeSize( aSize.Width(), aSize.Height() )];
1025 if( pImage )
1027 [pImage lockFocusFlipped:YES];
1028 NSGraphicsContext* pContext = [NSGraphicsContext currentContext];
1029 CGContextRef rCGContext = [pContext CGContext];
1031 const CGRect aDstRect = { {0, 0}, { static_cast<CGFloat>(aSize.Width()), static_cast<CGFloat>(aSize.Height()) } };
1032 CGContextDrawImage( rCGContext, aDstRect, xImage );
1034 [pImage unlockFocus];
1037 CGImageRelease( xImage );
1039 return pImage;
1042 bool AquaSalInstance::SVMainHook(int* pnInit)
1044 gpnInit = pnInit;
1046 OUString aExeURL, aExe;
1047 osl_getExecutableFile( &aExeURL.pData );
1048 osl_getSystemPathFromFileURL( aExeURL.pData, &aExe.pData );
1049 OString aByteExe( OUStringToOString( aExe, osl_getThreadTextEncoding() ) );
1051 #ifdef DEBUG
1052 aByteExe += OString ( " NSAccessibilityDebugLogLevel 1" );
1053 const char* pArgv[] = { aByteExe.getStr(), NULL };
1054 NSApplicationMain( 3, pArgv );
1055 #else
1056 const char* pArgv[] = { aByteExe.getStr(), nullptr };
1057 NSApplicationMain( 1, pArgv );
1058 #endif
1060 return true;
1063 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */