]> git.sesse.net Git - vlc/blob - modules/gui/skins2/src/theme_loader.cpp
* winamp2.xml: hack to support nums_ex.bmp and numbers.bmp
[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     string fullPath = rootDir + "/" + filenameInZip;
208     string basePath = getFilePath( fullPath );
209
210     // Extract the file if is not a directory
211     if( basePath != fullPath )
212     {
213         if( unzOpenCurrentFile( file ) )
214         {
215             free( pBuffer );
216             return false;
217         }
218         makedir( basePath.c_str() );
219         FILE *fout = fopen( fullPath.c_str(), "wb" );
220         if( fout == NULL )
221         {
222             msg_Err( getIntf(), "Error opening %s", fullPath.c_str() );
223             free( pBuffer );
224             return false;
225         }
226
227         // Extract the current file
228         int n;
229         do
230         {
231             n = unzReadCurrentFile( file, pBuffer, ZIP_BUFFER_SIZE );
232             if( n < 0 )
233             {
234                 msg_Err( getIntf(), "Error while reading zip file" );
235                 free( pBuffer );
236                 return false;
237             }
238             else if( n > 0 )
239             {
240                 if( fwrite( pBuffer, n , 1, fout) != 1 )
241                 {
242                     msg_Err( getIntf(), "Error while writing %s",
243                              fullPath.c_str() );
244                     free( pBuffer );
245                     return false;
246                 }
247             }
248         } while( n > 0 );
249
250         fclose(fout);
251
252         if( unzCloseCurrentFile( file ) != UNZ_OK )
253         {
254             free( pBuffer );
255             return false;
256         }
257     }
258
259     free( pBuffer );
260     return true;
261 }
262
263
264 bool ThemeLoader::extract( const string &fileName )
265 {
266     bool result = true;
267     char *tmpdir = tempnam( NULL, "vlt" );
268     string tempPath = tmpdir;
269     free( tmpdir );
270
271     // Extract the file in a temporary directory
272     if( ! extractTarGz( fileName, tempPath ) &&
273         ! extractZip( fileName, tempPath ) )
274         return false;
275
276     string path;
277     string xmlFile;
278     OSFactory *pOsFactory = OSFactory::instance( getIntf() );
279     // Find the XML file in the theme
280     if( findFile( tempPath, DEFAULT_XML_FILE, xmlFile ) )
281     {
282         path = getFilePath( xmlFile );
283     }
284     else
285     {
286         // No XML file, check if it is a winamp2 skin
287         string mainBmp;
288         if( findFile( tempPath, "main.bmp", mainBmp ) )
289         {
290             msg_Dbg( getIntf(), "Try to load a winamp2 skin" );
291             path = getFilePath( mainBmp );
292
293             // Look for winamp2.xml in the resource path
294             list<string> resPath = pOsFactory->getResourcePath();
295             list<string>::const_iterator it;
296             for( it = resPath.begin(); it != resPath.end(); it++ )
297             {
298                 if( findFile( *it, WINAMP2_XML_FILE, xmlFile ) )
299                     break;
300             }
301         }
302     }
303
304     if( !xmlFile.empty() )
305     {
306         // Parse the XML file
307         if (! parse( path, xmlFile ) )
308         {
309             msg_Err( getIntf(), "Error while parsing %s", xmlFile.c_str() );
310             result = false;
311         }
312     }
313     else
314     {
315         msg_Err( getIntf(), "No XML found in theme %s", fileName.c_str() );
316         result = false;
317     }
318
319     // Clean-up
320     deleteTempFiles( tempPath );
321     return result;
322 }
323
324
325 void ThemeLoader::deleteTempFiles( const string &path )
326 {
327     OSFactory::instance( getIntf() )->rmDir( path );
328 }
329 #endif // HAVE_ZLIB_H
330
331
332 bool ThemeLoader::parse( const string &path, const string &xmlFile )
333 {
334     // File loaded
335     msg_Dbg( getIntf(), "Using skin file: %s", xmlFile.c_str() );
336
337     // Start the parser
338     SkinParser parser( getIntf(), xmlFile, path );
339     if( ! parser.parse() )
340     {
341         msg_Err( getIntf(), "Failed to parse %s", xmlFile.c_str() );
342         return false;
343     }
344
345     // Build and store the theme
346     Builder builder( getIntf(), parser.getData() );
347     getIntf()->p_sys->p_theme = builder.build();
348
349     return true;
350 }
351
352
353 string ThemeLoader::getFilePath( const string &rFullPath )
354 {
355     OSFactory *pOsFactory = OSFactory::instance( getIntf() );
356     const string &sep = pOsFactory->getDirSeparator();
357     // Find the last separator ('/' or '\')
358     string::size_type p = rFullPath.rfind( sep, rFullPath.size() );
359     string basePath;
360     if( p != string::npos )
361     {
362         if( p < rFullPath.size() - 1)
363         {
364             basePath = rFullPath.substr( 0, p );
365         }
366         else
367         {
368             basePath = rFullPath;
369         }
370     }
371     return basePath;
372 }
373
374
375 bool ThemeLoader::findFile( const string &rootDir, const string &rFileName,
376                             string &themeFilePath )
377 {
378     // Path separator
379     const string &sep = OSFactory::instance( getIntf() )->getDirSeparator();
380
381     DIR *pCurrDir;
382     struct dirent *pDirContent;
383
384     // Open the dir
385     pCurrDir = opendir( rootDir.c_str() );
386
387     if( pCurrDir == NULL )
388     {
389         // An error occurred
390         msg_Dbg( getIntf(), "Cannot open directory %s", rootDir.c_str() );
391         return false;
392     }
393
394     // Get the first directory entry
395     pDirContent = (dirent*)readdir( pCurrDir );
396
397     // While we still have entries in the directory
398     while( pDirContent != NULL )
399     {
400         string newURI = rootDir + sep + pDirContent->d_name;
401
402         // Skip . and ..
403         if( string( pDirContent->d_name ) != "." &&
404             string( pDirContent->d_name ) != ".." )
405         {
406 #if defined( S_ISDIR )
407             struct stat stat_data;
408             stat( newURI.c_str(), &stat_data );
409             if( S_ISDIR(stat_data.st_mode) )
410 #elif defined( DT_DIR )
411             if( pDirContent->d_type & DT_DIR )
412 #else
413             if( 0 )
414 #endif
415             {
416                 // Can we find the file in this subdirectory?
417                 if( findFile( newURI, rFileName, themeFilePath ) )
418                 {
419                     closedir( pCurrDir );
420                     return true;
421                 }
422             }
423             else
424             {
425                 // Found the theme file?
426                 if( rFileName == string( pDirContent->d_name ) )
427                 {
428                     themeFilePath = newURI;
429                     closedir( pCurrDir );
430                     return true;
431                 }
432             }
433         }
434
435         pDirContent = (dirent*)readdir( pCurrDir );
436     }
437
438     closedir( pCurrDir );
439     return false;
440 }
441
442
443 #if !defined( HAVE_LIBTAR_H ) && defined( HAVE_ZLIB_H )
444
445 /* Values used in typeflag field */
446 #define REGTYPE  '0'            /* regular file */
447 #define AREGTYPE '\0'           /* regular file */
448 #define DIRTYPE  '5'            /* directory */
449
450 #define BLOCKSIZE 512
451
452 struct tar_header
453 {                               /* byte offset */
454     char name[100];             /*   0 */
455     char mode[8];               /* 100 */
456     char uid[8];                /* 108 */
457     char gid[8];                /* 116 */
458     char size[12];              /* 124 */
459     char mtime[12];             /* 136 */
460     char chksum[8];             /* 148 */
461     char typeflag;              /* 156 */
462     char linkname[100];         /* 157 */
463     char magic[6];              /* 257 */
464     char version[2];            /* 263 */
465     char uname[32];             /* 265 */
466     char gname[32];             /* 297 */
467     char devmajor[8];           /* 329 */
468     char devminor[8];           /* 337 */
469     char prefix[155];           /* 345 */
470                                 /* 500 */
471 };
472
473
474 union tar_buffer {
475     char              buffer[BLOCKSIZE];
476     struct tar_header header;
477 };
478
479
480
481 int tar_open( TAR **t, char *pathname, int oflags )
482 {
483     gzFile f = gzopen( pathname, "rb" );
484     if( f == NULL )
485     {
486         fprintf( stderr, "Couldn't gzopen %s\n", pathname );
487         return -1;
488     }
489
490     *t = (gzFile *)malloc( sizeof(gzFile) );
491     **t = f;
492     return 0;
493 }
494
495
496 int tar_extract_all( TAR *t, char *prefix )
497 {
498     union tar_buffer buffer;
499     int   len, err, getheader = 1, remaining = 0;
500     FILE  *outfile = NULL;
501     char  fname[BLOCKSIZE + PATH_MAX];
502
503     while( 1 )
504     {
505         len = gzread( *t, &buffer, BLOCKSIZE );
506         if( len < 0 )
507         {
508             fprintf( stderr, "%s\n", gzerror(*t, &err) );
509         }
510
511         /*
512          * Always expect complete blocks to process
513          * the tar information.
514          */
515         if( len != 0 && len != BLOCKSIZE )
516         {
517             fprintf( stderr, "gzread: incomplete block read\n" );
518             return -1;
519         }
520
521         /*
522          * If we have to get a tar header
523          */
524         if( getheader == 1 )
525         {
526             /*
527              * If we met the end of the tar
528              * or the end-of-tar block, we are done
529              */
530             if( (len == 0) || (buffer.header.name[0] == 0) )
531             {
532                 break;
533             }
534
535             sprintf( fname, "%s/%s", prefix, buffer.header.name );
536
537             /* Check magic value in header */
538             if( strncmp( buffer.header.magic, "GNUtar", 6 ) &&
539                 strncmp( buffer.header.magic, "ustar", 5 ) )
540             {
541                 //fprintf(stderr, "not a tar file\n");
542                 return -1;
543             }
544
545             switch( buffer.header.typeflag )
546             {
547                 case DIRTYPE:
548                     makedir( fname );
549                     break;
550                 case REGTYPE:
551                 case AREGTYPE:
552                     remaining = getoct( buffer.header.size, 12 );
553                     if( remaining )
554                     {
555                         outfile = fopen( fname, "wb" );
556                         if( outfile == NULL )
557                         {
558                             /* try creating directory */
559                             char *p = strrchr( fname, '/' );
560                             if( p != NULL )
561                             {
562                                 *p = '\0';
563                                 makedir( fname );
564                                 *p = '/';
565                                 outfile = fopen( fname, "wb" );
566                                 if( !outfile )
567                                 {
568                                     fprintf( stderr, "tar couldn't create %s\n",
569                                              fname );
570                                 }
571                             }
572                         }
573                     }
574                     else outfile = NULL;
575
576                 /*
577                  * could have no contents
578                  */
579                 getheader = (remaining) ? 0 : 1;
580                 break;
581             default:
582                 break;
583             }
584         }
585         else
586         {
587             unsigned int bytes = (remaining > BLOCKSIZE)?BLOCKSIZE:remaining;
588
589             if( outfile != NULL )
590             {
591                 if( fwrite( &buffer, sizeof(char), bytes, outfile ) != bytes )
592                 {
593                     fprintf( stderr, "error writing %s skipping...\n", fname );
594                     fclose( outfile );
595                     unlink( fname );
596                 }
597             }
598             remaining -= bytes;
599             if( remaining == 0 )
600             {
601                 getheader = 1;
602                 if( outfile != NULL )
603                 {
604                     fclose(outfile);
605                     outfile = NULL;
606                 }
607             }
608         }
609     }
610
611     return 0;
612 }
613
614
615 int tar_close( TAR *t )
616 {
617     if( gzclose( *t ) != Z_OK ) fprintf( stderr, "failed gzclose\n" );
618     free( t );
619     return 0;
620 }
621
622
623 /* helper functions */
624 int getoct( char *p, int width )
625 {
626     int result = 0;
627     char c;
628
629     while( width-- )
630     {
631         c = *p++;
632         if( c == ' ' )
633             continue;
634         if( c == 0 )
635             break;
636         result = result * 8 + (c - '0');
637     }
638     return result;
639 }
640
641 #endif
642
643 #ifdef WIN32
644 #  define mkdir(dirname,mode) _mkdir(dirname)
645 #endif
646
647 /* Recursive make directory
648  * Abort if you get an ENOENT errno somewhere in the middle
649  * e.g. ignore error "mkdir on existing directory"
650  *
651  * return 1 if OK, 0 on error
652  */
653 int makedir( const char *newdir )
654 {
655     char *p, *buffer = strdup( newdir );
656     int  len = strlen( buffer );
657
658     if( len <= 0 )
659     {
660         free( buffer );
661         return 0;
662     }
663
664     if( buffer[len-1] == '/' )
665     {
666         buffer[len-1] = '\0';
667     }
668
669     if( mkdir( buffer, 0775 ) == 0 )
670     {
671         free( buffer );
672         return 1;
673     }
674
675     p = buffer + 1;
676     while( 1 )
677     {
678         char hold;
679
680         while( *p && *p != '\\' && *p != '/' ) p++;
681         hold = *p;
682         *p = 0;
683         if( ( mkdir( buffer, 0775 ) == -1 ) && ( errno == ENOENT ) )
684         {
685             fprintf( stderr, "couldn't create directory %s\n", buffer );
686             free( buffer );
687             return 0;
688         }
689         if( hold == 0 ) break;
690         *p++ = hold;
691     }
692     free( buffer );
693     return 1;
694 }
695
696 #ifdef HAVE_ZLIB_H
697
698 static int currentGzFd = -1;
699 static void * currentGzVp = NULL;
700
701 int gzopen_frontend( char *pathname, int oflags, int mode )
702 {
703     char *gzflags;
704     gzFile gzf;
705
706     switch( oflags )
707     {
708         case O_WRONLY:
709             gzflags = "wb";
710             break;
711         case O_RDONLY:
712             gzflags = "rb";
713             break;
714         case O_RDWR:
715         default:
716             errno = EINVAL;
717             return -1;
718     }
719
720     gzf = gzopen( pathname, gzflags );
721     if( !gzf )
722     {
723         errno = ENOMEM;
724         return -1;
725     }
726
727     /** Hum ... */
728     currentGzFd = 42;
729     currentGzVp = gzf;
730
731     return currentGzFd;
732 }
733
734 int gzclose_frontend( int fd )
735 {
736     if( currentGzVp != NULL && fd != -1 )
737     {
738         void *toClose = currentGzVp;
739         currentGzVp = NULL;  currentGzFd = -1;
740         return gzclose( toClose );
741     }
742     return -1;
743 }
744
745 int gzread_frontend( int fd, void *p_buffer, size_t i_length )
746 {
747     if( currentGzVp != NULL && fd != -1 )
748     {
749         return gzread( currentGzVp, p_buffer, i_length );
750     }
751     return -1;
752 }
753
754 int gzwrite_frontend( int fd, const void * p_buffer, size_t i_length )
755 {
756     if( currentGzVp != NULL && fd != -1 )
757     {
758         return gzwrite( currentGzVp, const_cast<void*>(p_buffer), i_length );
759     }
760     return -1;
761 }
762
763 #endif