1 /*
   2  * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "splashscreen_impl.h"
  27 
  28 #import <Cocoa/Cocoa.h>
  29 #import <objc/objc-auto.h>
  30 
  31 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  32 #import "NSApplicationAWT.h"
  33 
  34 #include <sys/time.h>
  35 #include <pthread.h>
  36 #include <iconv.h>
  37 #include <langinfo.h>
  38 #include <locale.h>
  39 #include <fcntl.h>
  40 #include <poll.h>
  41 #include <errno.h>
  42 #include <sys/types.h>
  43 #include <signal.h>
  44 #include <unistd.h>
  45 #include <dlfcn.h>
  46 
  47 #include <sizecalc.h>
  48 #import "ThreadUtilities.h"
  49 
  50 static NSScreen* SplashNSScreen()
  51 {
  52     return [[NSScreen screens] objectAtIndex: 0];
  53 }
  54 
  55 static void SplashCenter(Splash * splash)
  56 {
  57     NSRect screenFrame = [SplashNSScreen() frame];
  58 
  59     splash->x = (screenFrame.size.width - splash->width) / 2;
  60     splash->y = (screenFrame.size.height - splash->height) / 2 + screenFrame.origin.y;
  61 }
  62 
  63 unsigned
  64 SplashTime(void) {
  65     struct timeval tv;
  66     struct timezone tz;
  67     unsigned long long msec;
  68 
  69     gettimeofday(&tv, &tz);
  70     msec = (unsigned long long) tv.tv_sec * 1000 +
  71         (unsigned long long) tv.tv_usec / 1000;
  72 
  73     return (unsigned) msec;
  74 }
  75 
  76 /* Could use npt but decided to cut down on linked code size */
  77 char* SplashConvertStringAlloc(const char* in, int* size) {
  78     const char     *codeset;
  79     const char     *codeset_out;
  80     iconv_t         cd;
  81     size_t          rc;
  82     char           *buf = NULL, *out;
  83     size_t          bufSize, inSize, outSize;
  84     const char* old_locale;
  85 
  86     if (!in) {
  87         return NULL;
  88     }
  89     old_locale = setlocale(LC_ALL, "");
  90 
  91     codeset = nl_langinfo(CODESET);
  92     if ( codeset == NULL || codeset[0] == 0 ) {
  93         goto done;
  94     }
  95     /* we don't need BOM in output so we choose native BE or LE encoding here */
  96     codeset_out = (platformByteOrder()==BYTE_ORDER_MSBFIRST) ?
  97         "UCS-2BE" : "UCS-2LE";
  98 
  99     cd = iconv_open(codeset_out, codeset);
 100     if (cd == (iconv_t)-1 ) {
 101         goto done;
 102     }
 103     inSize = strlen(in);
 104     buf = SAFE_SIZE_ARRAY_ALLOC(malloc, inSize, 2);
 105     if (!buf) {
 106         return NULL;
 107     }
 108     bufSize = inSize*2; // need 2 bytes per char for UCS-2, this is
 109                         // 2 bytes per source byte max
 110     out = buf; outSize = bufSize;
 111     /* linux iconv wants char** source and solaris wants const char**...
 112        cast to void* */
 113     rc = iconv(cd, (void*)&in, &inSize, &out, &outSize);
 114     iconv_close(cd);
 115 
 116     if (rc == (size_t)-1) {
 117         free(buf);
 118         buf = NULL;
 119     } else {
 120         if (size) {
 121             *size = (bufSize-outSize)/2; /* bytes to wchars */
 122         }
 123     }
 124 done:
 125     setlocale(LC_ALL, old_locale);
 126     return buf;
 127 }
 128 
 129 BOOL isSWTRunning() {
 130     char envVar[80];
 131     // If this property is present we are running SWT
 132     snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
 133     return getenv(envVar) != NULL;
 134 }
 135 
 136 jboolean SplashGetScaledImageName(const char* jar, const char* file,
 137                                   float *scaleFactor, char *scaledFile,
 138                                   const size_t scaledImageLength) {
 139     *scaleFactor = 1;
 140 
 141     if(isSWTRunning()){
 142         return JNI_FALSE;
 143     }
 144 
 145     NSAutoreleasePool *pool = [NSAutoreleasePool new];
 146     __block float screenScaleFactor = 1;
 147 
 148     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 149         // initialize NSApplication and AWT stuff
 150         [NSApplicationAWT sharedApplication];
 151         screenScaleFactor = [SplashNSScreen() backingScaleFactor];
 152     }];
 153 
 154     if (screenScaleFactor > 1) {
 155         NSString *fileName = [NSString stringWithUTF8String: file];
 156         NSUInteger length = [fileName length];
 157         NSRange range = [fileName rangeOfString: @"."
 158                                         options:NSBackwardsSearch];
 159         NSUInteger dotIndex = range.location;
 160         NSString *fileName2x = nil;
 161 
 162         fileName2x = findScaledImageName(fileName, dotIndex, @"@2x");
 163         if(![[NSFileManager defaultManager]
 164                 fileExistsAtPath: fileName2x]) {
 165             fileName2x = findScaledImageName(fileName, dotIndex, @"@200pct");
 166         }
 167         if (jar || [[NSFileManager defaultManager]
 168                 fileExistsAtPath: fileName2x]){
 169             if (strlen([fileName2x UTF8String]) > scaledImageLength) {
 170                 [pool drain];
 171                 return JNI_FALSE;
 172             }
 173             *scaleFactor = 2;
 174             strcpy(scaledFile, [fileName2x UTF8String]);
 175             [pool drain];
 176             return JNI_TRUE;
 177         }
 178     }
 179     [pool drain];
 180     return JNI_FALSE;
 181 }
 182 
 183 void
 184 SplashInitPlatform(Splash * splash) {
 185     pthread_mutex_init(&splash->lock, NULL);
 186 
 187     splash->maskRequired = 0;
 188 
 189     
 190     //TODO: the following is too much of a hack but should work in 90% cases.
 191     //      besides we don't use device-dependant drawing, so probably
 192     //      that's very fine indeed
 193     splash->byteAlignment = 1;
 194     initFormat(&splash->screenFormat, 0xff << 8,
 195             0xff << 16, 0xff << 24, 0xff << 0);
 196     splash->screenFormat.byteOrder = 1 ?  BYTE_ORDER_LSBFIRST : BYTE_ORDER_MSBFIRST;
 197     splash->screenFormat.depthBytes = 4;
 198 
 199     // If we are running SWT we should not start a runLoop
 200     if (!isSWTRunning()) {
 201         [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^() {
 202             [NSApplicationAWT runAWTLoopWithApp:[NSApplicationAWT sharedApplication]];
 203         }];
 204     }
 205 }
 206 
 207 void
 208 SplashCleanupPlatform(Splash * splash) {
 209     splash->maskRequired = 0;
 210 }
 211 
 212 void
 213 SplashDonePlatform(Splash * splash) {
 214     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 215 
 216     pthread_mutex_destroy(&splash->lock);
 217     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 218         if (splash->window) {
 219             [splash->window orderOut:nil];
 220             [splash->window release];
 221         }
 222     }];
 223     [pool drain];
 224 }
 225 
 226 void
 227 SplashLock(Splash * splash) {
 228     pthread_mutex_lock(&splash->lock);
 229 }
 230 
 231 void
 232 SplashUnlock(Splash * splash) {
 233     pthread_mutex_unlock(&splash->lock);
 234 }
 235 
 236 void
 237 SplashInitFrameShape(Splash * splash, int imageIndex) {
 238     // No shapes, we rely on alpha compositing
 239 }
 240 
 241 void * SplashScreenThread(void *param);
 242 void
 243 SplashCreateThread(Splash * splash) {
 244     pthread_t thr;
 245     pthread_attr_t attr;
 246     int rc;
 247 
 248     pthread_attr_init(&attr);
 249     rc = pthread_create(&thr, &attr, SplashScreenThread, (void *) splash);
 250 }
 251 
 252 void
 253 SplashRedrawWindow(Splash * splash) {
 254     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 255 
 256     SplashUpdateScreenData(splash);
 257 
 258     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 259         // NSDeviceRGBColorSpace vs. NSCalibratedRGBColorSpace ?
 260         NSBitmapImageRep * rep = [[NSBitmapImageRep alloc]
 261             initWithBitmapDataPlanes: (unsigned char**)&splash->screenData
 262                           pixelsWide: splash->width
 263                           pixelsHigh: splash->height
 264                        bitsPerSample: 8
 265                      samplesPerPixel: 4
 266                             hasAlpha: YES
 267                             isPlanar: NO
 268                       colorSpaceName: NSDeviceRGBColorSpace
 269                         bitmapFormat: NSAlphaFirstBitmapFormat | NSAlphaNonpremultipliedBitmapFormat
 270                          bytesPerRow: splash->width * 4
 271                         bitsPerPixel: 32];
 272 
 273         NSImage * image = [[NSImage alloc]
 274             initWithSize: NSMakeSize(splash->width, splash->height)];
 275         [image setBackgroundColor: [NSColor clearColor]];
 276 
 277         [image addRepresentation: rep];
 278         float scaleFactor = splash->scaleFactor;
 279         if (scaleFactor > 0 && scaleFactor != 1) {
 280             NSSize size = [image size];
 281             size.width /= scaleFactor;
 282             size.height /= scaleFactor;
 283             [image setSize: size];
 284         }
 285         
 286         NSImageView * view = [[NSImageView alloc] init];
 287 
 288         [view setImage: image];
 289         [view setEditable: NO];
 290         //NOTE: we don't set a 'wait cursor' for the view because:
 291         //      1. The Cocoa GUI guidelines suggest to avoid it, and use a progress
 292         //         bar instead.
 293         //      2. There simply isn't an instance of NSCursor that represent
 294         //         the 'wait cursor'. So that is undoable.
 295 
 296         //TODO: only the first image in an animated gif preserves transparency.
 297         //      Loos like the splash->screenData contains inappropriate data
 298         //      for all but the first frame.
 299 
 300         [image release];
 301         [rep release];
 302 
 303         [splash->window setContentView: view];
 304         [splash->window orderFrontRegardless];
 305     }];
 306 
 307     [pool drain];
 308 }
 309 
 310 void SplashReconfigureNow(Splash * splash) {
 311     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 312 
 313     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 314         SplashCenter(splash);
 315 
 316         if (!splash->window) {
 317             return;
 318         }
 319 
 320         [splash->window orderOut:nil];
 321         [splash->window setFrame: NSMakeRect(splash->x, splash->y, splash->width, splash->height)
 322                          display: NO];
 323     }];
 324 
 325     [pool drain];
 326 
 327     SplashRedrawWindow(splash);
 328 }
 329 
 330 void
 331 SplashEventLoop(Splash * splash) {
 332 
 333     /* we should have splash _locked_ on entry!!! */
 334 
 335     while (1) {
 336         struct pollfd pfd[1];
 337         int timeout = -1;
 338         int ctl = splash->controlpipe[0];
 339         int rc;
 340         int pipes_empty;
 341 
 342         pfd[0].fd = ctl;
 343         pfd[0].events = POLLIN | POLLPRI;
 344 
 345         errno = 0;
 346         if (splash->isVisible>0 && SplashIsStillLooping(splash)) {
 347             timeout = splash->time + splash->frames[splash->currentFrame].delay
 348                 - SplashTime();
 349             if (timeout < 0) {
 350                 timeout = 0;
 351             }
 352         }
 353         SplashUnlock(splash);
 354         rc = poll(pfd, 1, timeout);
 355         SplashLock(splash);
 356         if (splash->isVisible > 0 && splash->currentFrame >= 0 &&
 357                 SplashTime() >= splash->time + splash->frames[splash->currentFrame].delay) {
 358             SplashNextFrame(splash);
 359             SplashRedrawWindow(splash);
 360         }
 361         if (rc <= 0) {
 362             errno = 0;
 363             continue;
 364         }
 365         pipes_empty = 0;
 366         while(!pipes_empty) {
 367             char buf;
 368 
 369             pipes_empty = 1;
 370             if (read(ctl, &buf, sizeof(buf)) > 0) {
 371                 pipes_empty = 0;
 372                 switch (buf) {
 373                 case SPLASHCTL_UPDATE:
 374                     if (splash->isVisible>0) {
 375                         SplashRedrawWindow(splash);
 376                     }
 377                     break;
 378                 case SPLASHCTL_RECONFIGURE:
 379                     if (splash->isVisible>0) {
 380                         SplashReconfigureNow(splash);
 381                     }
 382                     break;
 383                 case SPLASHCTL_QUIT:
 384                     return;
 385                 }
 386             }
 387         }
 388     }
 389 }
 390 
 391 void *
 392 SplashScreenThread(void *param) {
 393     objc_registerThreadWithCollector();
 394 
 395     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 396     Splash *splash = (Splash *) param;
 397 
 398     SplashLock(splash);
 399     pipe(splash->controlpipe);
 400     fcntl(splash->controlpipe[0], F_SETFL,
 401         fcntl(splash->controlpipe[0], F_GETFL, 0) | O_NONBLOCK);
 402     splash->time = SplashTime();
 403     splash->currentFrame = 0;
 404     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 405         SplashCenter(splash);
 406 
 407         splash->window = (void*) [[NSWindow alloc]
 408             initWithContentRect: NSMakeRect(splash->x, splash->y, splash->width, splash->height)
 409                       styleMask: NSBorderlessWindowMask
 410                         backing: NSBackingStoreBuffered
 411                           defer: NO
 412                          screen: SplashNSScreen()];
 413 
 414         [splash->window setOpaque: NO];
 415         [splash->window setBackgroundColor: [NSColor clearColor]];
 416     }];
 417     fflush(stdout);
 418     if (splash->window) {
 419         [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 420             [splash->window orderFrontRegardless];
 421         }];
 422         SplashRedrawWindow(splash);
 423         SplashEventLoop(splash);
 424     }
 425     SplashUnlock(splash);
 426     SplashDone(splash);
 427 
 428     splash->isVisible=-1;
 429 
 430     [pool drain];
 431 
 432     return 0;
 433 }
 434 
 435 void
 436 sendctl(Splash * splash, char code) {
 437     if (splash && splash->controlpipe[1]) {
 438         write(splash->controlpipe[1], &code, 1);
 439     }
 440 }
 441 
 442 void
 443 SplashClosePlatform(Splash * splash) {
 444     sendctl(splash, SPLASHCTL_QUIT);
 445 }
 446 
 447 void
 448 SplashUpdate(Splash * splash) {
 449     sendctl(splash, SPLASHCTL_UPDATE);
 450 }
 451 
 452 void
 453 SplashReconfigure(Splash * splash) {
 454     sendctl(splash, SPLASHCTL_RECONFIGURE);
 455 }
 456 
 457 NSString* findScaledImageName(NSString *fileName, NSUInteger dotIndex, NSString *strToAppend) {
 458     NSString *fileName2x = nil;
 459     if (dotIndex == NSNotFound) {
 460         fileName2x = [fileName stringByAppendingString: strToAppend];
 461     } else {
 462         fileName2x = [fileName substringToIndex: dotIndex];
 463         fileName2x = [fileName2x stringByAppendingString: strToAppend];
 464         fileName2x = [fileName2x stringByAppendingString:
 465                       [fileName substringFromIndex: dotIndex]];
 466     }
 467     return fileName2x;
 468 }
 469