]> git.sesse.net Git - vlc/blob - modules/gui/skins2/src/theme_loader.cpp
e809c357710ec71e2e33956a2af6c9f62afaaa2d
[vlc] / modules / gui / skins2 / src / theme_loader.cpp
1 /*****************************************************************************
2  * theme_loader.cpp
3  *****************************************************************************
4  * Copyright (C) 2003 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Cyril Deguet     <asmax@via.ecp.fr>
8  *          Olivier Teulière <ipkiss@via.ecp.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 #include "theme_loader.hpp"
26 #include "theme.hpp"
27 #include "../parser/builder.hpp"
28 #include "../parser/skin_parser.hpp"
29 #include "../src/os_factory.hpp"
30 #include "../src/vlcproc.hpp"
31 #include "../src/window_manager.hpp"
32
33 #ifdef HAVE_FCNTL_H
34 #   include <fcntl.h>
35 #endif
36 #ifdef HAVE_SYS_STAT_H
37 #   include <sys/stat.h>
38 #endif
39 #ifdef HAVE_UNISTD_H
40 #   include <unistd.h>
41 #elif defined( WIN32 ) && !defined( UNDER_CE )
42 #   include <direct.h>
43 #endif
44
45 #ifdef HAVE_DIRENT_H
46 #   include <dirent.h>
47 #endif
48
49
50 #if defined( HAVE_ZLIB_H )
51 #   include <zlib.h>
52 #   include <errno.h>
53 int gzopen_frontend ( char *pathname, int oflags, int mode );
54 int gzclose_frontend( int );
55 int gzread_frontend ( int, void *, size_t );
56 int gzwrite_frontend( int, const void *, size_t );
57 #if defined( HAVE_LIBTAR_H )
58 #   include <libtar.h>
59 #else
60 typedef gzFile TAR;
61 int tar_open        ( TAR **t, char *pathname, int oflags );
62 int tar_extract_all ( TAR *t, char *prefix );
63 int tar_close       ( TAR *t );
64 int getoct( char *p, int width );
65 #endif
66 int makedir( const char *newdir );
67 #endif
68
69 #define DEFAULT_XML_FILE "theme.xml"
70 #define WINAMP2_XML_FILE "winamp2.xml"
71 #define ZIP_BUFFER_SIZE 4096
72
73
74 bool ThemeLoader::load( const string &fileName )
75 {
76     // First, we try to un-targz the file, and if it fails we hope it's a XML
77     // file...
78     string path = getFilePath( fileName );
79 #if defined( HAVE_ZLIB_H )
80     if( ! extract( fileName ) && ! parse( path, fileName ) )
81         return false;
82 #else
83     if( ! parse( path, fileName ) )
84         return false;
85 #endif
86
87     Theme *pNewTheme = getIntf()->p_sys->p_theme;
88     if( !pNewTheme )
89     {
90         return false;
91     }
92
93     // Check if the skin to load is in the config file, to load its config
94     char *skin_last = config_GetPsz( getIntf(), "skins2-last" );
95     if( skin_last != NULL && fileName == (string)skin_last )
96     {
97         // Restore the theme configuration
98         getIntf()->p_sys->p_theme->loadConfig();
99         // Used to anchor the windows at the beginning
100         pNewTheme->getWindowManager().stopMove();
101     }
102     else
103     {
104         config_PutPsz( getIntf(), "skins2-last", fileName.c_str() );
105         // Show the windows
106         pNewTheme->getWindowManager().showAll( true );
107     }
108     if( skin_last ) free( skin_last );
109
110     // The new theme cannot embed a video output yet
111     VlcProc::instance( getIntf() )->dropVout();
112
113     return true;
114 }
115
116
117 #if defined( HAVE_ZLIB_H )
118 bool ThemeLoader::extractTarGz( const string &tarFile, const string &rootDir )
119 {
120     TAR *t;
121 #if defined( HAVE_LIBTAR_H )
122     tartype_t gztype = { (openfunc_t) gzopen_frontend,
123                          (closefunc_t) gzclose_frontend,
124                          (readfunc_t) gzread_frontend,
125                          (writefunc_t) gzwrite_frontend };
126
127     if( tar_open( &t, (char *)tarFile.c_str(), &gztype, O_RDONLY, 0,
128                   TAR_GNU ) == -1 )
129 #else
130     if( tar_open( &t, (char *)tarFile.c_str(), O_RDONLY ) == -1 )
131 #endif
132     {
133         return false;
134     }
135
136     if( tar_extract_all( t, (char *)rootDir.c_str() ) != 0 )
137     {
138         tar_close( t );
139         return false;
140     }
141
142     if( tar_close( t ) != 0 )
143     {
144         return false;
145     }
146
147     return true;
148 }
149
150
151 bool ThemeLoader::extractZip( const string &zipFile, const string &rootDir )
152 {
153     // Try to open the ZIP file
154     unzFile file = unzOpen( zipFile.c_str() );
155     unz_global_info info;
156
157     if( unzGetGlobalInfo( file, &info ) != UNZ_OK )
158     {
159         return false;
160     }
161     // Extract all the files in the archive
162     for( unsigned long i = 0; i < info.number_entry; i++ )
163     {
164         if( !extractFileInZip( file, rootDir ) )
165         {
166             msg_Warn( getIntf(), "Error while unzipping %s",
167                       zipFile.c_str() );
168             return false;
169         }
170
171         if( i < info.number_entry - 1 )
172         {
173             // Go the next file in the archive
174             if( unzGoToNextFile( file ) !=UNZ_OK )
175             {
176                 msg_Warn( getIntf(), "Error while unzipping %s",
177                           zipFile.c_str() );
178                 return false;
179             }
180         }
181     }
182     return true;
183 }
184
185
186 bool ThemeLoader::extractFileInZip( unzFile file, const string &rootDir )
187 {
188     // Read info for the current file
189     char filenameInZip[256];
190     unz_file_info fileInfo;
191     if( unzGetCurrentFileInfo( file, &fileInfo, filenameInZip,
192                                sizeof( filenameInZip), NULL, 0, NULL, 0 )
193         != UNZ_OK )
194     {
195         return false;
196     }
197
198     // Allocate the buffer
199     void *pBuffer = malloc( ZIP_BUFFER_SIZE );
200     if( !pBuffer )
201     {
202         msg_Err( getIntf(), "Failed to allocate memory" );
203         return false;
204     }
205
206     // Get the path of the file
207     OSFactory *pOsFactory = OSFactory::instance( getIntf() );
208     string fullPath = rootDir
209         + pOsFactory->getDirSeparator()
210         + fixDirSeparators( filenameInZip );
211     string basePath = getFilePath( fullPath );
212
213     // Extract the file if is not a directory
214     if( basePath != fullPath )
215     {
216         if( unzOpenCurrentFile( file ) )
217         {
218             free( pBuffer );
219             return false;
220         }
221         makedir( basePath.c_str() );
222         FILE *fout = fopen( fullPath.c_str(), "wb" );
223         if( fout == NULL )
224         {
225             msg_Err( getIntf(), "Error opening %s", fullPath.c_str() );
226             free( pBuffer );
227             return false;
228         }
229
230         // Extract the current file
231         int n;
232         do
233         {
234             n = unzReadCurrentFile( file, pBuffer, ZIP_BUFFER_SIZE );
235             if( n < 0 )
236             {
237                 msg_Err( getIntf(), "Error while reading zip file" );
238                 free( pBuffer );
239                 return false;
240             }
241             else if( n > 0 )
242             {
243                 if( fwrite( pBuffer, n , 1, fout) != 1 )
244                 {
245                     msg_Err( getIntf(), "Error while writing %s",
246                              fullPath.c_str() );
247                     free( pBuffer );
248                     return false;
249                 }
250             }
251         } while( n > 0 );
252
253         fclose(fout);
254
255         if( unzCloseCurrentFile( file ) != UNZ_OK )
256         {
257             free( pBuffer );
258             return false;
259         }
260     }
261
262     free( pBuffer );
263     return true;
264 }
265
266
267 bool ThemeLoader::extract( const string &fileName )
268 {
269     bool result = true;
270     char *tmpdir = tempnam( NULL, "vlt" );
271     string tempPath = tmpdir;
272     free( tmpdir );
273
274     // Extract the file in a temporary directory
275     if( ! extractTarGz( fileName, tempPath ) &&
276         ! extractZip( fileName, tempPath ) )
277         return false;
278
279     string path;
280     string xmlFile;
281     OSFactory *pOsFactory = OSFactory::instance( getIntf() );
282     // Find the XML file in the theme
283     if( findFile( tempPath, DEFAULT_XML_FILE, xmlFile ) )
284     {
285         path = getFilePath( xmlFile );
286     }
287     else
288     {
289         // No XML file, check if it is a winamp2 skin
290         string mainBmp;
291         if( findFile( tempPath, "main.bmp", mainBmp ) )
292         {
293             msg_Dbg( getIntf(), "Try to load a winamp2 skin" );
294             path = getFilePath( mainBmp );
295
296             // Look for winamp2.xml in the resource path
297             list<string> resPath = pOsFactory->getResourcePath();
298             list<string>::const_iterator it;
299             for( it = resPath.begin(); it != resPath.end(); it++ )
300             {
301                 if( findFile( *it, WINAMP2_XML_FILE, xmlFile ) )
302                     break;
303             }
304         }
305     }
306
307     if( !xmlFile.empty() )
308     {
309         // Parse the XML file
310         if (! parse( path, xmlFile ) )
311         {
312             msg_Err( getIntf(), "Error while parsing %s", xmlFile.c_str() );
313             result = false;
314         }
315     }
316     else
317     {
318         msg_Err( getIntf(), "No XML found in theme %s", fileName.c_str() );
319         result = false;
320     }
321
322     // Clean-up
323     deleteTempFiles( tempPath );
324     return result;
325 }
326
327
328 void ThemeLoader::deleteTempFiles( const string &path )
329 {
330     OSFactory::instance( getIntf() )->rmDir( path );
331 }
332 #endif // HAVE_ZLIB_H
333
334
335 bool ThemeLoader::parse( const string &path, const string &xmlFile )
336 {
337     // File loaded
338     msg_Dbg( getIntf(), "Using skin file: %s", xmlFile.c_str() );
339
340     // Start the parser
341     SkinParser parser( getIntf(), xmlFile, path );
342     if( ! parser.parse() )
343     {
344         msg_Err( getIntf(), "Failed to parse %s", xmlFile.c_str() );
345         return false;
346     }
347
348     // Build and store the theme
349     Builder builder( getIntf(), parser.getData() );
350     getIntf()->p_sys->p_theme = builder.build();
351
352     return true;
353 }
354
355
356 string ThemeLoader::getFilePath( const string &rFullPath )
357 {
358     OSFactory *pOsFactory = OSFactory::instance( getIntf() );
359     const string &sep = pOsFactory->getDirSeparator();
360     // Find the last separator ('/' or '\')
361     string::size_type p = rFullPath.rfind( sep, rFullPath.size() );
362     string basePath;
363     if( p != string::npos )
364     {
365         if( p < rFullPath.size() - 1)
366         {
367             basePath = rFullPath.substr( 0, p );
368         }
369         else
370         {
371             basePath = rFullPath;
372         }
373     }
374     return basePath;
375 }
376
377
378 string ThemeLoader::fixDirSeparators( const string &rPath )
379 {
380     OSFactory *pOsFactory = OSFactory::instance( getIntf() );
381     const string &sep = pOsFactory->getDirSeparator();
382     string::size_type p = rPath.find( "/", 0 );
383     string newPath = rPath;
384     while( p != string::npos )
385     {
386         newPath = newPath.replace( p, 1, sep );
387         p = newPath.find( "/", p + 1 );
388     }
389     return newPath;
390 }
391
392
393 bool ThemeLoader::findFile( const string &rootDir, const string &rFileName,
394                             string &themeFilePath )
395 {
396     // Path separator
397     const string &sep = OSFactory::instance( getIntf() )->getDirSeparator();
398
399     DIR *pCurrDir;
400     struct dirent *pDirContent;
401
402     // Open the dir
403     pCurrDir = opendir( rootDir.c_str() );
404
405     if( pCurrDir == NULL )
406     {
407         // An error occurred
408         msg_Dbg( getIntf(), "Cannot open directory %s", rootDir.c_str() );
409         return false;
410     }
411
412     // Get the first directory entry
413     pDirContent = (dirent*)readdir( pCurrDir );
414
415     // While we still have entries in the directory
416     while( pDirContent != NULL )
417     {
418         string newURI = rootDir + sep + pDirContent->d_name;
419
420         // Skip . and ..
421         if( string( pDirContent->d_name ) != "." &&
422             string( pDirContent->d_name ) != ".." )
423         {
424 #if defined( S_ISDIR )
425             struct stat stat_data;
426             stat( newURI.c_str(), &stat_data );
427             if( S_ISDIR(stat_data.st_mode) )
428 #elif defined( DT_DIR )
429             if( pDirContent->d_type & DT_DIR )
430 #else
431             if( 0 )
432 #endif
433             {
434                 // Can we find the file in this subdirectory?
435                 if( findFile( newURI, rFileName, themeFilePath ) )
436                 {
437                     closedir( pCurrDir );
438                     return true;
439                 }
440             }
441             else
442             {
443                 // Found the theme file?
444                 if( rFileName == string( pDirContent->d_name ) )
445                 {
446                     themeFilePath = newURI;
447                     closedir( pCurrDir );
448                     return true;
449                 }
450             }
451         }
452
453         pDirContent = (dirent*)readdir( pCurrDir );
454     }
455
456     closedir( pCurrDir );
457     return false;
458 }
459
460
461 #if !defined( HAVE_LIBTAR_H ) && defined( HAVE_ZLIB_H )
462
463 /* Values used in typeflag field */
464 #define REGTYPE  '0'            /* regular file */
465 #define AREGTYPE '\0'           /* regular file */
466 #define DIRTYPE  '5'            /* directory */
467
468 #define BLOCKSIZE 512
469
470 struct tar_header
471 {                               /* byte offset */
472     char name[100];             /*   0 */
473     char mode[8];               /* 100 */
474     char uid[8];                /* 108 */
475     char gid[8];                /* 116 */
476     char size[12];              /* 124 */
477     char mtime[12];             /* 136 */
478     char chksum[8];             /* 148 */
479     char typeflag;              /* 156 */
480     char linkname[100];         /* 157 */
481     char magic[6];              /* 257 */
482     char version[2];            /* 263 */
483     char uname[32];             /* 265 */
484     char gname[32];             /* 297 */
485     char devmajor[8];           /* 329 */
486     char devminor[8];           /* 337 */
487     char prefix[155];           /* 345 */
488                                 /* 500 */
489 };
490
491
492 union tar_buffer {
493     char              buffer[BLOCKSIZE];
494     struct tar_header header;
495 };
496
497
498
499 int tar_open( TAR **t, char *pathname, int oflags )
500 {
501     gzFile f = gzopen( pathname, "rb" );
502     if( f == NULL )
503     {
504         fprintf( stderr, "Couldn't gzopen %s\n", pathname );
505         return -1;
506     }
507
508     *t = (gzFile *)malloc( sizeof(gzFile) );
509     **t = f;
510     return 0;
511 }
512
513
514 int tar_extract_all( TAR *t, char *prefix )
515 {
516     union tar_buffer buffer;
517     int   len, err, getheader = 1, remaining = 0;
518     FILE  *outfile = NULL;
519     char  fname[BLOCKSIZE + PATH_MAX];
520
521     while( 1 )
522     {
523         len = gzread( *t, &buffer, BLOCKSIZE );
524         if( len < 0 )
525         {
526             fprintf( stderr, "%s\n", gzerror(*t, &err) );
527         }
528
529         /*
530          * Always expect complete blocks to process
531          * the tar information.
532          */
533         if( len != 0 && len != BLOCKSIZE )
534         {
535             fprintf( stderr, "gzread: incomplete block read\n" );
536             return -1;
537         }
538
539         /*
540          * If we have to get a tar header
541          */
542         if( getheader == 1 )
543         {
544             /*
545              * If we met the end of the tar
546              * or the end-of-tar block, we are done
547              */
548             if( (len == 0) || (buffer.header.name[0] == 0) )
549             {
550                 break;
551             }
552
553             sprintf( fname, "%s/%s", prefix, buffer.header.name );
554
555             /* Check magic value in header */
556             if( strncmp( buffer.header.magic, "GNUtar", 6 ) &&
557                 strncmp( buffer.header.magic, "ustar", 5 ) )
558             {
559                 //fprintf(stderr, "not a tar file\n");
560                 return -1;
561             }
562
563             switch( buffer.header.typeflag )
564             {
565                 case DIRTYPE:
566                     makedir( fname );
567                     break;
568                 case REGTYPE:
569                 case AREGTYPE:
570                     remaining = getoct( buffer.header.size, 12 );
571                     if( remaining )
572                     {
573                         outfile = fopen( fname, "wb" );
574                         if( outfile == NULL )
575                         {
576                             /* try creating directory */
577                             char *p = strrchr( fname, '/' );
578                             if( p != NULL )
579                             {
580                                 *p = '\0';
581                                 makedir( fname );
582                                 *p = '/';
583                                 outfile = fopen( fname, "wb" );
584                                 if( !outfile )
585                                 {
586                                     fprintf( stderr, "tar couldn't create %s\n",
587                                              fname );
588                                 }
589                             }
590                         }
591                     }
592                     else outfile = NULL;
593
594                 /*
595                  * could have no contents
596                  */
597                 getheader = (remaining) ? 0 : 1;
598                 break;
599             default:
600                 break;
601             }
602         }
603         else
604         {
605             unsigned int bytes = (remaining > BLOCKSIZE)?BLOCKSIZE:remaining;
606
607             if( outfile != NULL )
608             {
609                 if( fwrite( &buffer, sizeof(char), bytes, outfile ) != bytes )
610                 {
611                     fprintf( stderr, "error writing %s skipping...\n", fname );
612                     fclose( outfile );
613                     unlink( fname );
614                 }
615             }
616             remaining -= bytes;
617             if( remaining == 0 )
618             {
619                 getheader = 1;
620                 if( outfile != NULL )
621                 {
622                     fclose(outfile);
623                     outfile = NULL;
624                 }
625             }
626         }
627     }
628
629     return 0;
630 }
631
632
633 int tar_close( TAR *t )
634 {
635     if( gzclose( *t ) != Z_OK ) fprintf( stderr, "failed gzclose\n" );
636     free( t );
637     return 0;
638 }
639
640
641 /* helper functions */
642 int getoct( char *p, int width )
643 {
644     int result = 0;
645     char c;
646
647     while( width-- )
648     {
649         c = *p++;
650         if( c == ' ' )
651             continue;
652         if( c == 0 )
653             break;
654         result = result * 8 + (c - '0');
655     }
656     return result;
657 }
658
659 #endif
660
661 #ifdef WIN32
662 #  define mkdir(dirname,mode) _mkdir(dirname)
663 #endif
664
665 /* Recursive make directory
666  * Abort if you get an ENOENT errno somewhere in the middle
667  * e.g. ignore error "mkdir on existing directory"
668  *
669  * return 1 if OK, 0 on error
670  */
671 int makedir( const char *newdir )
672 {
673     char *p, *buffer = strdup( newdir );
674     int  len = strlen( buffer );
675
676     if( len <= 0 )
677     {
678         free( buffer );
679         return 0;
680     }
681
682     if( buffer[len-1] == '/' )
683     {
684         buffer[len-1] = '\0';
685     }
686
687     if( mkdir( buffer, 0775 ) == 0 )
688     {
689         free( buffer );
690         return 1;
691     }
692
693     p = buffer + 1;
694     while( 1 )
695     {
696         char hold;
697
698         while( *p && *p != '\\' && *p != '/' ) p++;
699         hold = *p;
700         *p = 0;
701         if( ( mkdir( buffer, 0775 ) == -1 ) && ( errno == ENOENT ) )
702         {
703             fprintf( stderr, "couldn't create directory %s\n", buffer );
704             free( buffer );
705             return 0;
706         }
707         if( hold == 0 ) break;
708         *p++ = hold;
709     }
710     free( buffer );
711     return 1;
712 }
713
714 #ifdef HAVE_ZLIB_H
715
716 static int currentGzFd = -1;
717 static void * currentGzVp = NULL;
718
719 int gzopen_frontend( char *pathname, int oflags, int mode )
720 {
721     char *gzflags;
722     gzFile gzf;
723
724     switch( oflags )
725     {
726         case O_WRONLY:
727             gzflags = "wb";
728             break;
729         case O_RDONLY:
730             gzflags = "rb";
731             break;
732         case O_RDWR:
733         default:
734             errno = EINVAL;
735             return -1;
736     }
737
738     gzf = gzopen( pathname, gzflags );
739     if( !gzf )
740     {
741         errno = ENOMEM;
742         return -1;
743     }
744
745     /** Hum ... */
746     currentGzFd = 42;
747     currentGzVp = gzf;
748
749     return currentGzFd;
750 }
751
752 int gzclose_frontend( int fd )
753 {
754     if( currentGzVp != NULL && fd != -1 )
755     {
756         void *toClose = currentGzVp;
757         currentGzVp = NULL;  currentGzFd = -1;
758         return gzclose( toClose );
759     }
760     return -1;
761 }
762
763 int gzread_frontend( int fd, void *p_buffer, size_t i_length )
764 {
765     if( currentGzVp != NULL && fd != -1 )
766     {
767         return gzread( currentGzVp, p_buffer, i_length );
768     }
769     return -1;
770 }
771
772 int gzwrite_frontend( int fd, const void * p_buffer, size_t i_length )
773 {
774     if( currentGzVp != NULL && fd != -1 )
775     {
776         return gzwrite( currentGzVp, const_cast<void*>(p_buffer), i_length );
777     }
778     return -1;
779 }
780
781 #endif