Package muntjac :: Package service :: Module file_type_resolver
[hide private]
[frames] | no frames]

Source Code for Module muntjac.service.file_type_resolver

  1  # Copyright (C) 2012 Vaadin Ltd.  
  2  # Copyright (C) 2012 Richard Lincoln 
  3  #  
  4  # Licensed under the Apache License, Version 2.0 (the "License");  
  5  # you may not use this file except in compliance with the License.  
  6  # You may obtain a copy of the License at  
  7  #  
  8  #     http://www.apache.org/licenses/LICENSE-2.0  
  9  #  
 10  # Unless required by applicable law or agreed to in writing, software  
 11  # distributed under the License is distributed on an "AS IS" BASIS,  
 12  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 13  # See the License for the specific language governing permissions and  
 14  # limitations under the License. 
 15   
 16  """Defines a class that can figure out mime-types and icons related to 
 17  files.""" 
 18   
 19  from os.path import isdir 
 20   
 21  from muntjac.terminal.theme_resource import ThemeResource 
22 23 24 -class FileTypeResolver(object):
25 """Utility class that can figure out mime-types and icons related to files. 26 27 Note : The icons are associated purely to mime-types, so a file may not 28 have a custom icon accessible with this class. 29 30 @author: Vaadin Ltd. 31 @author: Richard Lincoln 32 @version: 1.1.2 33 """ 34 35 #: Default icon given if no icon is specified for a mime-type. 36 DEFAULT_ICON = ThemeResource('../runo/icons/16/document.png') 37 38 #: Default mime-type. 39 DEFAULT_MIME_TYPE = 'application/octet-stream' 40 41 #: Initial file extension to mime-type mapping. 42 _initialExtToMIMEMap = \ 43 ('application/cu-seeme csm cu,' 44 'application/dsptype tsp,' 45 'application/futuresplash spl,' 46 'application/mac-binhex40 hqx,' 47 'application/msaccess mdb,' 48 'application/msword doc dot,' 49 'application/octet-stream bin,' 50 'application/oda oda,' 51 'application/pdf pdf,' 52 'application/pgp-signature pgp,' 53 'application/postscript ps ai eps,' 54 'application/rtf rtf,' 55 'application/vnd.ms-excel xls xlb,' 56 'application/vnd.ms-powerpoint ppt pps pot,' 57 'application/vnd.wap.wmlc wmlc,' 58 'application/vnd.wap.wmlscriptc wmlsc,' 59 'application/wordperfect5.1 wp5,' 60 'application/zip zip,' 61 'application/x-123 wk,' 62 'application/x-bcpio bcpio,' 63 'application/x-chess-pgn pgn,' 64 'application/x-cpio cpio,' 65 'application/x-debian-package deb,' 66 'application/x-director dcr dir dxr,' 67 'application/x-dms dms,' 68 'application/x-dvi dvi,' 69 'application/x-xfig fig,' 70 'application/x-font pfa pfb gsf pcf pcf.Z,' 71 'application/x-gnumeric gnumeric,' 72 'application/x-gtar gtar tgz taz,' 73 'application/x-hdf hdf,' 74 'application/x-httpd-php phtml pht php,' 75 'application/x-httpd-php3 php3,' 76 'application/x-httpd-php3-source phps,' 77 'application/x-httpd-php3-preprocessed php3p,' 78 'application/x-httpd-php4 php4,' 79 'application/x-ica ica,' 80 'application/x-java-archive jar,' 81 'application/x-java-serialized-object ser,' 82 'application/x-java-vm class,' 83 'application/x-javascript js,' 84 'application/x-kchart chrt,' 85 'application/x-killustrator kil,' 86 'application/x-kpresenter kpr kpt,' 87 'application/x-kspread ksp,' 88 'application/x-kword kwd kwt,' 89 'application/x-latex latex,' 90 'application/x-lha lha,' 91 'application/x-lzh lzh,' 92 'application/x-lzx lzx,' 93 'application/x-maker frm maker frame fm fb book fbdoc,' 94 'application/x-mif mif,' 95 'application/x-msdos-program com exe bat dll,' 96 'application/x-msi msi,' 97 'application/x-netcdf nc cdf,' 98 'application/x-ns-proxy-autoconfig pac,' 99 'application/x-object o,' 100 'application/x-ogg ogg,' 101 'application/x-oz-application oza,' 102 'application/x-perl pl pm,' 103 'application/x-pkcs7-crl crl,' 104 'application/x-redhat-package-manager rpm,' 105 'application/x-shar shar,' 106 'application/x-shockwave-flash swf swfl,' 107 'application/x-star-office sdd sda,' 108 'application/x-stuffit sit,' 109 'application/x-sv4cpio sv4cpio,' 110 'application/x-sv4crc sv4crc,' 111 'application/x-tar tar,' 112 'application/x-tex-gf gf,' 113 'application/x-tex-pk pk PK,' 114 'application/x-texinfo texinfo texi,' 115 'application/x-trash ~ % bak old sik,' 116 'application/x-troff t tr roff,' 117 'application/x-troff-man man,' 118 'application/x-troff-me me,' 119 'application/x-troff-ms ms,' 120 'application/x-ustar ustar,' 121 'application/x-wais-source src,' 122 'application/x-wingz wz,' 123 'application/x-x509-ca-cert crt,' 124 'audio/basic au snd,' 125 'audio/midi mid midi,' 126 'audio/mpeg mpga mpega mp2 mp3,' 127 'audio/mpegurl m3u,' 128 'audio/prs.sid sid,' 129 'audio/x-aiff aif aiff aifc,' 130 'audio/x-gsm gsm,' 131 'audio/x-pn-realaudio ra rm ram,' 132 'audio/x-scpls pls,' 133 'audio/x-wav wav,' 134 'audio/ogg ogg,' 135 'audio/mp4 m4a,' 136 'audio/x-aac aac,' 137 'image/bitmap bmp,' 138 'image/gif gif,' 139 'image/ief ief,' 140 'image/jpeg jpeg jpg jpe,' 141 'image/pcx pcx,' 142 'image/png png,' 143 'image/svg+xml svg svgz,' 144 'image/tiff tiff tif,' 145 'image/vnd.wap.wbmp wbmp,' 146 'image/x-cmu-raster ras,' 147 'image/x-coreldraw cdr,' 148 'image/x-coreldrawpattern pat,' 149 'image/x-coreldrawtemplate cdt,' 150 'image/x-corelphotopaint cpt,' 151 'image/x-jng jng,' 152 'image/x-portable-anymap pnm,' 153 'image/x-portable-bitmap pbm,' 154 'image/x-portable-graymap pgm,' 155 'image/x-portable-pixmap ppm,' 156 'image/x-rgb rgb,' 157 'image/x-xbitmap xbm,' 158 'image/x-xpixmap xpm,' 159 'image/x-xwindowdump xwd,' 160 'text/comma-separated-values csv,' 161 'text/css css,' 162 'text/html htm html xhtml,' 163 'text/mathml mml,' 164 'text/plain txt text diff,' 165 'text/richtext rtx,' 166 'text/tab-separated-values tsv,' 167 'text/vnd.wap.wml wml,' 168 'text/vnd.wap.wmlscript wmls,' 169 'text/xml xml,' 170 'text/x-c++hdr h++ hpp hxx hh,' 171 'text/x-c++src c++ cpp cxx cc,' 172 'text/x-chdr h,' 173 'text/x-csh csh,' 174 'text/x-csrc c,' 175 'text/x-java java,' 176 'text/x-moc moc,' 177 'text/x-pascal p pas,' 178 'text/x-setext etx,' 179 'text/x-sh sh,' 180 'text/x-tcl tcl tk,' 181 'text/x-tex tex ltx sty cls,' 182 'text/x-vcalendar vcs,' 183 'text/x-vcard vcf,' 184 'video/dl dl,' 185 'video/fli fli,' 186 'video/gl gl,' 187 'video/mpeg mpeg mpg mpe,' 188 'video/quicktime qt mov,' 189 'video/x-mng mng,' 190 'video/x-ms-asf asf asx,' 191 'video/x-msvideo avi,' 192 'video/x-sgi-movie movie,' 193 'video/ogg ogv,' 194 'video/mp4 mp4,' 195 'x-world/x-vrml vrm vrml wrl') 196 197 198 #: File extension to MIME type mapping. All extensions are in lower case. 199 _extToMIMEMap = dict() 200 201 #: MIME type to Icon mapping. 202 _MIMEToIconMap = dict() 203 204 205 @classmethod
206 - def getMIMEType(cls, file_or_filename):
207 """Gets the mime-type of a file. Currently the mime-type is resolved 208 based only on the file name extension. 209 210 @param file_or_filename: 211 the file or name of the file whose mime-type is requested. 212 @return: mime-type string 213 """ 214 # Checks for nulls 215 if isinstance(file_or_filename, basestring): 216 fileName = file_or_filename 217 # Calculates the extension of the file 218 dotIndex = fileName.find('.') 219 while dotIndex >= 0 and fileName.find('.', dotIndex + 1) >= 0: 220 dotIndex = fileName.find('.', dotIndex + 1) 221 dotIndex += 1 222 if len(fileName) > dotIndex: 223 ext = fileName[dotIndex:] 224 # Ignore any query parameters 225 queryStringStart = ext.find('?') 226 if queryStringStart > 0: 227 ext = ext[:queryStringStart] 228 # Return type from extension map, if found 229 typ = cls._extToMIMEMap.get(ext.lower()) 230 if typ is not None: 231 return typ 232 return cls.DEFAULT_MIME_TYPE 233 else: 234 raise NotImplementedError 235 236 fd = file_or_filename 237 if fd is None: 238 raise ValueError, 'File can not be null' 239 # Directories 240 if isdir(fd): 241 # Drives 242 if fd.getParentFile() is None: 243 return 'inode/drive' 244 else: 245 return 'inode/directory' 246 # Return type from extension 247 return cls.getMIMEType(fd.getName())
248 249 250 @classmethod
251 - def getIcon(cls, file_or_filename):
252 """Gets the descriptive icon representing file, based on the filename. 253 First the mime-type for the given filename is resolved, and then the 254 corresponding icon is fetched from the internal icon storage. If it is 255 not found the default icon is returned. 256 257 @param file_or_filename: 258 the file or name of the file whose icon is requested. 259 @return: the icon corresponding to the given file 260 """ 261 return cls.getIconByMimeType(cls.getMIMEType(file_or_filename))
262 263 264 @classmethod
265 - def getIconByMimeType(cls, mimeType):
266 icon = cls._MIMEToIconMap.get(mimeType) 267 if icon is not None: 268 return icon 269 270 # If nothing is known about the file-type, general file 271 # icon is used 272 return cls.DEFAULT_ICON
273 274 275 @classmethod
276 - def addExtension(cls, extension, MIMEType):
277 """Adds a mime-type mapping for the given filename extension. If the 278 extension is already in the internal mapping it is overwritten. 279 280 @param extension: 281 the filename extension to be associated with 282 C{MIMEType}. 283 @param MIMEType: 284 the new mime-type for C{extension}. 285 """ 286 cls._extToMIMEMap[extension.lower()] = MIMEType
287 288 289 @classmethod
290 - def addIcon(cls, MIMEType, icon):
291 """Adds a icon for the given mime-type. If the mime-type also has a 292 corresponding icon, it is replaced with the new icon. 293 294 @param MIMEType: 295 the mime-type whose icon is to be changed. 296 @param icon: 297 the new icon to be associated with C{MIMEType}. 298 """ 299 cls._MIMEToIconMap[MIMEType] = icon
300 301 302 @classmethod
304 """Gets the internal file extension to mime-type mapping. 305 306 @return: unmodifiable map containing the current file extension to 307 mime-type mapping 308 """ 309 return dict(cls._extToMIMEMap)
310 311 312 @classmethod
314 """Gets the internal mime-type to icon mapping. 315 316 @return: map containing the current mime-type to icon mapping 317 """ 318 return dict(cls._MIMEToIconMap)
319 320 321 # Initialize extension to MIME map 322 lines = FileTypeResolver._initialExtToMIMEMap.split(',') 323 for line in lines: 324 exts = line.split() 325 typ = exts[0] 326 for ext in exts[1:]: 327 FileTypeResolver.addExtension(ext, typ) 328 329 # Initialize Icons 330 folder = ThemeResource('../runo/icons/16/folder.png') 331 FileTypeResolver.addIcon('inode/drive', folder) 332 FileTypeResolver.addIcon('inode/directory', folder) 333