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 
  49 static NSScreen* SplashNSScreen()
  50 {
  51     return [[NSScreen screens] objectAtIndex: 0];
  52 }
  53 
  54 static void SplashCenter(Splash * splash)
  55 {
  56     NSRect screenFrame = [SplashNSScreen() frame];
  57 
  58     splash->x = (screenFrame.size.width - splash->width) / 2;
  59     splash->y = (screenFrame.size.height - splash->height) / 2 + screenFrame.origin.y;
  60 }
  61 
  62 unsigned
  63 SplashTime(void) {
  64     struct timeval tv;
  65     struct timezone tz;
  66     unsigned long long msec;
  67 
  68     gettimeofday(&tv, &tz);
  69     msec = (unsigned long long) tv.tv_sec * 1000 +
  70         (unsigned long long) tv.tv_usec / 1000;
  71 
  72     return (unsigned) msec;
  73 }
  74 
  75 /* Could use npt but decided to cut down on linked code size */
  76 char* SplashConvertStringAlloc(const char* in, int* size) {
  77     const char     *codeset;
  78     const char     *codeset_out;
  79     iconv_t         cd;
  80     size_t          rc;
  81     char           *buf = NULL, *out;
  82     size_t          bufSize, inSize, outSize;
  83     const char* old_locale;
  84 
  85     if (!in) {
  86         return NULL;
  87     }
  88     old_locale = setlocale(LC_ALL, "");
  89 
  90     codeset = nl_langinfo(CODESET);
  91     if ( codeset == NULL || codeset[0] == 0 ) {
  92         goto done;
  93     }
  94     /* we don't need BOM in output so we choose native BE or LE encoding here */
  95     codeset_out = (platformByteOrder()==BYTE_ORDER_MSBFIRST) ?
  96         "UCS-2BE" : "UCS-2LE";
  97 
  98     cd = iconv_open(codeset_out, codeset);
  99     if (cd == (iconv_t)-1 ) {
 100         goto done;
 101     }
 102     inSize = strlen(in);
 103     buf = SAFE_SIZE_ARRAY_ALLOC(malloc, inSize, 2);
 104     if (!buf) {
 105         return NULL;
 106     }
 107     bufSize = inSize*2; // need 2 bytes per char for UCS-2, this is
 108                         // 2 bytes per source byte max
 109     out = buf; outSize = bufSize;
 110     /* linux iconv wants char** source and solaris wants const char**...
 111        cast to void* */
 112     rc = iconv(cd, (void*)&in, &inSize, &out, &outSize);
 113     iconv_close(cd);
 114 
 115     if (rc == (size_t)-1) {
 116         free(buf);
 117         buf = NULL;
 118     } else {
 119         if (size) {
 120             *size = (bufSize-outSize)/2; /* bytes to wchars */
 121         }
 122     }
 123 done:
 124     setlocale(LC_ALL, old_locale);
 125     return buf;
 126 }
 127 
 128 
 129 void
 130 SplashInitPlatform(Splash * splash) {
 131     pthread_mutex_init(&splash->lock, NULL);
 132 
 133     splash->maskRequired = 0;
 134 
 135 
 136     //TODO: the following is too much of a hack but should work in 90% cases.
 137     //      besides we don't use device-dependant drawing, so probably
 138     //      that's very fine indeed
 139     splash->byteAlignment = 1;
 140     initFormat(&splash->screenFormat, 0xff << 8,
 141             0xff << 16, 0xff << 24, 0xff << 0);
 142     splash->screenFormat.byteOrder = 1 ?  BYTE_ORDER_LSBFIRST : BYTE_ORDER_MSBFIRST;
 143     splash->screenFormat.depthBytes = 4;
 144 
 145     // If this property is present we are running SWT and should not start a runLoop
 146     char envVar[80];
 147     snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
 148     if (getenv(envVar) == NULL) {
 149         [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^() {
 150             [NSApplicationAWT runAWTLoopWithApp:[NSApplicationAWT sharedApplication]];
 151         }];
 152     }
 153 }
 154 
 155 void
 156 SplashCleanupPlatform(Splash * splash) {
 157     splash->maskRequired = 0;
 158 }
 159 
 160 void
 161 SplashDonePlatform(Splash * splash) {
 162     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 163 
 164     pthread_mutex_destroy(&splash->lock);
 165     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 166         if (splash->window) {
 167             [splash->window orderOut:nil];
 168             [splash->window release];
 169         }
 170     }];
 171     [pool drain];
 172 }
 173 
 174 void
 175 SplashLock(Splash * splash) {
 176     pthread_mutex_lock(&splash->lock);
 177 }
 178 
 179 void
 180 SplashUnlock(Splash * splash) {
 181     pthread_mutex_unlock(&splash->lock);
 182 }
 183 
 184 void
 185 SplashInitFrameShape(Splash * splash, int imageIndex) {
 186     // No shapes, we rely on alpha compositing
 187 }
 188 
 189 void * SplashScreenThread(void *param);
 190 void
 191 SplashCreateThread(Splash * splash) {
 192     pthread_t thr;
 193     pthread_attr_t attr;
 194     int rc;
 195 
 196     pthread_attr_init(&attr);
 197     rc = pthread_create(&thr, &attr, SplashScreenThread, (void *) splash);
 198 }
 199 
 200 void
 201 SplashRedrawWindow(Splash * splash) {
 202     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 203 
 204     SplashUpdateScreenData(splash);
 205 
 206     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 207         // NSDeviceRGBColorSpace vs. NSCalibratedRGBColorSpace ?
 208         NSBitmapImageRep * rep = [[NSBitmapImageRep alloc]
 209             initWithBitmapDataPlanes: (unsigned char**)&splash->screenData
 210                           pixelsWide: splash->width
 211                           pixelsHigh: splash->height
 212                        bitsPerSample: 8
 213                      samplesPerPixel: 4
 214                             hasAlpha: YES
 215                             isPlanar: NO
 216                       colorSpaceName: NSDeviceRGBColorSpace
 217                         bitmapFormat: NSAlphaFirstBitmapFormat | NSAlphaNonpremultipliedBitmapFormat
 218                          bytesPerRow: splash->width * 4
 219                         bitsPerPixel: 32];
 220 
 221         NSImage * image = [[NSImage alloc]
 222             initWithSize: NSMakeSize(splash->width, splash->height)];
 223         [image setBackgroundColor: [NSColor clearColor]];
 224 
 225         [image addRepresentation: rep];
 226 
 227         NSImageView * view = [[NSImageView alloc] init];
 228 
 229         [view setImage: image];
 230         [view setEditable: NO];
 231         //NOTE: we don't set a 'wait cursor' for the view because:
 232         //      1. The Cocoa GUI guidelines suggest to avoid it, and use a progress
 233         //         bar instead.
 234         //      2. There simply isn't an instance of NSCursor that represent
 235         //         the 'wait cursor'. So that is undoable.
 236 
 237         //TODO: only the first image in an animated gif preserves transparency.
 238         //      Loos like the splash->screenData contains inappropriate data
 239         //      for all but the first frame.
 240 
 241         [image release];
 242         [rep release];
 243 
 244         [splash->window setContentView: view];
 245         [splash->window orderFrontRegardless];
 246     }];
 247 
 248     [pool drain];
 249 }
 250 
 251 void SplashReconfigureNow(Splash * splash) {
 252     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 253 
 254     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 255         SplashCenter(splash);
 256 
 257         if (!splash->window) {
 258             return;
 259         }
 260 
 261         [splash->window orderOut:nil];
 262         [splash->window setFrame: NSMakeRect(splash->x, splash->y, splash->width, splash->height)
 263                          display: NO];
 264     }];
 265 
 266     [pool drain];
 267 
 268     SplashRedrawWindow(splash);
 269 }
 270 
 271 void
 272 SplashEventLoop(Splash * splash) {
 273 
 274     /* we should have splash _locked_ on entry!!! */
 275 
 276     while (1) {
 277         struct pollfd pfd[1];
 278         int timeout = -1;
 279         int ctl = splash->controlpipe[0];
 280         int rc;
 281         int pipes_empty;
 282 
 283         pfd[0].fd = ctl;
 284         pfd[0].events = POLLIN | POLLPRI;
 285 
 286         errno = 0;
 287         if (splash->isVisible>0 && SplashIsStillLooping(splash)) {
 288             timeout = splash->time + splash->frames[splash->currentFrame].delay
 289                 - SplashTime();
 290             if (timeout < 0) {
 291                 timeout = 0;
 292             }
 293         }
 294         SplashUnlock(splash);
 295         rc = poll(pfd, 1, timeout);
 296         SplashLock(splash);
 297         if (splash->isVisible > 0 && splash->currentFrame >= 0 &&
 298                 SplashTime() >= splash->time + splash->frames[splash->currentFrame].delay) {
 299             SplashNextFrame(splash);
 300             SplashRedrawWindow(splash);
 301         }
 302         if (rc <= 0) {
 303             errno = 0;
 304             continue;
 305         }
 306         pipes_empty = 0;
 307         while(!pipes_empty) {
 308             char buf;
 309 
 310             pipes_empty = 1;
 311             if (read(ctl, &buf, sizeof(buf)) > 0) {
 312                 pipes_empty = 0;
 313                 switch (buf) {
 314                 case SPLASHCTL_UPDATE:
 315                     if (splash->isVisible>0) {
 316                         SplashRedrawWindow(splash);
 317                     }
 318                     break;
 319                 case SPLASHCTL_RECONFIGURE:
 320                     if (splash->isVisible>0) {
 321                         SplashReconfigureNow(splash);
 322                     }
 323                     break;
 324                 case SPLASHCTL_QUIT:
 325                     return;
 326                 }
 327             }
 328         }
 329     }
 330 }
 331 
 332 void *
 333 SplashScreenThread(void *param) {
 334     objc_registerThreadWithCollector();
 335 
 336     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 337     Splash *splash = (Splash *) param;
 338 
 339     SplashLock(splash);
 340     pipe(splash->controlpipe);
 341     fcntl(splash->controlpipe[0], F_SETFL,
 342         fcntl(splash->controlpipe[0], F_GETFL, 0) | O_NONBLOCK);
 343     splash->time = SplashTime();
 344     splash->currentFrame = 0;
 345     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 346         SplashCenter(splash);
 347 
 348         splash->window = (void*) [[NSWindow alloc]
 349             initWithContentRect: NSMakeRect(splash->x, splash->y, splash->width, splash->height)
 350                       styleMask: NSBorderlessWindowMask
 351                         backing: NSBackingStoreBuffered
 352                           defer: NO
 353                          screen: SplashNSScreen()];
 354 
 355         [splash->window setOpaque: NO];
 356         [splash->window setBackgroundColor: [NSColor clearColor]];
 357     }];
 358     fflush(stdout);
 359     if (splash->window) {
 360         [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 361             [splash->window orderFrontRegardless];
 362         }];
 363         SplashRedrawWindow(splash);
 364         SplashEventLoop(splash);
 365     }
 366     SplashUnlock(splash);
 367     SplashDone(splash);
 368 
 369     splash->isVisible=-1;
 370 
 371     [pool drain];
 372 
 373     return 0;
 374 }
 375 
 376 void
 377 sendctl(Splash * splash, char code) {
 378     if (splash && splash->controlpipe[1]) {
 379         write(splash->controlpipe[1], &code, 1);
 380     }
 381 }
 382 
 383 void
 384 SplashClosePlatform(Splash * splash) {
 385     sendctl(splash, SPLASHCTL_QUIT);
 386 }
 387 
 388 void
 389 SplashUpdate(Splash * splash) {
 390     sendctl(splash, SPLASHCTL_UPDATE);
 391 }
 392 
 393 void
 394 SplashReconfigure(Splash * splash) {
 395     sendctl(splash, SPLASHCTL_RECONFIGURE);
 396 }
 397