1 /**************************************************************
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 *************************************************************/
21
22
23
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_vcl.hxx"
26
27 #include <stdio.h>
28 #include <utility>
29
30 #include "tools/fsys.hxx"
31 #include "tools/getprocessworkingdir.hxx"
32 #include <tools/solarmutex.hxx>
33
34 #include "osl/process.h"
35
36 #include "rtl/ustrbuf.hxx"
37
38 #include "vcl/svapp.hxx"
39 #include "vcl/window.hxx"
40 #include "vcl/timer.hxx"
41
42 #include "aqua/saldata.hxx"
43 #include "aqua/salinst.h"
44 #include "aqua/salframe.h"
45 #include "aqua/salobj.h"
46 #include "aqua/salsys.h"
47 #include "aqua/salvd.h"
48 #include "aqua/salbmp.h"
49 #include "aqua/salprn.h"
50 #include "aqua/saltimer.h"
51 #include "aqua/vclnsapp.h"
52
53 #include "print.h"
54 #include "impbmp.hxx"
55 #include "salimestatus.hxx"
56
57 #include <comphelper/processfactory.hxx>
58
59 #include <com/sun/star/beans/XPropertySet.hpp>
60 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
61 #include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
62 #include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
63 #include <com/sun/star/uno/XComponentContext.hpp>
64
65 #include "premac.h"
66 #include <Foundation/Foundation.h>
67 #include <ApplicationServices/ApplicationServices.h>
68 #import "apple_remote/RemoteMainController.h"
69 #include "apple_remote/RemoteControl.h"
70 #include "postmac.h"
71
72 using namespace std;
73 using namespace ::com::sun::star;
74
75 extern sal_Bool ImplSVMain();
76
77 static sal_Bool* gpbInit = 0;
78 static NSMenu* pDockMenu = nil;
79 static bool bNoSVMain = true;
80 static bool bLeftMain = false;
81 // -----------------------------------------------------------------------
82
83 class AquaDelayedSettingsChanged : public Timer
84 {
85 bool mbInvalidate;
86 public:
AquaDelayedSettingsChanged(bool bInvalidate)87 AquaDelayedSettingsChanged( bool bInvalidate ) :
88 mbInvalidate( bInvalidate )
89 {
90 }
91
Timeout()92 virtual void Timeout()
93 {
94 SalData* pSalData = GetSalData();
95 if( ! pSalData->maFrames.empty() )
96 pSalData->maFrames.front()->CallCallback( SALEVENT_SETTINGSCHANGED, NULL );
97
98 if( mbInvalidate )
99 {
100 for( std::list< AquaSalFrame* >::iterator it = pSalData->maFrames.begin();
101 it != pSalData->maFrames.end(); ++it )
102 {
103 if( (*it)->mbShown )
104 (*it)->SendPaintEvent( NULL );
105 }
106 }
107 Stop();
108 delete this;
109 }
110 };
111
delayedSettingsChanged(bool bInvalidate)112 void AquaSalInstance::delayedSettingsChanged( bool bInvalidate )
113 {
114 vos::OGuard aGuard( *mpSalYieldMutex );
115 AquaDelayedSettingsChanged* pTimer = new AquaDelayedSettingsChanged( bInvalidate );
116 pTimer->SetTimeout( 50 );
117 pTimer->Start();
118 }
119
120
121 // the AppEventList must be available before any SalData/SalInst/etc. objects are ready
122 typedef std::list<const ApplicationEvent*> AppEventList;
123 AppEventList AquaSalInstance::aAppEventList;
124
GetDynamicDockMenu()125 NSMenu* AquaSalInstance::GetDynamicDockMenu()
126 {
127 if( ! pDockMenu && ! bLeftMain )
128 pDockMenu = [[NSMenu alloc] initWithTitle: @""];
129 return pDockMenu;
130 }
131
isOnCommandLine(const rtl::OUString & rArg)132 bool AquaSalInstance::isOnCommandLine( const rtl::OUString& rArg )
133 {
134 sal_uInt32 nArgs = osl_getCommandArgCount();
135 for( sal_uInt32 i = 0; i < nArgs; i++ )
136 {
137 rtl::OUString aArg;
138 osl_getCommandArg( i, &aArg.pData );
139 if( aArg.equals( rArg ) )
140 return true;
141 }
142 return false;
143 }
144
145
146 // initialize the cocoa VCL_NSApplication object
147 // returns an NSAutoreleasePool that must be released when the event loop begins
initNSApp()148 static void initNSApp()
149 {
150 // create our cocoa NSApplication
151 [VCL_NSApplication sharedApplication];
152
153 SalData::ensureThreadAutoreleasePool();
154
155 // put cocoa into multithreaded mode
156 [NSThread detachNewThreadSelector:@selector(enableCocoaThreads:) toTarget:[[CocoaThreadEnabler alloc] init] withObject:nil];
157
158 // activate our delegate methods
159 [NSApp setDelegate: NSApp];
160
161 [[NSNotificationCenter defaultCenter] addObserver: NSApp
162 selector: @selector(systemColorsChanged:)
163 name: NSSystemColorsDidChangeNotification
164 object: nil ];
165 [[NSNotificationCenter defaultCenter] addObserver: NSApp
166 selector: @selector(screenParametersChanged:)
167 name: NSApplicationDidChangeScreenParametersNotification
168 object: nil ];
169 // add observers for some settings changes that affect vcl's settings
170 // scrollbar variant
171 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
172 selector: @selector(scrollbarVariantChanged:)
173 name: @"AppleAquaScrollBarVariantChanged"
174 object: nil ];
175 // scrollbar page behavior ("jump to here" or not)
176 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
177 selector: @selector(scrollbarSettingsChanged:)
178 name: @"AppleNoRedisplayAppearancePreferenceChanged"
179 object: nil ];
180
181 // get System Version and store the value in GetSalData()->mnSystemVersion
182 SInt32 systemVersion = OSX_VER_LION; // initialize with the minimal requirement
183 const OSErr err = Gestalt( gestaltSystemVersion, &systemVersion);
184 if( err == noErr )
185 {
186 GetSalData()->mnSystemVersion = systemVersion;
187 #if OSL_DEBUG_LEVEL > 1
188 fprintf( stderr, "OSX System Version 0x%04x\n", (unsigned int)systemVersion);
189 #endif
190 }
191 else
192 NSLog(@"Unable to obtain system version: %ld", (long)err);
193
194 GetSalData()->mpAppleRemoteMainController = [[AppleRemoteMainController alloc] init];
195
196 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
197 selector: @selector(applicationWillBecomeActive:)
198 name: @"AppleRemoteWillBecomeActive"
199 object: nil ];
200
201 [[NSDistributedNotificationCenter defaultCenter] addObserver: NSApp
202 selector: @selector(applicationWillResignActive:)
203 name: @"AppleRemoteWillResignActive"
204 object: nil ];
205
206 if( ImplGetSVData()->mbIsTestTool )
207 [NSApp activateIgnoringOtherApps: YES];
208 }
209
ImplSVMainHook(sal_Bool * pbInit)210 sal_Bool ImplSVMainHook( sal_Bool * pbInit )
211 {
212 gpbInit = pbInit;
213
214 bNoSVMain = false;
215 initNSApp();
216
217 rtl::OUString aExeURL, aExe;
218 osl_getExecutableFile( &aExeURL.pData );
219 osl_getSystemPathFromFileURL( aExeURL.pData, &aExe.pData );
220 rtl::OString aByteExe( rtl::OUStringToOString( aExe, osl_getThreadTextEncoding() ) );
221
222 #ifdef DEBUG
223 aByteExe += OString ( " NSAccessibilityDebugLogLevel 1" );
224 const char* pArgv[] = { aByteExe.getStr(), NULL };
225 NSApplicationMain( 3, pArgv );
226 #else
227 const char* pArgv[] = { aByteExe.getStr(), NULL };
228 NSApplicationMain( 1, pArgv );
229 #endif
230
231 return TRUE; // indicate that ImplSVMainHook is implemented
232 }
233
234 // =======================================================================
235
SalAbort(const XubString & rErrorText)236 void SalAbort( const XubString& rErrorText )
237 {
238 if( !rErrorText.Len() )
239 fprintf( stderr, "Application Error " );
240 else
241 fprintf( stderr, "%s ",
242 ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() );
243 abort();
244 }
245
246 // -----------------------------------------------------------------------
247
InitSalData()248 void InitSalData()
249 {
250 SalData *pSalData = new SalData;
251 SetSalData( pSalData );
252 }
253
254 // -----------------------------------------------------------------------
255
SalGetDesktopEnvironment()256 const ::rtl::OUString& SalGetDesktopEnvironment()
257 {
258 static OUString aDesktopEnvironment(RTL_CONSTASCII_USTRINGPARAM( "MacOSX" ));
259 return aDesktopEnvironment;
260 }
261
262 // -----------------------------------------------------------------------
263
DeInitSalData()264 void DeInitSalData()
265 {
266 SalData *pSalData = GetSalData();
267 if( pSalData->mpStatusItem )
268 {
269 [pSalData->mpStatusItem release];
270 pSalData->mpStatusItem = nil;
271 }
272 delete pSalData;
273 SetSalData( NULL );
274 }
275
276 // -----------------------------------------------------------------------
277
278 extern "C" {
279 #include <crt_externs.h>
280 }
281
282 // -----------------------------------------------------------------------
283
InitSalMain()284 void InitSalMain()
285 {
286 rtl::OUString urlWorkDir;
287 rtl_uString *sysWorkDir = NULL;
288 if (tools::getProcessWorkingDir(&urlWorkDir))
289 {
290 oslFileError err2 = osl_getSystemPathFromFileURL(urlWorkDir.pData, &sysWorkDir);
291 if (err2 == osl_File_E_None)
292 {
293 ByteString aPath( getenv( "PATH" ) );
294 ByteString aResPath( getenv( "STAR_RESOURCEPATH" ) );
295 ByteString aLibPath( getenv( "DYLD_LIBRARY_PATH" ) );
296 ByteString aCmdPath( OUStringToOString(OUString(sysWorkDir), RTL_TEXTENCODING_UTF8).getStr() );
297 ByteString aTmpPath;
298 // Get absolute path of command's directory
299 if ( aCmdPath.Len() ) {
300 DirEntry aCmdDirEntry( aCmdPath );
301 aCmdDirEntry.ToAbs();
302 aCmdPath = ByteString( aCmdDirEntry.GetPath().GetFull(), RTL_TEXTENCODING_ASCII_US );
303 }
304 // Assign to PATH environment variable
305 if ( aCmdPath.Len() )
306 {
307 aTmpPath = aCmdPath;
308 if ( aPath.Len() )
309 aTmpPath += ByteString( DirEntry::GetSearchDelimiter(), RTL_TEXTENCODING_ASCII_US );
310 aTmpPath += aPath;
311 setenv( "PATH", aTmpPath.GetBuffer(), TRUE );
312 }
313 // Assign to STAR_RESOURCEPATH environment variable
314 if ( aCmdPath.Len() )
315 {
316 aTmpPath = aCmdPath;
317 if ( aResPath.Len() )
318 aTmpPath += ByteString( DirEntry::GetSearchDelimiter(), RTL_TEXTENCODING_ASCII_US );
319 aTmpPath += aResPath;
320 setenv( "STAR_RESOURCEPATH", aTmpPath.GetBuffer(), TRUE );
321 }
322 // Assign to DYLD_LIBRARY_PATH environment variable
323 if ( aCmdPath.Len() )
324 {
325 aTmpPath = aCmdPath;
326 if ( aLibPath.Len() )
327 aTmpPath += ByteString( DirEntry::GetSearchDelimiter(), RTL_TEXTENCODING_ASCII_US );
328 aTmpPath += aLibPath;
329 setenv( "DYLD_LIBRARY_PATH", aTmpPath.GetBuffer(), TRUE );
330 }
331 }
332 }
333 }
334
335 // -----------------------------------------------------------------------
336
DeInitSalMain()337 void DeInitSalMain()
338 {
339 }
340
341 // =======================================================================
342
postYieldWakeupEvent()343 static void postYieldWakeupEvent()
344 {
345 if( ! NSApp )
346 return;
347 SalData::ensureThreadAutoreleasePool();
348 NSEvent* pEvent = [NSEvent otherEventWithType: NSApplicationDefined
349 location: NSZeroPoint
350 modifierFlags: 0
351 timestamp: 0
352 windowNumber: 0
353 context: nil
354 subtype: AquaSalInstance::YieldWakeupEvent
355 data1: 0
356 data2: 0 ];
357 if( pEvent )
358 [NSApp postEvent: pEvent atStart: NO];
359 }
360
361 @interface SalMainThreadRunner : NSObject
362 {
363 }
364 -(void)runPending: (id)pUnused;
365 @end
366
367 @implementation SalMainThreadRunner
368 -(void)runPending: (id)pUnused
369 {
370 (void)pUnused;
371 GetSalData()->mpFirstInstance->mpSalYieldMutex->runPendingOnMainThread();
372 }
373 @end
374
SalYieldMutex()375 SalYieldMutex::SalYieldMutex()
376 {
377 mnCount = 0;
378 mnThreadId = 0;
379 mnMainThreadId = 0;
380 pthread_mutex_init( &maMainThreadMutex, NULL );
381 pthread_cond_init( &maMainThreadCond, NULL );
382 pthread_cond_init( &maResultCond, NULL );
383 mbWakeUpMain = false;
384 mbMainWaiting = false;
385 mbResultReady = false;
386 mpMainThreadFunc = NULL;
387 mbRunningForOwner = false;
388 }
389
~SalYieldMutex()390 SalYieldMutex::~SalYieldMutex()
391 {
392 pthread_cond_destroy( &maResultCond );
393 pthread_cond_destroy( &maMainThreadCond );
394 pthread_mutex_destroy( &maMainThreadMutex );
395 }
396
isMainThread() const397 bool SalYieldMutex::isMainThread() const
398 {
399 return mnMainThreadId != 0 && vos::OThread::getCurrentIdentifier() == mnMainThreadId;
400 }
401
acquire()402 void SalYieldMutex::acquire()
403 {
404 if( isMainThread() )
405 {
406 if( mbRunningForOwner )
407 return;
408 acquireOnMainThread();
409 }
410 else
411 OMutex::acquire();
412 mnThreadId = vos::OThread::getCurrentIdentifier();
413 mnCount++;
414 }
415
acquireOnMainThread()416 void SalYieldMutex::acquireOnMainThread()
417 {
418 // while another thread owns the mutex, run what it hands over via runOnMainThread()
419 for(;;)
420 {
421 pthread_mutex_lock( &maMainThreadMutex );
422 if( OMutex::tryToAcquire() )
423 {
424 mbWakeUpMain = false;
425 pthread_mutex_unlock( &maMainThreadMutex );
426 return;
427 }
428 mbMainWaiting = true;
429 while( ! mbWakeUpMain )
430 pthread_cond_wait( &maMainThreadCond, &maMainThreadMutex );
431 mbMainWaiting = false;
432 mbWakeUpMain = false;
433 const boost::function0<void>* pFunc = mpMainThreadFunc;
434 mpMainThreadFunc = NULL;
435 pthread_mutex_unlock( &maMainThreadMutex );
436
437 if( pFunc )
438 runForOwner( pFunc );
439 }
440 }
441
runPendingOnMainThread()442 void SalYieldMutex::runPendingOnMainThread()
443 {
444 if( ! isMainThread() || mbRunningForOwner )
445 return;
446
447 pthread_mutex_lock( &maMainThreadMutex );
448 const boost::function0<void>* pFunc = mpMainThreadFunc;
449 mpMainThreadFunc = NULL;
450 pthread_mutex_unlock( &maMainThreadMutex );
451
452 if( pFunc )
453 runForOwner( pFunc );
454 }
455
runForOwner(const boost::function0<void> * pFunc)456 void SalYieldMutex::runForOwner( const boost::function0<void>* pFunc )
457 {
458 std::exception_ptr aException;
459 mbRunningForOwner = true;
460 try
461 {
462 (*pFunc)();
463 }
464 catch( ... )
465 {
466 aException = std::current_exception();
467 }
468 mbRunningForOwner = false;
469
470 pthread_mutex_lock( &maMainThreadMutex );
471 maMainThreadException = aException;
472 mbResultReady = true;
473 pthread_cond_signal( &maResultCond );
474 pthread_mutex_unlock( &maMainThreadMutex );
475 }
476
release()477 void SalYieldMutex::release()
478 {
479 const bool bMainThread = isMainThread();
480 if( bMainThread && mbRunningForOwner )
481 return;
482
483 // the main thread may be waiting for this release in acquireOnMainThread()
484 if( ! bMainThread && mnCount == 1 && mnThreadId == vos::OThread::getCurrentIdentifier() )
485 {
486 pthread_mutex_lock( &maMainThreadMutex );
487 mnThreadId = 0;
488 mnCount--;
489 OMutex::release();
490 mbWakeUpMain = true;
491 pthread_cond_signal( &maMainThreadCond );
492 pthread_mutex_unlock( &maMainThreadMutex );
493 return;
494 }
495
496 if ( mnThreadId == vos::OThread::getCurrentIdentifier() )
497 {
498 if ( mnCount == 1 )
499 mnThreadId = 0;
500 mnCount--;
501 }
502 OMutex::release();
503 }
504
runOnMainThread(const boost::function0<void> & rFunc)505 void SalYieldMutex::runOnMainThread( const boost::function0<void>& rFunc )
506 {
507 if( isMainThread() )
508 {
509 rFunc();
510 return;
511 }
512
513 // the main thread only runs rFunc for the owner of the mutex
514 vos::OGuard aGuard( *this );
515
516 bool bMainWaiting;
517 pthread_mutex_lock( &maMainThreadMutex );
518 mpMainThreadFunc = &rFunc;
519 mbWakeUpMain = true;
520 bMainWaiting = mbMainWaiting;
521 pthread_cond_signal( &maMainThreadCond );
522 pthread_mutex_unlock( &maMainThreadMutex );
523
524 // common modes also reach a main thread inside AppKit's menu tracking or live resize loops
525 if( ! bMainWaiting )
526 {
527 static SalMainThreadRunner* pRunner = [[SalMainThreadRunner alloc] init];
528 [pRunner performSelectorOnMainThread: @selector(runPending:)
529 withObject: nil
530 waitUntilDone: NO
531 modes: [NSArray arrayWithObject: NSRunLoopCommonModes]];
532 }
533
534 std::exception_ptr aException;
535 pthread_mutex_lock( &maMainThreadMutex );
536 while( ! mbResultReady )
537 pthread_cond_wait( &maResultCond, &maMainThreadMutex );
538 mbResultReady = false;
539 std::swap( aException, maMainThreadException );
540 pthread_mutex_unlock( &maMainThreadMutex );
541
542 if( aException )
543 std::rethrow_exception( aException );
544 }
545
isRunningForOwner() const546 bool SalYieldMutex::isRunningForOwner() const
547 {
548 return isMainThread() && mbRunningForOwner;
549 }
550
tryToAcquire()551 sal_Bool SalYieldMutex::tryToAcquire()
552 {
553 if( isMainThread() && mbRunningForOwner )
554 return sal_True;
555 if ( OMutex::tryToAcquire() )
556 {
557 mnThreadId = vos::OThread::getCurrentIdentifier();
558 mnCount++;
559 return sal_True;
560 }
561 else
562 return sal_False;
563 }
564
565 // -----------------------------------------------------------------------
566
567 // some convenience functions regarding the yield mutex, aka solar mutex
568
ImplSalYieldMutexTryToAcquire()569 sal_Bool ImplSalYieldMutexTryToAcquire()
570 {
571 AquaSalInstance* pInst = (AquaSalInstance*) GetSalData()->mpFirstInstance;
572 if ( pInst )
573 return pInst->mpSalYieldMutex->tryToAcquire();
574 else
575 return FALSE;
576 }
577
ImplSalYieldMutexAcquire()578 void ImplSalYieldMutexAcquire()
579 {
580 AquaSalInstance* pInst = (AquaSalInstance*) GetSalData()->mpFirstInstance;
581 if ( pInst )
582 pInst->mpSalYieldMutex->acquire();
583 }
584
ImplSalYieldMutexRelease()585 void ImplSalYieldMutexRelease()
586 {
587 AquaSalInstance* pInst = (AquaSalInstance*) GetSalData()->mpFirstInstance;
588 if ( pInst )
589 pInst->mpSalYieldMutex->release();
590 }
591
592 // =======================================================================
593
CreateSalInstance()594 SalInstance* CreateSalInstance()
595 {
596 // this is the case for not using SVMain
597 // not so good
598 if( bNoSVMain )
599 initNSApp();
600
601 SalData* pSalData = GetSalData();
602 DBG_ASSERT( pSalData->mpFirstInstance == NULL, "more than one instance created" );
603 AquaSalInstance* pInst = new AquaSalInstance;
604
605 // init instance (only one instance in this version !!!)
606 pSalData->mpFirstInstance = pInst;
607 // this one is for outside AquaSalInstance::Yield
608 SalData::ensureThreadAutoreleasePool();
609 // no focus rects on NWF aqua
610 ImplGetSVData()->maNWFData.mbNoFocusRects = true;
611 ImplGetSVData()->maNWFData.mbNoBoldTabFocus = true;
612 ImplGetSVData()->maNWFData.mbNoActiveTabTextRaise = true;
613 ImplGetSVData()->maNWFData.mbCenteredTabs = true;
614 ImplGetSVData()->maNWFData.mbProgressNeedsErase = true;
615 ImplGetSVData()->maNWFData.mbCheckBoxNeedsErase = true;
616 ImplGetSVData()->maNWFData.mnStatusBarLowerRightOffset = 10;
617 ImplGetSVData()->maGDIData.mbNoXORClipping = true;
618 ImplGetSVData()->maWinData.mbNoSaveBackground = true;
619
620 return pInst;
621 }
622
623 // -----------------------------------------------------------------------
624
DestroySalInstance(SalInstance * pInst)625 void DestroySalInstance( SalInstance* pInst )
626 {
627 delete pInst;
628 }
629
630 // -----------------------------------------------------------------------
631
AquaSalInstance()632 AquaSalInstance::AquaSalInstance()
633 {
634 maMainThread = vos::OThread::getCurrentIdentifier();
635 mpSalYieldMutex = new SalYieldMutex;
636 mpSalYieldMutex->setMainThread( maMainThread );
637 mpSalYieldMutex->acquire();
638 ::tools::SolarMutex::SetSolarMutex( mpSalYieldMutex );
639 mbWaitingYield = false;
640 maUserEventListMutex = osl_createMutex();
641 mnActivePrintJobs = 0;
642 maWaitingYieldCond = osl_createCondition();
643 }
644
645 // -----------------------------------------------------------------------
646
~AquaSalInstance()647 AquaSalInstance::~AquaSalInstance()
648 {
649 ::tools::SolarMutex::SetSolarMutex( 0 );
650 mpSalYieldMutex->release();
651 delete mpSalYieldMutex;
652 osl_destroyMutex( maUserEventListMutex );
653 osl_destroyCondition( maWaitingYieldCond );
654 }
655
656 // -----------------------------------------------------------------------
657
wakeupYield()658 void AquaSalInstance::wakeupYield()
659 {
660 // wakeup :Yield
661 if( mbWaitingYield )
662 postYieldWakeupEvent();
663 }
664
665 // -----------------------------------------------------------------------
666
PostUserEvent(AquaSalFrame * pFrame,sal_uInt16 nType,void * pData)667 void AquaSalInstance::PostUserEvent( AquaSalFrame* pFrame, sal_uInt16 nType, void* pData )
668 {
669 osl_acquireMutex( maUserEventListMutex );
670 maUserEvents.push_back( SalUserEvent( pFrame, pData, nType ) );
671 osl_releaseMutex( maUserEventListMutex );
672
673 // notify main loop that an event has arrived
674 wakeupYield();
675 }
676
677 // -----------------------------------------------------------------------
678
GetYieldMutex()679 vos::IMutex* AquaSalInstance::GetYieldMutex()
680 {
681 return mpSalYieldMutex;
682 }
683
684 // -----------------------------------------------------------------------
685
ReleaseYieldMutex()686 sal_uLong AquaSalInstance::ReleaseYieldMutex()
687 {
688 SalYieldMutex* pYieldMutex = mpSalYieldMutex;
689 if ( pYieldMutex->GetThreadId() ==
690 vos::OThread::getCurrentIdentifier() )
691 {
692 sal_uLong nCount = pYieldMutex->GetAcquireCount();
693 sal_uLong n = nCount;
694 while ( n )
695 {
696 pYieldMutex->release();
697 n--;
698 }
699
700 return nCount;
701 }
702 else
703 return 0;
704 }
705
706 // -----------------------------------------------------------------------
707
AcquireYieldMutex(sal_uLong nCount)708 void AquaSalInstance::AcquireYieldMutex( sal_uLong nCount )
709 {
710 SalYieldMutex* pYieldMutex = mpSalYieldMutex;
711 while ( nCount )
712 {
713 pYieldMutex->acquire();
714 nCount--;
715 }
716 }
717
718 // -----------------------------------------------------------------------
719
CheckYieldMutex()720 bool AquaSalInstance::CheckYieldMutex()
721 {
722 bool bRet = true;
723
724 if( mpSalYieldMutex->isRunningForOwner() )
725 return bRet;
726
727 SalYieldMutex* pYieldMutex = mpSalYieldMutex;
728 if ( pYieldMutex->GetThreadId() !=
729 vos::OThread::getCurrentIdentifier() )
730 {
731 bRet = false;
732 }
733
734 return bRet;
735 }
736
737 // -----------------------------------------------------------------------
738
isNSAppThread() const739 bool AquaSalInstance::isNSAppThread() const
740 {
741 return vos::OThread::getCurrentIdentifier() == maMainThread;
742 }
743
744 // -----------------------------------------------------------------------
745
forwardToMainThread(const boost::function0<void> & rFunc)746 bool AquaSalInstance::forwardToMainThread( const boost::function0<void>& rFunc )
747 {
748 if( isNSAppThread() )
749 return false;
750 mpSalYieldMutex->runOnMainThread( rFunc );
751 return true;
752 }
753
754 // -----------------------------------------------------------------------
755
handleAppDefinedEvent(NSEvent * pEvent)756 void AquaSalInstance::handleAppDefinedEvent( NSEvent* pEvent )
757 {
758 switch( [pEvent subtype] )
759 {
760 case AppStartTimerEvent:
761 AquaSalTimer::handleStartTimerEvent( pEvent );
762 break;
763 case AppEndLoopEvent:
764 [NSApp stop: NSApp];
765 break;
766 case AppExecuteSVMain:
767 {
768 sal_Bool bResult = ImplSVMain();
769 if( gpbInit )
770 *gpbInit = bResult;
771 [NSApp stop: NSApp];
772 bLeftMain = true;
773 if( pDockMenu )
774 {
775 [pDockMenu release];
776 pDockMenu = nil;
777 }
778 }
779 break;
780 case AppleRemoteEvent:
781 {
782 sal_Int16 nCommand = 0;
783 SalData* pSalData = GetSalData();
784 bool bIsFullScreenMode = false;
785
786 std::list<AquaSalFrame*>::iterator it = pSalData->maFrames.begin();
787 for(; it != pSalData->maFrames.end(); ++it )
788 {
789 if( (*it)->mbFullScreen )
790 bIsFullScreenMode = true;
791 }
792
793 switch ([pEvent data1])
794 {
795 case kRemoteButtonPlay:
796 nCommand = ( bIsFullScreenMode == true ) ? MEDIA_COMMAND_PLAY_PAUSE : MEDIA_COMMAND_PLAY;
797 break;
798
799 // kept for experimentation purpose (scheduled for future implementation)
800 // case kRemoteButtonMenu: nCommand = MEDIA_COMMAND_MENU; break;
801
802 case kRemoteButtonPlus: nCommand = MEDIA_COMMAND_VOLUME_UP; break;
803
804 case kRemoteButtonMinus: nCommand = MEDIA_COMMAND_VOLUME_DOWN; break;
805
806 case kRemoteButtonRight: nCommand = MEDIA_COMMAND_NEXTTRACK; break;
807
808 case kRemoteButtonRight_Hold: nCommand = MEDIA_COMMAND_NEXTTRACK_HOLD; break;
809
810 case kRemoteButtonLeft: nCommand = MEDIA_COMMAND_PREVIOUSTRACK; break;
811
812 case kRemoteButtonLeft_Hold: nCommand = MEDIA_COMMAND_REWIND; break;
813
814 case kRemoteButtonPlay_Hold: nCommand = MEDIA_COMMAND_PLAY_HOLD; break;
815
816 case kRemoteButtonMenu_Hold: nCommand = MEDIA_COMMAND_STOP; break;
817
818 // FIXME : not detected
819 case kRemoteButtonPlus_Hold:
820 case kRemoteButtonMinus_Hold:
821 break;
822
823 default:
824 break;
825 }
826 AquaSalFrame* pFrame = pSalData->maFrames.front();
827 Window* pWindow = pFrame ? pFrame->GetWindow() : NULL;
828
829 if( pWindow )
830 {
831 const Point aPoint;
832 CommandEvent aCEvt( aPoint, COMMAND_MEDIA, FALSE, &nCommand );
833 NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt );
834
835 if ( !ImplCallPreNotify( aNCmdEvt ) )
836 pWindow->Command( aCEvt );
837 }
838
839 }
840 break;
841
842 case YieldWakeupEvent:
843 // do nothing, fall out of Yield
844 break;
845
846 default:
847 DBG_ERROR( "unhandled NSApplicationDefined event" );
848 break;
849 };
850 }
851
852 // -----------------------------------------------------------------------
853
854 class ReleasePoolHolder
855 {
856 NSAutoreleasePool* mpPool;
857 public:
ReleasePoolHolder()858 ReleasePoolHolder() : mpPool( [[NSAutoreleasePool alloc] init] ) {}
~ReleasePoolHolder()859 ~ReleasePoolHolder() { [mpPool release]; }
860 };
861
Yield(bool bWait,bool bHandleAllCurrentEvents)862 void AquaSalInstance::Yield( bool bWait, bool bHandleAllCurrentEvents )
863 {
864 // ensure that the per thread autorelease pool is top level and
865 // will therefore not be destroyed by cocoa implicitly
866 SalData::ensureThreadAutoreleasePool();
867
868 // NSAutoreleasePool documentation suggests we should have
869 // an own pool for each yield level
870 ReleasePoolHolder aReleasePool;
871
872 // Release all locks so that we don't deadlock when we pull pending
873 // events from the event queue
874 bool bDispatchUser = true;
875 while( bDispatchUser )
876 {
877 sal_uLong nCount = ReleaseYieldMutex();
878
879 // get one user event
880 osl_acquireMutex( maUserEventListMutex );
881 SalUserEvent aEvent( NULL, NULL, 0 );
882 if( ! maUserEvents.empty() )
883 {
884 aEvent = maUserEvents.front();
885 maUserEvents.pop_front();
886 }
887 else
888 bDispatchUser = false;
889 osl_releaseMutex( maUserEventListMutex );
890
891 AcquireYieldMutex( nCount );
892
893 // dispatch it
894 if( aEvent.mpFrame && AquaSalFrame::isAlive( aEvent.mpFrame ) )
895 {
896 aEvent.mpFrame->CallCallback( aEvent.mnType, aEvent.mpData );
897 osl_setCondition( maWaitingYieldCond );
898 // return if only one event is asked for
899 if( ! bHandleAllCurrentEvents )
900 return;
901 }
902 }
903
904 // handle cocoa event queue
905 // cocoa events mye be only handled in the thread the NSApp was created
906 if( isNSAppThread() && mnActivePrintJobs == 0 )
907 {
908 // we need to be woken up by a cocoa-event
909 // if a user event should be posted by the event handling below
910 bool bOldWaitingYield = mbWaitingYield;
911 mbWaitingYield = bWait;
912
913 // handle available events
914 NSEvent* pEvent = nil;
915 bool bHadEvent = false;
916 do
917 {
918 sal_uLong nCount = ReleaseYieldMutex();
919
920 pEvent = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: nil
921 inMode: NSDefaultRunLoopMode dequeue: YES];
922 if( pEvent )
923 {
924 [NSApp sendEvent: pEvent];
925 bHadEvent = true;
926 }
927 [NSApp updateWindows];
928
929 AcquireYieldMutex( nCount );
930 } while( bHandleAllCurrentEvents && pEvent );
931
932 // if we had no event yet, wait for one if requested
933 if( bWait && ! bHadEvent )
934 {
935 sal_uLong nCount = ReleaseYieldMutex();
936
937 NSDate* pDt = AquaSalTimer::pRunningTimer ? [AquaSalTimer::pRunningTimer fireDate] : [NSDate distantFuture];
938 pEvent = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: pDt
939 inMode: NSDefaultRunLoopMode dequeue: YES];
940 if( pEvent )
941 [NSApp sendEvent: pEvent];
942 [NSApp updateWindows];
943
944 AcquireYieldMutex( nCount );
945
946 // #i86581#
947 // FIXME: sometimes the NSTimer will never fire. Firing it by hand then
948 // fixes the problem even seems to set the correct next firing date
949 // Why oh why ?
950 if( ! pEvent && AquaSalTimer::pRunningTimer )
951 {
952 // this cause crashes on MacOSX 10.4
953 // [AquaSalTimer::pRunningTimer fire];
954 ImplGetSVData()->mpSalTimer->CallCallback();
955 }
956 }
957
958 mbWaitingYield = bOldWaitingYield;
959
960 // collect update rectangles
961 const std::list< AquaSalFrame* > rFrames( GetSalData()->maFrames );
962 for( std::list< AquaSalFrame* >::const_iterator it = rFrames.begin(); it != rFrames.end(); ++it )
963 {
964 if( (*it)->mbShown && ! (*it)->maInvalidRect.IsEmpty() )
965 {
966 (*it)->Flush( (*it)->maInvalidRect );
967 (*it)->maInvalidRect.SetEmpty();
968 }
969 }
970 osl_setCondition( maWaitingYieldCond );
971 }
972 else if( bWait )
973 {
974 // #i103162#
975 // wait until any thread (most likely the main thread)
976 // has dispatched an event, cop out at 250 ms
977 TimeValue aVal = { 0, 250000000 };
978 osl_resetCondition( maWaitingYieldCond );
979 sal_uLong nCount = ReleaseYieldMutex();
980 osl_waitCondition( maWaitingYieldCond, &aVal );
981 AcquireYieldMutex( nCount );
982 }
983 // we get some apple events way too early
984 // before the application is ready to handle them,
985 // so their corresponding application events need to be delayed
986 // now is a good time to handle at least one of them
987 if( bWait && !aAppEventList.empty() && ImplGetSVData()->maAppData.mbInAppExecute )
988 {
989 // make sure that only one application event is active at a time
990 static bool bInAppEvent = false;
991 if( !bInAppEvent )
992 {
993 bInAppEvent = true;
994 // get the next delayed application event
995 const ApplicationEvent* pAppEvent = aAppEventList.front();
996 aAppEventList.pop_front();
997 // handle one application event (no recursion)
998 const ImplSVData* pSVData = ImplGetSVData();
999 pSVData->mpApp->AppEvent( *pAppEvent );
1000 delete pAppEvent;
1001 // allow the next delayed application event
1002 bInAppEvent = false;
1003 }
1004 }
1005 }
1006
1007 // -----------------------------------------------------------------------
1008
AnyInput(sal_uInt16 nType)1009 bool AquaSalInstance::AnyInput( sal_uInt16 nType )
1010 {
1011 if( ! isNSAppThread() )
1012 return callOnMainThread< bool >( boost::bind( &AquaSalInstance::AnyInput, this, nType ) );
1013
1014 if( nType & INPUT_APPEVENT )
1015 {
1016 if( ! aAppEventList.empty() )
1017 return true;
1018 if( nType == INPUT_APPEVENT )
1019 return false;
1020 }
1021
1022 if( nType & INPUT_TIMER )
1023 {
1024 if( AquaSalTimer::pRunningTimer )
1025 {
1026 NSDate* pDt = [AquaSalTimer::pRunningTimer fireDate];
1027 if( pDt && [pDt timeIntervalSinceNow] < 0 )
1028 {
1029 return true;
1030 }
1031 }
1032 }
1033
1034 unsigned/*NSUInteger*/ nEventMask = 0;
1035 if( nType & INPUT_MOUSE)
1036 nEventMask |=
1037 NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask |
1038 NSLeftMouseUpMask | NSRightMouseUpMask | NSOtherMouseUpMask |
1039 NSLeftMouseDraggedMask | NSRightMouseDraggedMask | NSOtherMouseDraggedMask |
1040 NSScrollWheelMask |
1041 // NSMouseMovedMask |
1042 NSMouseEnteredMask | NSMouseExitedMask;
1043 if( nType & INPUT_KEYBOARD)
1044 nEventMask |= NSKeyDownMask | NSKeyUpMask | NSFlagsChangedMask;
1045 if( nType & INPUT_OTHER)
1046 nEventMask |= NSTabletPoint;
1047 // TODO: INPUT_PAINT / more INPUT_OTHER
1048 if( !nType)
1049 return false;
1050
1051 NSEvent* pEvent = [NSApp nextEventMatchingMask: nEventMask untilDate: nil
1052 inMode: NSDefaultRunLoopMode dequeue: NO];
1053 return (pEvent != NULL);
1054 }
1055
1056 // -----------------------------------------------------------------------
1057
CreateChildFrame(SystemParentData *,sal_uLong)1058 SalFrame* AquaSalInstance::CreateChildFrame( SystemParentData*, sal_uLong /*nSalFrameStyle*/ )
1059 {
1060 return NULL;
1061 }
1062
1063 // -----------------------------------------------------------------------
1064
CreateFrame(SalFrame * pParent,sal_uLong nSalFrameStyle)1065 SalFrame* AquaSalInstance::CreateFrame( SalFrame* pParent, sal_uLong nSalFrameStyle )
1066 {
1067 SalData::ensureThreadAutoreleasePool();
1068
1069 SalFrame* pFrame = new AquaSalFrame( pParent, nSalFrameStyle );
1070 return pFrame;
1071 }
1072
1073 // -----------------------------------------------------------------------
1074
DestroyFrame(SalFrame * pFrame)1075 void AquaSalInstance::DestroyFrame( SalFrame* pFrame )
1076 {
1077 if( forwardToMainThread( boost::bind( &AquaSalInstance::DestroyFrame, this, pFrame ) ) )
1078 return;
1079 delete pFrame;
1080 }
1081
1082 // -----------------------------------------------------------------------
1083
CreateObject(SalFrame * pParent,SystemWindowData *,sal_Bool)1084 SalObject* AquaSalInstance::CreateObject( SalFrame* pParent, SystemWindowData* /* pWindowData */, sal_Bool /* bShow */ )
1085 {
1086 // SystemWindowData is meaningless on Mac OS X
1087 AquaSalObject *pObject = NULL;
1088
1089 if ( pParent )
1090 pObject = new AquaSalObject( static_cast<AquaSalFrame*>(pParent) );
1091
1092 return pObject;
1093 }
1094
1095 // -----------------------------------------------------------------------
1096
DestroyObject(SalObject * pObject)1097 void AquaSalInstance::DestroyObject( SalObject* pObject )
1098 {
1099 delete ( pObject );
1100 }
1101
1102 // -----------------------------------------------------------------------
1103
CreatePrinter(SalInfoPrinter * pInfoPrinter)1104 SalPrinter* AquaSalInstance::CreatePrinter( SalInfoPrinter* pInfoPrinter )
1105 {
1106 return new AquaSalPrinter( dynamic_cast<AquaSalInfoPrinter*>(pInfoPrinter) );
1107 }
1108
1109 // -----------------------------------------------------------------------
1110
DestroyPrinter(SalPrinter * pPrinter)1111 void AquaSalInstance::DestroyPrinter( SalPrinter* pPrinter )
1112 {
1113 delete pPrinter;
1114 }
1115
1116 // -----------------------------------------------------------------------
1117
GetPrinterQueueInfo(ImplPrnQueueList * pList)1118 void AquaSalInstance::GetPrinterQueueInfo( ImplPrnQueueList* pList )
1119 {
1120 NSArray* pNames = [NSPrinter printerNames];
1121 NSArray* pTypes = [NSPrinter printerTypes];
1122 unsigned int nNameCount = pNames ? [pNames count] : 0;
1123 unsigned int nTypeCount = pTypes ? [pTypes count] : 0;
1124 DBG_ASSERT( nTypeCount == nNameCount, "type count not equal to printer count" );
1125 for( unsigned int i = 0; i < nNameCount; i++ )
1126 {
1127 NSString* pName = [pNames objectAtIndex: i];
1128 NSString* pType = i < nTypeCount ? [pTypes objectAtIndex: i] : nil;
1129 if( pName )
1130 {
1131 SalPrinterQueueInfo* pInfo = new SalPrinterQueueInfo;
1132 pInfo->maPrinterName = GetOUString( pName );
1133 if( pType )
1134 pInfo->maDriver = GetOUString( pType );
1135 pInfo->mnStatus = 0;
1136 pInfo->mnJobs = 0;
1137 pInfo->mpSysData = NULL;
1138
1139 pList->Add( pInfo );
1140 }
1141 }
1142 }
1143
1144 // -----------------------------------------------------------------------
1145
GetPrinterQueueState(SalPrinterQueueInfo *)1146 void AquaSalInstance::GetPrinterQueueState( SalPrinterQueueInfo* )
1147 {
1148 }
1149
1150 // -----------------------------------------------------------------------
1151
DeletePrinterQueueInfo(SalPrinterQueueInfo * pInfo)1152 void AquaSalInstance::DeletePrinterQueueInfo( SalPrinterQueueInfo* pInfo )
1153 {
1154 delete pInfo;
1155 }
1156
1157 // -----------------------------------------------------------------------
1158
GetDefaultPrinter()1159 XubString AquaSalInstance::GetDefaultPrinter()
1160 {
1161 // #i113170# may not be the main thread if called from UNO API
1162 SalData::ensureThreadAutoreleasePool();
1163
1164 if( ! maDefaultPrinter.getLength() )
1165 {
1166 NSPrintInfo* pPI = [NSPrintInfo sharedPrintInfo];
1167 DBG_ASSERT( pPI, "no print info" );
1168 if( pPI )
1169 {
1170 NSPrinter* pPr = [pPI printer];
1171 DBG_ASSERT( pPr, "no printer in default info" );
1172 if( pPr )
1173 {
1174 NSString* pDefName = [pPr name];
1175 DBG_ASSERT( pDefName, "printer has no name" );
1176 maDefaultPrinter = GetOUString( pDefName );
1177 }
1178 }
1179 }
1180 return maDefaultPrinter;
1181 }
1182
1183 // -----------------------------------------------------------------------
1184
CreateInfoPrinter(SalPrinterQueueInfo * pQueueInfo,ImplJobSetup * pSetupData)1185 SalInfoPrinter* AquaSalInstance::CreateInfoPrinter( SalPrinterQueueInfo* pQueueInfo,
1186 ImplJobSetup* pSetupData )
1187 {
1188 // #i113170# may not be the main thread if called from UNO API
1189 SalData::ensureThreadAutoreleasePool();
1190
1191 SalInfoPrinter* pNewInfoPrinter = NULL;
1192 if( pQueueInfo )
1193 {
1194 pNewInfoPrinter = new AquaSalInfoPrinter( *pQueueInfo );
1195 if( pSetupData )
1196 pNewInfoPrinter->SetPrinterData( pSetupData );
1197 }
1198
1199 return pNewInfoPrinter;
1200 }
1201
1202 // -----------------------------------------------------------------------
1203
DestroyInfoPrinter(SalInfoPrinter * pPrinter)1204 void AquaSalInstance::DestroyInfoPrinter( SalInfoPrinter* pPrinter )
1205 {
1206 // #i113170# may not be the main thread if called from UNO API
1207 SalData::ensureThreadAutoreleasePool();
1208
1209 delete pPrinter;
1210 }
1211
1212 // -----------------------------------------------------------------------
1213
CreateSystem()1214 SalSystem* AquaSalInstance::CreateSystem()
1215 {
1216 return new AquaSalSystem();
1217 }
1218
1219 // -----------------------------------------------------------------------
1220
DestroySystem(SalSystem * pSystem)1221 void AquaSalInstance::DestroySystem( SalSystem* pSystem )
1222 {
1223 delete pSystem;
1224 }
1225
1226 // -----------------------------------------------------------------------
1227
SetEventCallback(void *,bool (*)(void *,void *,int))1228 void AquaSalInstance::SetEventCallback( void*, bool(*)(void*,void*,int) )
1229 {
1230 }
1231
1232 // -----------------------------------------------------------------------
1233
SetErrorEventCallback(void *,bool (*)(void *,void *,int))1234 void AquaSalInstance::SetErrorEventCallback( void*, bool(*)(void*,void*,int) )
1235 {
1236 }
1237
1238 // -----------------------------------------------------------------------
1239
GetConnectionIdentifier(ConnectionIdentifierType & rReturnedType,int & rReturnedBytes)1240 void* AquaSalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )
1241 {
1242 rReturnedBytes = 1;
1243 rReturnedType = AsciiCString;
1244 return (void*)"";
1245 }
1246
1247 // We need to re-encode file urls because osl_getFileURLFromSystemPath converts
1248 // to UTF-8 before encoding non ascii characters, which is not what other apps expect.
translateToExternalUrl(const rtl::OUString & internalUrl)1249 static rtl::OUString translateToExternalUrl(const rtl::OUString& internalUrl)
1250 {
1251 rtl::OUString extUrl;
1252
1253 uno::Reference< lang::XMultiServiceFactory > sm = comphelper::getProcessServiceFactory();
1254 if (sm.is())
1255 {
1256 uno::Reference< beans::XPropertySet > pset;
1257 sm->queryInterface( getCppuType( &pset )) >>= pset;
1258 if (pset.is())
1259 {
1260 uno::Reference< uno::XComponentContext > context;
1261 static const rtl::OUString DEFAULT_CONTEXT( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) );
1262 pset->getPropertyValue(DEFAULT_CONTEXT) >>= context;
1263 if (context.is())
1264 extUrl = uri::ExternalUriReferenceTranslator::create(context)->translateToExternal(internalUrl);
1265 }
1266 }
1267 return extUrl;
1268 }
1269
1270 // #i104525# many versions of OSX have problems with some URLs:
1271 // when an app requests OSX to add one of these URLs to the "Recent Items" list
1272 // then this app gets killed (TextEdit, Preview, etc. and also OOo)
isDangerousUrl(const rtl::OUString & rUrl)1273 static bool isDangerousUrl( const rtl::OUString& rUrl )
1274 {
1275 // use a heuristic that detects all known cases since there is no official comment
1276 // on the exact impact and root cause of the OSX bug
1277 const int nLen = rUrl.getLength();
1278 const sal_Unicode* p = rUrl.getStr();
1279 for( int i = 0; i < nLen-3; ++i, ++p ) {
1280 if( p[0] != '%' )
1281 continue;
1282 // escaped percent?
1283 if( (p[1] == '2') && (p[2] == '5') )
1284 return true;
1285 // escapes are considered to be UTF-8 encoded
1286 // => check for invalid UTF-8 leading byte
1287 if( (p[1] != 'f') && (p[1] != 'F') )
1288 continue;
1289 int cLowNibble = p[2];
1290 if( (cLowNibble >= '0' ) && (cLowNibble <= '9'))
1291 return false;
1292 if( cLowNibble >= 'a' )
1293 cLowNibble -= 'a' - 'A';
1294 if( (cLowNibble < 'A') || (cLowNibble >= 'C'))
1295 return true;
1296 }
1297
1298 return false;
1299 }
1300
AddToRecentDocumentList(const rtl::OUString & rFileUrl,const rtl::OUString &)1301 void AquaSalInstance::AddToRecentDocumentList(const rtl::OUString& rFileUrl, const rtl::OUString& /*rMimeType*/)
1302 {
1303 // Convert file URL for external use (see above)
1304 rtl::OUString externalUrl = translateToExternalUrl(rFileUrl);
1305 if( 0 == externalUrl.getLength() )
1306 externalUrl = rFileUrl;
1307
1308 if( externalUrl.getLength() && !isDangerousUrl( externalUrl ) )
1309 {
1310 NSString* pString = CreateNSString( externalUrl );
1311 NSURL* pURL = [NSURL URLWithString: pString];
1312
1313 if( pURL )
1314 {
1315 NSDocumentController* pCtrl = [NSDocumentController sharedDocumentController];
1316 [pCtrl noteNewRecentDocumentURL: pURL];
1317 }
1318 if( pString )
1319 [pString release];
1320 }
1321 }
1322
1323
1324 // -----------------------------------------------------------------------
1325
CreateSalTimer()1326 SalTimer* AquaSalInstance::CreateSalTimer()
1327 {
1328 return new AquaSalTimer();
1329 }
1330
1331 // -----------------------------------------------------------------------
1332
CreateSalSystem()1333 SalSystem* AquaSalInstance::CreateSalSystem()
1334 {
1335 return new AquaSalSystem();
1336 }
1337
1338 // -----------------------------------------------------------------------
1339
CreateSalBitmap()1340 SalBitmap* AquaSalInstance::CreateSalBitmap()
1341 {
1342 return new AquaSalBitmap();
1343 }
1344
1345 // -----------------------------------------------------------------------
1346
CreateSalSession()1347 SalSession* AquaSalInstance::CreateSalSession()
1348 {
1349 return NULL;
1350 }
1351
1352 // -----------------------------------------------------------------------
1353
1354 class MacImeStatus : public SalI18NImeStatus
1355 {
1356 public:
MacImeStatus()1357 MacImeStatus() {}
~MacImeStatus()1358 virtual ~MacImeStatus() {}
1359
1360 // asks whether there is a status window available
1361 // to toggle into menubar
canToggle()1362 virtual bool canToggle() { return false; }
toggle()1363 virtual void toggle() {}
1364 };
1365
1366 // -----------------------------------------------------------------------
1367
CreateI18NImeStatus()1368 SalI18NImeStatus* AquaSalInstance::CreateI18NImeStatus()
1369 {
1370 return new MacImeStatus();
1371 }
1372
1373 // YieldMutexReleaser
YieldMutexReleaser()1374 YieldMutexReleaser::YieldMutexReleaser() : mnCount( 0 )
1375 {
1376 SalData* pSalData = GetSalData();
1377 if( ! pSalData->mpFirstInstance->isNSAppThread() )
1378 {
1379 SalData::ensureThreadAutoreleasePool();
1380 mnCount = pSalData->mpFirstInstance->ReleaseYieldMutex();
1381 }
1382 }
1383
~YieldMutexReleaser()1384 YieldMutexReleaser::~YieldMutexReleaser()
1385 {
1386 if( mnCount != 0 )
1387 GetSalData()->mpFirstInstance->AcquireYieldMutex( mnCount );
1388 }
1389
1390 //////////////////////////////////////////////////////////////
GetOUString(CFStringRef rStr)1391 rtl::OUString GetOUString( CFStringRef rStr )
1392 {
1393 if( rStr == 0 )
1394 return rtl::OUString();
1395 CFIndex nLength = CFStringGetLength( rStr );
1396 if( nLength == 0 )
1397 return rtl::OUString();
1398 const UniChar* pConstStr = CFStringGetCharactersPtr( rStr );
1399 if( pConstStr )
1400 return rtl::OUString( pConstStr, nLength );
1401 UniChar* pStr = reinterpret_cast<UniChar*>( rtl_allocateMemory( sizeof(UniChar)*nLength ) );
1402 CFRange aRange = { 0, nLength };
1403 CFStringGetCharacters( rStr, aRange, pStr );
1404 rtl::OUString aRet( pStr, nLength );
1405 rtl_freeMemory( pStr );
1406 return aRet;
1407 }
1408
GetOUString(NSString * pStr)1409 rtl::OUString GetOUString( NSString* pStr )
1410 {
1411 if( ! pStr )
1412 return rtl::OUString();
1413 int nLen = [pStr length];
1414 if( nLen == 0 )
1415 return rtl::OUString();
1416
1417 rtl::OUStringBuffer aBuf( nLen+1 );
1418 aBuf.setLength( nLen );
1419 [pStr getCharacters: const_cast<sal_Unicode*>(aBuf.getStr())];
1420 return aBuf.makeStringAndClear();
1421 }
1422
CreateCFString(const rtl::OUString & rStr)1423 CFStringRef CreateCFString( const rtl::OUString& rStr )
1424 {
1425 return CFStringCreateWithCharacters(kCFAllocatorDefault, rStr.getStr(), rStr.getLength() );
1426 }
1427
CreateNSString(const rtl::OUString & rStr)1428 NSString* CreateNSString( const rtl::OUString& rStr )
1429 {
1430 return [[NSString alloc] initWithCharacters: rStr.getStr() length: rStr.getLength()];
1431 }
1432
CreateCGImage(const Image & rImage)1433 CGImageRef CreateCGImage( const Image& rImage )
1434 {
1435 BitmapEx aBmpEx( rImage.GetBitmapEx() );
1436 Bitmap aBmp( aBmpEx.GetBitmap() );
1437
1438 if( ! aBmp || ! aBmp.ImplGetImpBitmap() )
1439 return NULL;
1440
1441 // simple case, no transparency
1442 AquaSalBitmap* pSalBmp = static_cast<AquaSalBitmap*>(aBmp.ImplGetImpBitmap()->ImplGetSalBitmap());
1443
1444 if( ! pSalBmp )
1445 return NULL;
1446
1447 CGImageRef xImage = NULL;
1448 if( ! (aBmpEx.IsAlpha() || aBmpEx.IsTransparent() ) )
1449 xImage = pSalBmp->CreateCroppedImage( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1450 else if( aBmpEx.IsAlpha() )
1451 {
1452 AlphaMask aAlphaMask( aBmpEx.GetAlpha() );
1453 Bitmap aMask( aAlphaMask.GetBitmap() );
1454 AquaSalBitmap* pMaskBmp = static_cast<AquaSalBitmap*>(aMask.ImplGetImpBitmap()->ImplGetSalBitmap());
1455 if( pMaskBmp )
1456 xImage = pSalBmp->CreateWithMask( *pMaskBmp, 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1457 else
1458 xImage = pSalBmp->CreateCroppedImage( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1459 }
1460 else if( aBmpEx.GetTransparentType() == TRANSPARENT_BITMAP )
1461 {
1462 Bitmap aMask( aBmpEx.GetMask() );
1463 AquaSalBitmap* pMaskBmp = static_cast<AquaSalBitmap*>(aMask.ImplGetImpBitmap()->ImplGetSalBitmap());
1464 if( pMaskBmp )
1465 xImage = pSalBmp->CreateWithMask( *pMaskBmp, 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1466 else
1467 xImage = pSalBmp->CreateCroppedImage( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight );
1468 }
1469 else if( aBmpEx.GetTransparentType() == TRANSPARENT_COLOR )
1470 {
1471 Color aTransColor( aBmpEx.GetTransparentColor() );
1472 SalColor nTransColor = MAKE_SALCOLOR( aTransColor.GetRed(), aTransColor.GetGreen(), aTransColor.GetBlue() );
1473 xImage = pSalBmp->CreateColorMask( 0, 0, pSalBmp->mnWidth, pSalBmp->mnHeight, nTransColor );
1474 }
1475
1476 return xImage;
1477 }
1478
CreateNSImage(const Image & rImage)1479 NSImage* CreateNSImage( const Image& rImage )
1480 {
1481 CGImageRef xImage = CreateCGImage( rImage );
1482
1483 if( ! xImage )
1484 return nil;
1485
1486 Size aSize( rImage.GetSizePixel() );
1487 NSImage* pImage = [[NSImage alloc] initWithSize: NSMakeSize( aSize.Width(), aSize.Height() )];
1488 if( pImage )
1489 {
1490 [pImage setFlipped: YES];
1491 [pImage lockFocus];
1492
1493 NSGraphicsContext* pContext = [NSGraphicsContext currentContext];
1494 CGContextRef rCGContext = reinterpret_cast<CGContextRef>([pContext graphicsPort]);
1495
1496 const CGRect aDstRect = CGRectMake( 0, 0, aSize.Width(), aSize.Height());
1497 CGContextDrawImage( rCGContext, aDstRect, xImage );
1498
1499 [pImage unlockFocus];
1500 }
1501
1502 CGImageRelease( xImage );
1503
1504 return pImage;
1505 }
1506