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