gb_var2file: remove now unused chunk-size parameter
[LibreOffice.git] / vcl / osx / salinst.cxx
blobe8a4a94efc0893db5d312898899330255abaf124
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 , mbIsLiveResize( false )
372 , mbNoYieldLock( false )
373 , mbTimerProcessed( false )
375 maMainThread = osl::Thread::getCurrentIdentifier();
377 ImplSVData* pSVData = ImplGetSVData();
378 pSVData->maAppData.mxToolkitName = OUString("osx");
379 m_bSupportsOpenGL = true;
381 mpButtonCell = [[NSButtonCell alloc] init];
382 mpCheckCell = [[NSButtonCell alloc] init];
383 mpRadioCell = [[NSButtonCell alloc] init];
384 mpTextFieldCell = [[NSTextFieldCell alloc] initTextCell:@""];
385 mpComboBoxCell = [[NSComboBoxCell alloc] initTextCell:@""];
386 mpPopUpButtonCell = [[NSPopUpButtonCell alloc] init];
387 mpStepperCell = [[NSStepperCell alloc] init];
388 mpListNodeCell = [[NSButtonCell alloc] init];
390 #if HAVE_FEATURE_SKIA
391 AquaSkiaSalGraphicsImpl::prepareSkia();
392 #endif
395 AquaSalInstance::~AquaSalInstance()
397 [NSApp stop: NSApp];
398 bLeftMain = true;
399 if( pDockMenu )
401 [pDockMenu release];
402 pDockMenu = nil;
405 [mpListNodeCell release];
406 [mpStepperCell release];
407 [mpPopUpButtonCell release];
408 [mpComboBoxCell release];
409 [mpTextFieldCell release];
410 [mpRadioCell release];
411 [mpCheckCell release];
412 [mpButtonCell release];
414 #if HAVE_FEATURE_SKIA
415 SkiaHelper::cleanup();
416 #endif
419 void AquaSalInstance::TriggerUserEventProcessing()
421 dispatch_async(dispatch_get_main_queue(),^{
422 ImplNSAppPostEvent( AquaSalInstance::YieldWakeupEvent, NO );
426 void AquaSalInstance::ProcessEvent( SalUserEvent aEvent )
428 aEvent.m_pFrame->CallCallback( aEvent.m_nEvent, aEvent.m_pData );
429 maWaitingYieldCond.set();
432 bool AquaSalInstance::IsMainThread() const
434 return osl::Thread::getCurrentIdentifier() == maMainThread;
437 void AquaSalInstance::handleAppDefinedEvent( NSEvent* pEvent )
439 AquaSalTimer *pTimer = static_cast<AquaSalTimer*>( ImplGetSVData()->maSchedCtx.mpSalTimer );
440 int nSubtype = [pEvent subtype];
441 switch( nSubtype )
443 case AppStartTimerEvent:
444 if ( pTimer )
445 pTimer->handleStartTimerEvent( pEvent );
446 break;
447 case AppExecuteSVMain:
449 int nRet = ImplSVMain();
450 if (gpnInit)
451 *gpnInit = nRet;
452 [NSApp stop: NSApp];
453 break;
455 case DispatchTimerEvent:
457 AquaSalInstance *pInst = GetSalData()->mpInstance;
458 if ( pTimer && pInst )
459 pInst->mbTimerProcessed = pTimer->handleDispatchTimerEvent( pEvent );
460 break;
462 #if !HAVE_FEATURE_MACOSX_SANDBOX
463 case AppleRemoteControlEvent: // Defined in <apple_remote/RemoteMainController.h>
465 MediaCommand nCommand;
466 AquaSalInstance *pInst = GetSalData()->mpInstance;
467 bool bIsFullScreenMode = false;
469 for( auto pSalFrame : pInst->getFrames() )
471 const AquaSalFrame* pFrame = static_cast<const AquaSalFrame*>( pSalFrame );
472 if ( pFrame->mbFullScreen )
474 bIsFullScreenMode = true;
475 break;
479 switch ([pEvent data1])
481 case kRemoteButtonPlay:
482 nCommand = bIsFullScreenMode ? MediaCommand::PlayPause : MediaCommand::Play;
483 break;
485 // kept for experimentation purpose (scheduled for future implementation)
486 // case kRemoteButtonMenu: nCommand = MediaCommand::Menu; break;
488 case kRemoteButtonPlus: nCommand = MediaCommand::VolumeUp; break;
490 case kRemoteButtonMinus: nCommand = MediaCommand::VolumeDown; break;
492 case kRemoteButtonRight: nCommand = MediaCommand::NextTrack; break;
494 case kRemoteButtonRight_Hold: nCommand = MediaCommand::NextTrackHold; break;
496 case kRemoteButtonLeft: nCommand = MediaCommand::PreviousTrack; break;
498 case kRemoteButtonLeft_Hold: nCommand = MediaCommand::Rewind; break;
500 case kRemoteButtonPlay_Hold: nCommand = MediaCommand::PlayHold; break;
502 case kRemoteButtonMenu_Hold: nCommand = MediaCommand::Stop; break;
504 // FIXME : not detected
505 case kRemoteButtonPlus_Hold:
506 case kRemoteButtonMinus_Hold:
507 break;
509 default:
510 break;
512 AquaSalFrame* pFrame = static_cast<AquaSalFrame*>( pInst->anyFrame() );
513 vcl::Window* pWindow = pFrame ? pFrame->GetWindow() : nullptr;
514 if( pWindow )
516 const Point aPoint;
517 CommandMediaData aMediaData(nCommand);
518 CommandEvent aCEvt( aPoint, CommandEventId::Media, false, &aMediaData );
519 NotifyEvent aNCmdEvt( NotifyEventType::COMMAND, pWindow, &aCEvt );
521 if ( !ImplCallPreNotify( aNCmdEvt ) )
522 pWindow->Command( aCEvt );
526 break;
527 #endif
529 case YieldWakeupEvent:
530 // do nothing, fall out of Yield
531 break;
533 default:
534 OSL_FAIL( "unhandled NSEventTypeApplicationDefined event" );
535 break;
539 bool AquaSalInstance::RunInMainYield( bool bHandleAllCurrentEvents )
541 OSX_SALDATA_RUNINMAIN_UNION( DoYield( false, bHandleAllCurrentEvents), boolean )
543 // PrinterController::removeTransparencies() calls this frequently on the
544 // main thread so reduce the severity from an assert so that printing still
545 // works in a debug builds
546 SAL_WARN_IF( true, "vcl", "Don't call this from the main thread!" );
547 return false;
551 static bool isWakeupEvent( NSEvent *pEvent )
553 return NSEventTypeApplicationDefined == [pEvent type]
554 && AquaSalInstance::YieldWakeupEvent == static_cast<int>([pEvent subtype]);
557 bool AquaSalInstance::DoYield(bool bWait, bool bHandleAllCurrentEvents)
559 // ensure that the per thread autorelease pool is top level and
560 // will therefore not be destroyed by cocoa implicitly
561 SalData::ensureThreadAutoreleasePool();
563 // NSAutoreleasePool documentation suggests we should have
564 // an own pool for each yield level
565 ReleasePoolHolder aReleasePool;
567 // first, process current user events
568 bool bHadEvent = DispatchUserEvents( bHandleAllCurrentEvents );
569 if ( !bHandleAllCurrentEvents && bHadEvent )
570 return true;
572 // handle cocoa event queue
573 // cocoa events may be only handled in the thread the NSApp was created
574 if( IsMainThread() && mnActivePrintJobs == 0 )
576 // handle available events
577 NSEvent* pEvent = nil;
578 NSTimeInterval now = [[NSProcessInfo processInfo] systemUptime];
579 mbTimerProcessed = false;
583 SolarMutexReleaser aReleaser;
585 pEvent = [NSApp nextEventMatchingMask: NSEventMaskAny
586 untilDate: nil
587 inMode: NSDefaultRunLoopMode
588 dequeue: YES];
589 if( pEvent )
591 [NSApp sendEvent: pEvent];
592 if ( isWakeupEvent( pEvent ) )
593 continue;
594 bHadEvent = true;
597 [NSApp updateWindows];
599 if ( !bHandleAllCurrentEvents || !pEvent || now < [pEvent timestamp] )
600 break;
602 while( true );
604 AquaSalTimer *pTimer = static_cast<AquaSalTimer*>( ImplGetSVData()->maSchedCtx.mpSalTimer );
605 if ( !mbTimerProcessed && pTimer && pTimer->IsDirectTimeout() )
607 pTimer->handleTimerElapsed();
608 bHadEvent = true;
611 // if we had no event yet, wait for one if requested
612 if( bWait && ! bHadEvent )
614 SolarMutexReleaser aReleaser;
616 pEvent = [NSApp nextEventMatchingMask: NSEventMaskAny
617 untilDate: [NSDate distantFuture]
618 inMode: NSDefaultRunLoopMode
619 dequeue: YES];
620 if( pEvent )
622 [NSApp sendEvent: pEvent];
623 if ( !isWakeupEvent( pEvent ) )
624 bHadEvent = true;
626 [NSApp updateWindows];
629 // collect update rectangles
630 for( auto pSalFrame : GetSalData()->mpInstance->getFrames() )
632 AquaSalFrame* pFrame = static_cast<AquaSalFrame*>( pSalFrame );
633 if( pFrame->mbShown && ! pFrame->maInvalidRect.IsEmpty() )
635 pFrame->Flush( pFrame->maInvalidRect );
636 pFrame->maInvalidRect.SetEmpty();
640 if ( bHadEvent )
641 maWaitingYieldCond.set();
643 else
645 bHadEvent = RunInMainYield( bHandleAllCurrentEvents );
646 if ( !bHadEvent && bWait )
648 // #i103162#
649 // wait until the main thread has dispatched an event
650 maWaitingYieldCond.reset();
651 SolarMutexReleaser aReleaser;
652 maWaitingYieldCond.wait();
656 // we get some apple events way too early
657 // before the application is ready to handle them,
658 // so their corresponding application events need to be delayed
659 // now is a good time to handle at least one of them
660 if( bWait && !aAppEventList.empty() && ImplGetSVData()->maAppData.mbInAppExecute )
662 // make sure that only one application event is active at a time
663 static bool bInAppEvent = false;
664 if( !bInAppEvent )
666 bInAppEvent = true;
667 // get the next delayed application event
668 const ApplicationEvent* pAppEvent = aAppEventList.front();
669 aAppEventList.pop_front();
670 // handle one application event (no recursion)
671 const ImplSVData* pSVData = ImplGetSVData();
672 pSVData->mpApp->AppEvent( *pAppEvent );
673 delete pAppEvent;
674 // allow the next delayed application event
675 bInAppEvent = false;
679 return bHadEvent;
682 bool AquaSalInstance::AnyInput( VclInputFlags nType )
684 if( nType & VclInputFlags::APPEVENT )
686 if( ! aAppEventList.empty() )
687 return true;
688 if( nType == VclInputFlags::APPEVENT )
689 return false;
692 OSX_INST_RUNINMAIN_UNION( AnyInput( nType ), boolean )
694 if( nType & VclInputFlags::TIMER )
696 AquaSalTimer *pTimer = static_cast<AquaSalTimer*>( ImplGetSVData()->maSchedCtx.mpSalTimer );
697 if (pTimer && pTimer->IsTimerElapsed())
698 return true;
701 unsigned/*NSUInteger*/ nEventMask = 0;
702 if( nType & VclInputFlags::MOUSE)
703 nEventMask |=
704 NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown |
705 NSEventMaskLeftMouseUp | NSEventMaskRightMouseUp | NSEventMaskOtherMouseUp |
706 NSEventMaskLeftMouseDragged | NSEventMaskRightMouseDragged | NSEventMaskOtherMouseDragged |
707 NSEventMaskScrollWheel |
708 // NSEventMaskMouseMoved |
709 NSEventMaskMouseEntered | NSEventMaskMouseExited;
710 if( nType & VclInputFlags::KEYBOARD)
711 nEventMask |= NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
712 if( nType & VclInputFlags::OTHER)
713 nEventMask |= NSEventMaskTabletPoint | NSEventMaskApplicationDefined;
714 // TODO: VclInputFlags::PAINT / more VclInputFlags::OTHER
715 if( !bool(nType) )
716 return false;
718 NSEvent* pEvent = [NSApp nextEventMatchingMask: nEventMask untilDate: nil
719 inMode: NSDefaultRunLoopMode dequeue: NO];
720 return (pEvent != nullptr);
723 SalFrame* AquaSalInstance::CreateChildFrame( SystemParentData*, SalFrameStyleFlags /*nSalFrameStyle*/ )
725 return nullptr;
728 SalFrame* AquaSalInstance::CreateFrame( SalFrame* pParent, SalFrameStyleFlags nSalFrameStyle )
730 OSX_INST_RUNINMAIN_POINTER( CreateFrame( pParent, nSalFrameStyle ), SalFrame* )
731 return new AquaSalFrame( pParent, nSalFrameStyle );
734 void AquaSalInstance::DestroyFrame( SalFrame* pFrame )
736 OSX_INST_RUNINMAIN( DestroyFrame( pFrame ) )
737 delete pFrame;
740 SalObject* AquaSalInstance::CreateObject( SalFrame* pParent, SystemWindowData* pWindowData, bool /* bShow */ )
742 if ( !pParent )
743 return nullptr;
745 OSX_INST_RUNINMAIN_POINTER( CreateObject( pParent, pWindowData, false ), SalObject* )
746 return new AquaSalObject( static_cast<AquaSalFrame*>(pParent), pWindowData );
749 void AquaSalInstance::DestroyObject( SalObject* pObject )
751 OSX_INST_RUNINMAIN( DestroyObject( pObject ) )
752 delete pObject;
755 std::unique_ptr<SalPrinter> AquaSalInstance::CreatePrinter( SalInfoPrinter* pInfoPrinter )
757 return std::unique_ptr<SalPrinter>(new AquaSalPrinter( dynamic_cast<AquaSalInfoPrinter*>(pInfoPrinter) ));
760 void AquaSalInstance::GetPrinterQueueInfo( ImplPrnQueueList* pList )
762 NSArray* pNames = [NSPrinter printerNames];
763 NSArray* pTypes = [NSPrinter printerTypes];
764 unsigned int nNameCount = pNames ? [pNames count] : 0;
765 unsigned int nTypeCount = pTypes ? [pTypes count] : 0;
766 SAL_WARN_IF( nTypeCount != nNameCount, "vcl", "type count not equal to printer count" );
767 for( unsigned int i = 0; i < nNameCount; i++ )
769 NSString* pName = [pNames objectAtIndex: i];
770 NSString* pType = i < nTypeCount ? [pTypes objectAtIndex: i] : nil;
771 if( pName )
773 std::unique_ptr<SalPrinterQueueInfo> pInfo(new SalPrinterQueueInfo);
774 pInfo->maPrinterName = GetOUString( pName );
775 if( pType )
776 pInfo->maDriver = GetOUString( pType );
777 pInfo->mnStatus = PrintQueueFlags::NONE;
778 pInfo->mnJobs = 0;
780 pList->Add( std::move(pInfo) );
784 // tdf#151700 Prevent the non-native LibreOffice PrintDialog from
785 // displaying by creating a fake printer if there are no printers. This
786 // will allow the LibreOffice printing code to proceed with native
787 // NSPrintOperation which will display the native print panel.
788 if ( !nNameCount )
790 std::unique_ptr<SalPrinterQueueInfo> pInfo(new SalPrinterQueueInfo);
791 pInfo->maPrinterName = getFallbackPrinterName();
792 pInfo->mnStatus = PrintQueueFlags::NONE;
793 pInfo->mnJobs = 0;
795 pList->Add( std::move(pInfo) );
799 void AquaSalInstance::GetPrinterQueueState( SalPrinterQueueInfo* )
803 OUString AquaSalInstance::GetDefaultPrinter()
805 // #i113170# may not be the main thread if called from UNO API
806 SalData::ensureThreadAutoreleasePool();
808 // WinSalInstance::GetDefaultPrinter() fetches current default printer
809 // on every call so do the same here
810 OUString aDefaultPrinter;
812 NSPrintInfo* pPI = [NSPrintInfo sharedPrintInfo];
813 SAL_WARN_IF( !pPI, "vcl", "no print info" );
814 if( pPI )
816 NSPrinter* pPr = [pPI printer];
817 SAL_WARN_IF( !pPr, "vcl", "no printer in default info" );
818 if( pPr )
820 // Related: tdf#151700 Return the name of the fake printer if
821 // there are no printers so that the LibreOffice printing code
822 // will be able to find the the fake printer returned by
823 // AquaSalInstance::GetPrinterQueueInfo()
824 NSString* pDefName = [pPr name];
825 SAL_WARN_IF( !pDefName, "vcl", "printer has no name" );
826 if ( pDefName && [pDefName length])
827 aDefaultPrinter = GetOUString( pDefName );
828 else
829 aDefaultPrinter = getFallbackPrinterName();
833 return aDefaultPrinter;
836 SalInfoPrinter* AquaSalInstance::CreateInfoPrinter( SalPrinterQueueInfo* pQueueInfo,
837 ImplJobSetup* pSetupData )
839 // #i113170# may not be the main thread if called from UNO API
840 SalData::ensureThreadAutoreleasePool();
842 SalInfoPrinter* pNewInfoPrinter = nullptr;
843 if( pQueueInfo )
845 pNewInfoPrinter = new AquaSalInfoPrinter( *pQueueInfo );
846 if( pSetupData )
847 pNewInfoPrinter->SetPrinterData( pSetupData );
850 return pNewInfoPrinter;
853 void AquaSalInstance::DestroyInfoPrinter( SalInfoPrinter* pPrinter )
855 // #i113170# may not be the main thread if called from UNO API
856 SalData::ensureThreadAutoreleasePool();
858 delete pPrinter;
861 OUString AquaSalInstance::GetConnectionIdentifier()
863 return OUString();
866 // We need to re-encode file urls because osl_getFileURLFromSystemPath converts
867 // to UTF-8 before encoding non ascii characters, which is not what other apps expect.
868 static OUString translateToExternalUrl(const OUString& internalUrl)
870 uno::Reference< uno::XComponentContext > context(
871 comphelper::getProcessComponentContext());
872 return uri::ExternalUriReferenceTranslator::create(context)->translateToExternal(internalUrl);
875 // #i104525# many versions of OSX have problems with some URLs:
876 // when an app requests OSX to add one of these URLs to the "Recent Items" list
877 // then this app gets killed (TextEdit, Preview, etc. and also OOo)
878 static bool isDangerousUrl( const OUString& rUrl )
880 // use a heuristic that detects all known cases since there is no official comment
881 // on the exact impact and root cause of the OSX bug
882 const int nLen = rUrl.getLength();
883 const sal_Unicode* p = rUrl.getStr();
884 for( int i = 0; i < nLen-3; ++i, ++p ) {
885 if( p[0] != '%' )
886 continue;
887 // escaped percent?
888 if( (p[1] == '2') && (p[2] == '5') )
889 return true;
890 // escapes are considered to be UTF-8 encoded
891 // => check for invalid UTF-8 leading byte
892 if( (p[1] != 'f') && (p[1] != 'F') )
893 continue;
894 int cLowNibble = p[2];
895 if( (cLowNibble >= '0' ) && (cLowNibble <= '9'))
896 return false;
897 if( cLowNibble >= 'a' )
898 cLowNibble -= 'a' - 'A';
899 if( (cLowNibble < 'A') || (cLowNibble >= 'C'))
900 return true;
903 return false;
906 void AquaSalInstance::AddToRecentDocumentList(const OUString& rFileUrl, const OUString& /*rMimeType*/, const OUString& /*rDocumentService*/)
908 // Convert file URL for external use (see above)
909 OUString externalUrl = translateToExternalUrl(rFileUrl);
910 if( externalUrl.isEmpty() )
911 externalUrl = rFileUrl;
913 if( !externalUrl.isEmpty() && !isDangerousUrl( externalUrl ) )
915 NSString* pString = CreateNSString( externalUrl );
916 NSURL* pURL = [NSURL URLWithString: pString];
918 if( pURL )
920 NSDocumentController* pCtrl = [NSDocumentController sharedDocumentController];
921 [pCtrl noteNewRecentDocumentURL: pURL];
923 if( pString )
924 [pString release];
928 SalTimer* AquaSalInstance::CreateSalTimer()
930 return new AquaSalTimer();
933 SalSystem* AquaSalInstance::CreateSalSystem()
935 return new AquaSalSystem();
938 std::shared_ptr<SalBitmap> AquaSalInstance::CreateSalBitmap()
940 #if HAVE_FEATURE_SKIA
941 if (SkiaHelper::isVCLSkiaEnabled())
942 return std::make_shared<SkiaSalBitmap>();
943 else
944 #endif
945 return std::make_shared<QuartzSalBitmap>();
948 OUString AquaSalInstance::getOSVersion()
950 NSString * versionString = nullptr;
951 NSDictionary * sysVersionDict = [ NSDictionary dictionaryWithContentsOfFile: @"/System/Library/CoreServices/SystemVersion.plist" ];
952 if ( sysVersionDict )
953 versionString = [ sysVersionDict valueForKey: @"ProductVersion" ];
955 OUString aVersion = "Mac OS X ";
956 if ( versionString )
957 aVersion += OUString::fromUtf8( [ versionString UTF8String ] );
958 else
959 aVersion += "(unknown)";
961 return aVersion;
964 CGImageRef CreateCGImage( const Image& rImage )
966 #if HAVE_FEATURE_SKIA
967 if (SkiaHelper::isVCLSkiaEnabled())
968 return SkiaHelper::createCGImage( rImage );
969 #endif
971 BitmapEx aBmpEx( rImage.GetBitmapEx() );
972 Bitmap aBmp( aBmpEx.GetBitmap() );
974 if( aBmp.IsEmpty() || ! aBmp.ImplGetSalBitmap() )
975 return nullptr;
977 // simple case, no transparency
978 QuartzSalBitmap* pSalBmp = static_cast<QuartzSalBitmap*>(aBmp.ImplGetSalBitmap().get());
980 if( ! pSalBmp )
981 return nullptr;
983 CGImageRef xImage = nullptr;
984 if( !aBmpEx.IsAlpha() )
985 xImage = pSalBmp->CreateCroppedImage( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
986 else
988 AlphaMask aAlphaMask( aBmpEx.GetAlpha() );
989 Bitmap aMask( aAlphaMask.GetBitmap() );
990 QuartzSalBitmap* pMaskBmp = static_cast<QuartzSalBitmap*>(aMask.ImplGetSalBitmap().get());
991 if( pMaskBmp )
992 xImage = pSalBmp->CreateWithMask( *pMaskBmp, 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
993 else
994 xImage = pSalBmp->CreateCroppedImage( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
997 return xImage;
1000 NSImage* CreateNSImage( const Image& rImage )
1002 CGImageRef xImage = CreateCGImage( rImage );
1004 if( ! xImage )
1005 return nil;
1007 Size aSize( rImage.GetSizePixel() );
1008 NSImage* pImage = [[NSImage alloc] initWithSize: NSMakeSize( aSize.Width(), aSize.Height() )];
1009 if( pImage )
1011 [pImage lockFocusFlipped:YES];
1012 NSGraphicsContext* pContext = [NSGraphicsContext currentContext];
1013 CGContextRef rCGContext = [pContext CGContext];
1015 const CGRect aDstRect = { {0, 0}, { static_cast<CGFloat>(aSize.Width()), static_cast<CGFloat>(aSize.Height()) } };
1016 CGContextDrawImage( rCGContext, aDstRect, xImage );
1018 [pImage unlockFocus];
1021 CGImageRelease( xImage );
1023 return pImage;
1026 bool AquaSalInstance::SVMainHook(int* pnInit)
1028 gpnInit = pnInit;
1030 OUString aExeURL, aExe;
1031 osl_getExecutableFile( &aExeURL.pData );
1032 osl_getSystemPathFromFileURL( aExeURL.pData, &aExe.pData );
1033 OString aByteExe( OUStringToOString( aExe, osl_getThreadTextEncoding() ) );
1035 #ifdef DEBUG
1036 aByteExe += OString ( " NSAccessibilityDebugLogLevel 1" );
1037 const char* pArgv[] = { aByteExe.getStr(), NULL };
1038 NSApplicationMain( 3, pArgv );
1039 #else
1040 const char* pArgv[] = { aByteExe.getStr(), nullptr };
1041 NSApplicationMain( 1, pArgv );
1042 #endif
1044 return true;
1047 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */