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