Back to index

lightning-sunbird  0.9+nobinonly
nsIconChannel.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
00002  *
00003  * ***** BEGIN LICENSE BLOCK *****
00004  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00005  *
00006  * The contents of this file are subject to the Mozilla Public License Version
00007  * 1.1 (the "License"); you may not use this file except in compliance with
00008  * the License. You may obtain a copy of the License at
00009  * http://www.mozilla.org/MPL/
00010  *
00011  * Software distributed under the License is distributed on an "AS IS" basis,
00012  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00013  * for the specific language governing rights and limitations under the
00014  * License.
00015  *
00016  * The Original Code is mozilla.org code.
00017  *
00018  * The Initial Developer of the Original Code is
00019  * Brian Ryner.
00020  * Portions created by the Initial Developer are Copyright (C) 2000
00021  * the Initial Developer. All Rights Reserved.
00022  *
00023  * Contributor(s):
00024  *   Scott MacGregor <mscott@netscape.com>
00025  *   Neil Rashbrook <neil@parkwaycc.co.uk>
00026  *   Ben Goodger <ben@mozilla.org>
00027  *
00028  * Alternatively, the contents of this file may be used under the terms of
00029  * either the GNU General Public License Version 2 or later (the "GPL"), or
00030  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00031  * in which case the provisions of the GPL or the LGPL are applicable instead
00032  * of those above. If you wish to allow use of your version of this file only
00033  * under the terms of either the GPL or the LGPL, and not to allow others to
00034  * use your version of this file under the terms of the MPL, indicate your
00035  * decision by deleting the provisions above and replace them with the notice
00036  * and other provisions required by the GPL or the LGPL. If you do not delete
00037  * the provisions above, a recipient may use your version of this file under
00038  * the terms of any one of the MPL, the GPL or the LGPL.
00039  *
00040  * ***** END LICENSE BLOCK ***** */
00041 
00042 
00043 #include "nsIconChannel.h"
00044 #include "nsIIconURI.h"
00045 #include "nsIServiceManager.h"
00046 #include "nsIInterfaceRequestor.h"
00047 #include "nsIInterfaceRequestorUtils.h"
00048 #include "nsXPIDLString.h"
00049 #include "nsReadableUtils.h"
00050 #include "nsMimeTypes.h"
00051 #include "nsMemory.h"
00052 #include "nsIStringStream.h"
00053 #include "nsIURL.h"
00054 #include "nsNetUtil.h"
00055 #include "nsInt64.h"
00056 #include "nsIFile.h"
00057 #include "nsIFileURL.h"
00058 #include "nsIMIMEService.h"
00059 #include "nsCExternalHandlerService.h"
00060 #include "nsDirectoryServiceDefs.h"
00061 
00062 // we need windows.h to read out registry information...
00063 #include <windows.h>
00064 #include <shellapi.h>
00065 #include <shlobj.h>
00066 
00067 struct ICONFILEHEADER {
00068   PRUint16 ifhReserved;
00069   PRUint16 ifhType;
00070   PRUint16 ifhCount;
00071 };
00072 
00073 struct ICONENTRY {
00074   PRInt8 ieWidth;
00075   PRInt8 ieHeight;
00076   PRUint8 ieColors;
00077   PRUint8 ieReserved;
00078   PRUint16 iePlanes;
00079   PRUint16 ieBitCount;
00080   PRUint32 ieSizeImage;
00081   PRUint32 ieFileOffset;
00082 };
00083 
00084 // nsIconChannel methods
00085 nsIconChannel::nsIconChannel()
00086 {
00087 }
00088 
00089 nsIconChannel::~nsIconChannel() 
00090 {}
00091 
00092 NS_IMPL_THREADSAFE_ISUPPORTS4(nsIconChannel, 
00093                               nsIChannel, 
00094                               nsIRequest,
00095                               nsIRequestObserver,
00096                               nsIStreamListener)
00097 
00098 nsresult nsIconChannel::Init(nsIURI* uri)
00099 {
00100   NS_ASSERTION(uri, "no uri");
00101   mUrl = uri;
00102 
00103   nsresult rv;
00104   mPump = do_CreateInstance(NS_INPUTSTREAMPUMP_CONTRACTID, &rv);
00105   return rv;
00106 }
00107 
00109 // nsIRequest methods:
00110 
00111 NS_IMETHODIMP nsIconChannel::GetName(nsACString &result)
00112 {
00113   return mUrl->GetSpec(result);
00114 }
00115 
00116 NS_IMETHODIMP nsIconChannel::IsPending(PRBool *result)
00117 {
00118   return mPump->IsPending(result);
00119 }
00120 
00121 NS_IMETHODIMP nsIconChannel::GetStatus(nsresult *status)
00122 {
00123   return mPump->GetStatus(status);
00124 }
00125 
00126 NS_IMETHODIMP nsIconChannel::Cancel(nsresult status)
00127 {
00128   return mPump->Cancel(status);
00129 }
00130 
00131 NS_IMETHODIMP nsIconChannel::Suspend(void)
00132 {
00133   return mPump->Suspend();
00134 }
00135 
00136 NS_IMETHODIMP nsIconChannel::Resume(void)
00137 {
00138   return mPump->Resume();
00139 }
00140 NS_IMETHODIMP nsIconChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
00141 {
00142   *aLoadGroup = mLoadGroup;
00143   NS_IF_ADDREF(*aLoadGroup);
00144   return NS_OK;
00145 }
00146 
00147 NS_IMETHODIMP nsIconChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
00148 {
00149   mLoadGroup = aLoadGroup;
00150   return NS_OK;
00151 }
00152 
00153 NS_IMETHODIMP nsIconChannel::GetLoadFlags(PRUint32 *aLoadAttributes)
00154 {
00155   return mPump->GetLoadFlags(aLoadAttributes);
00156 }
00157 
00158 NS_IMETHODIMP nsIconChannel::SetLoadFlags(PRUint32 aLoadAttributes)
00159 {
00160   return mPump->SetLoadFlags(aLoadAttributes);
00161 }
00162 
00164 // nsIChannel methods:
00165 
00166 NS_IMETHODIMP nsIconChannel::GetOriginalURI(nsIURI* *aURI)
00167 {
00168   *aURI = mOriginalURI ? mOriginalURI : mUrl;
00169   NS_ADDREF(*aURI);
00170   return NS_OK;
00171 }
00172 
00173 NS_IMETHODIMP nsIconChannel::SetOriginalURI(nsIURI* aURI)
00174 {
00175   mOriginalURI = aURI;
00176   return NS_OK;
00177 }
00178 
00179 NS_IMETHODIMP nsIconChannel::GetURI(nsIURI* *aURI)
00180 {
00181   *aURI = mUrl;
00182   NS_IF_ADDREF(*aURI);
00183   return NS_OK;
00184 }
00185 
00186 NS_IMETHODIMP
00187 nsIconChannel::Open(nsIInputStream **_retval)
00188 {
00189   return MakeInputStream(_retval, PR_FALSE);
00190 }
00191 
00192 nsresult nsIconChannel::ExtractIconInfoFromUrl(nsIFile ** aLocalFile, PRUint32 * aDesiredImageSize, nsACString &aContentType, nsACString &aFileExtension)
00193 {
00194   nsresult rv = NS_OK;
00195   nsCOMPtr<nsIMozIconURI> iconURI (do_QueryInterface(mUrl, &rv));
00196   NS_ENSURE_SUCCESS(rv, rv);
00197 
00198   iconURI->GetImageSize(aDesiredImageSize);
00199   iconURI->GetContentType(aContentType);
00200   iconURI->GetFileExtension(aFileExtension);
00201 
00202   nsCOMPtr<nsIURI> fileURI;
00203   rv = iconURI->GetIconFile(getter_AddRefs(fileURI));
00204   if (NS_FAILED(rv) || !fileURI) return NS_OK;
00205 
00206   nsCOMPtr<nsIFileURL>    fileURL = do_QueryInterface(fileURI, &rv);
00207   if (NS_FAILED(rv) || !fileURL) return NS_OK;
00208 
00209   nsCOMPtr<nsIFile> file;
00210   rv = fileURL->GetFile(getter_AddRefs(file));
00211   if (NS_FAILED(rv) || !file) return NS_OK;
00212 
00213   return file->Clone(aLocalFile);
00214 }
00215 
00216 NS_IMETHODIMP nsIconChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *ctxt)
00217 {
00218   nsCOMPtr<nsIInputStream> inStream;
00219   nsresult rv = MakeInputStream(getter_AddRefs(inStream), PR_TRUE);
00220   if (NS_FAILED(rv))
00221     return rv;
00222 
00223   // Init our streampump
00224   rv = mPump->Init(inStream, nsInt64(-1), nsInt64(-1), 0, 0, PR_FALSE);
00225   if (NS_FAILED(rv))
00226     return rv;
00227 
00228   rv = mPump->AsyncRead(this, ctxt);
00229   if (NS_SUCCEEDED(rv)) {
00230     // Store our real listener
00231     mListener = aListener;
00232     // Add ourself to the load group, if available
00233     if (mLoadGroup)
00234       mLoadGroup->AddRequest(this, nsnull);
00235   }
00236   return rv;
00237 }
00238 
00239 static DWORD GetSpecialFolderIcon(nsIFile* aFile, int aFolder, SHFILEINFO* aSFI, UINT aInfoFlags)
00240 {
00241   DWORD shellResult = 0;
00242 
00243   if (!aFile)
00244     return shellResult;
00245 
00246   char fileNativePath[MAX_PATH];
00247   nsCAutoString fileNativePathStr;
00248   aFile->GetNativePath(fileNativePathStr);
00249   ::GetShortPathName(fileNativePathStr.get(), fileNativePath, sizeof(fileNativePath));
00250 
00251   LPITEMIDLIST idList;
00252   HRESULT hr = ::SHGetSpecialFolderLocation(NULL, aFolder, &idList);
00253   if (SUCCEEDED(hr)) {
00254     char specialNativePath[MAX_PATH];
00255     ::SHGetPathFromIDList(idList, specialNativePath);
00256     ::GetShortPathName(specialNativePath, specialNativePath, sizeof(specialNativePath));
00257   
00258     if (nsDependentCString(fileNativePath).EqualsIgnoreCase(specialNativePath)) {
00259       aInfoFlags |= (SHGFI_PIDL | SHGFI_SYSICONINDEX);
00260       shellResult = ::SHGetFileInfo((LPCTSTR)(LPCITEMIDLIST)idList, 0, aSFI, 
00261                                     sizeof(SHFILEINFO), aInfoFlags);
00262       IMalloc* pMalloc;
00263       hr = ::SHGetMalloc(&pMalloc);
00264       if (SUCCEEDED(hr)) {
00265         pMalloc->Free(idList);
00266         pMalloc->Release();
00267       }
00268     }
00269   }
00270   return shellResult;
00271 }
00272 
00273 nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, PRBool nonBlocking)
00274 {
00275   nsXPIDLCString contentType;
00276   nsCAutoString filePath;
00277   nsCOMPtr<nsIFile> localFile; // file we want an icon for
00278   PRUint32 desiredImageSize;
00279   nsresult rv = ExtractIconInfoFromUrl(getter_AddRefs(localFile), &desiredImageSize, contentType, filePath);
00280   NS_ENSURE_SUCCESS(rv, rv);
00281 
00282   // if the file exists, we are going to use it's real attributes...otherwise we only want to use it for it's extension...
00283   SHFILEINFO      sfi;
00284   UINT infoFlags = SHGFI_ICON;
00285   
00286   PRBool fileExists = PR_FALSE;
00287  
00288   if (localFile)
00289   {
00290     rv = localFile->Normalize();
00291     NS_ENSURE_SUCCESS(rv, rv);
00292 
00293     localFile->GetNativePath(filePath);
00294     if (filePath.Length() < 2 || filePath[1] != ':')
00295       return NS_ERROR_MALFORMED_URI; // UNC
00296 
00297     localFile->Exists(&fileExists);
00298   }
00299 
00300   if (!fileExists)
00301    infoFlags |= SHGFI_USEFILEATTRIBUTES;
00302 
00303 #ifndef WINCE
00304   if (desiredImageSize > 16)
00305     infoFlags |= SHGFI_SHELLICONSIZE;
00306   else
00307 #endif
00308     infoFlags |= SHGFI_SMALLICON;
00309 
00310   // if we have a content type... then use it! but for existing files, we want
00311   // to show their real icon.
00312   if (!fileExists && !contentType.IsEmpty())
00313   {
00314     nsCOMPtr<nsIMIMEService> mimeService (do_GetService(NS_MIMESERVICE_CONTRACTID, &rv));
00315     NS_ENSURE_SUCCESS(rv, rv);
00316 
00317     nsCAutoString fileExt;
00318     mimeService->GetPrimaryExtension(contentType, EmptyCString(), fileExt);
00319     // If the mime service does not know about this mime type, we show
00320     // the generic icon.
00321     // In any case, we need to insert a '.' before the extension.
00322     filePath = NS_LITERAL_CSTRING(".") + fileExt;
00323   }
00324 
00325   rv = NS_ERROR_NOT_AVAILABLE;
00326 
00327   // Is this the "Desktop" folder?
00328   DWORD shellResult = GetSpecialFolderIcon(localFile, CSIDL_DESKTOP, &sfi, infoFlags);
00329   if (!shellResult) {
00330     // Is this the "My Documents" folder?
00331     shellResult = GetSpecialFolderIcon(localFile, CSIDL_PERSONAL, &sfi, infoFlags);
00332   }
00333 
00334   // There are other "Special Folders" and Namespace entities that we are not 
00335   // fetching icons for, see: 
00336   // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp
00337   // If we ever need to get them, code to do so would be inserted here. 
00338 
00339   // Not a special folder, or something else failed above.
00340   if (!shellResult)
00341     shellResult = ::SHGetFileInfo(filePath.get(), FILE_ATTRIBUTE_ARCHIVE, &sfi, sizeof(sfi), infoFlags);
00342 
00343   if (shellResult && sfi.hIcon)
00344   {
00345     // we got a handle to an icon. Now we want to get a bitmap for the icon using GetIconInfo....
00346     ICONINFO iconInfo;
00347     if (GetIconInfo(sfi.hIcon, &iconInfo))
00348     {
00349       // we got the bitmaps, first find out their size
00350       HDC hDC = CreateCompatibleDC(NULL); // get a device context for the screen.
00351       BITMAPINFO maskInfo = {{sizeof(BITMAPINFOHEADER)}};
00352       if (GetDIBits(hDC, iconInfo.hbmMask, 0, 0, NULL, &maskInfo, DIB_RGB_COLORS) &&
00353           maskInfo.bmiHeader.biSizeImage > 0) {
00354         PRUint32 colorSize = maskInfo.bmiHeader.biWidth * maskInfo.bmiHeader.biHeight * 4;
00355         PRUint32 iconSize = sizeof(ICONFILEHEADER) + sizeof(ICONENTRY) + sizeof(BITMAPINFOHEADER) + colorSize + maskInfo.bmiHeader.biSizeImage;
00356         char *buffer = new char[iconSize];
00357         if (!buffer)
00358           rv = NS_ERROR_OUT_OF_MEMORY;
00359         else {
00360           // the data starts with an icon file header
00361           ICONFILEHEADER *iconHeader = (ICONFILEHEADER *)buffer;
00362           iconHeader->ifhReserved = 0;
00363           iconHeader->ifhType = 1;
00364           iconHeader->ifhCount = 1;
00365           // followed by the single icon entry
00366           ICONENTRY *iconEntry = (ICONENTRY *)(buffer + sizeof(ICONFILEHEADER));
00367           iconEntry->ieWidth = maskInfo.bmiHeader.biWidth;
00368           iconEntry->ieHeight = maskInfo.bmiHeader.biHeight;
00369           iconEntry->ieColors = 0;
00370           iconEntry->ieReserved = 0;
00371           iconEntry->iePlanes = 1;
00372           iconEntry->ieBitCount = 32;
00373           iconEntry->ieSizeImage = sizeof(BITMAPINFOHEADER) + colorSize + maskInfo.bmiHeader.biSizeImage;
00374           iconEntry->ieFileOffset = sizeof(ICONFILEHEADER) + sizeof(ICONENTRY);
00375           // followed by the bitmap info header and the bits
00376           LPBITMAPINFO lpBitmapInfo = (LPBITMAPINFO)(buffer + sizeof(ICONFILEHEADER) + sizeof(ICONENTRY));
00377           memcpy(lpBitmapInfo, &maskInfo.bmiHeader, sizeof(BITMAPINFOHEADER));
00378           if (GetDIBits(hDC, iconInfo.hbmMask, 0, maskInfo.bmiHeader.biHeight, buffer + sizeof(ICONFILEHEADER) + sizeof(ICONENTRY) + sizeof(BITMAPINFOHEADER) + colorSize, lpBitmapInfo, DIB_RGB_COLORS)) {
00379             PRUint32 maskSize = lpBitmapInfo->bmiHeader.biSizeImage;
00380             lpBitmapInfo->bmiHeader.biBitCount = 32;
00381             lpBitmapInfo->bmiHeader.biSizeImage = colorSize;
00382             lpBitmapInfo->bmiHeader.biClrUsed = 0;
00383             lpBitmapInfo->bmiHeader.biClrImportant = 0;
00384             if (GetDIBits(hDC, iconInfo.hbmColor, 0, maskInfo.bmiHeader.biHeight, buffer + sizeof(ICONFILEHEADER) + sizeof(ICONENTRY) + sizeof(BITMAPINFOHEADER), lpBitmapInfo, DIB_RGB_COLORS)) {
00385               // doubling the height because icons have two bitmaps
00386               lpBitmapInfo->bmiHeader.biHeight *= 2;
00387               lpBitmapInfo->bmiHeader.biSizeImage += maskSize;
00388 
00389               // Now, create a pipe and stuff our data into it
00390               nsCOMPtr<nsIInputStream> inStream;
00391               nsCOMPtr<nsIOutputStream> outStream;
00392               rv = NS_NewPipe(getter_AddRefs(inStream), getter_AddRefs(outStream),
00393                               iconSize, iconSize, nonBlocking);
00394               if (NS_SUCCEEDED(rv)) {
00395                 PRUint32 written;
00396                 rv = outStream->Write(buffer, iconSize, &written);
00397                 if (NS_SUCCEEDED(rv)) {
00398                   NS_ADDREF(*_retval = inStream);
00399                 }
00400               }
00401 
00402             } // if we got bitmap bits
00403           } // if we got mask bits
00404           delete [] buffer;
00405         } // if we allocated the buffer
00406       } // if we got mask size
00407 
00408       DeleteDC(hDC);
00409       DeleteObject(iconInfo.hbmColor);
00410       DeleteObject(iconInfo.hbmMask);
00411     } // if we got icon info
00412     DestroyIcon(sfi.hIcon);
00413   } // if we got sfi
00414 
00415   return rv;
00416 }
00417 
00418 NS_IMETHODIMP nsIconChannel::GetContentType(nsACString &aContentType) 
00419 {
00420   aContentType.AssignLiteral("image/x-icon");
00421   return NS_OK;
00422 }
00423 
00424 NS_IMETHODIMP
00425 nsIconChannel::SetContentType(const nsACString &aContentType)
00426 {
00427   // It doesn't make sense to set the content-type on this type
00428   // of channel...
00429   return NS_ERROR_FAILURE;
00430 }
00431 
00432 NS_IMETHODIMP nsIconChannel::GetContentCharset(nsACString &aContentCharset) 
00433 {
00434   aContentCharset.Truncate();
00435   return NS_OK;
00436 }
00437 
00438 NS_IMETHODIMP
00439 nsIconChannel::SetContentCharset(const nsACString &aContentCharset)
00440 {
00441   // It doesn't make sense to set the content-charset on this type
00442   // of channel...
00443   return NS_ERROR_FAILURE;
00444 }
00445 
00446 NS_IMETHODIMP nsIconChannel::GetContentLength(PRInt32 *aContentLength)
00447 {
00448   *aContentLength = mContentLength;
00449   return NS_OK;
00450 }
00451 
00452 NS_IMETHODIMP nsIconChannel::SetContentLength(PRInt32 aContentLength)
00453 {
00454   NS_NOTREACHED("nsIconChannel::SetContentLength");
00455   return NS_ERROR_NOT_IMPLEMENTED;
00456 }
00457 
00458 NS_IMETHODIMP nsIconChannel::GetOwner(nsISupports* *aOwner)
00459 {
00460   *aOwner = mOwner.get();
00461   NS_IF_ADDREF(*aOwner);
00462   return NS_OK;
00463 }
00464 
00465 NS_IMETHODIMP nsIconChannel::SetOwner(nsISupports* aOwner)
00466 {
00467   mOwner = aOwner;
00468   return NS_OK;
00469 }
00470 
00471 NS_IMETHODIMP nsIconChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
00472 {
00473   *aNotificationCallbacks = mCallbacks.get();
00474   NS_IF_ADDREF(*aNotificationCallbacks);
00475   return NS_OK;
00476 }
00477 
00478 NS_IMETHODIMP nsIconChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
00479 {
00480   mCallbacks = aNotificationCallbacks;
00481   return NS_OK;
00482 }
00483 
00484 NS_IMETHODIMP nsIconChannel::GetSecurityInfo(nsISupports * *aSecurityInfo)
00485 {
00486   *aSecurityInfo = nsnull;
00487   return NS_OK;
00488 }
00489 
00490 // nsIRequestObserver methods
00491 NS_IMETHODIMP nsIconChannel::OnStartRequest(nsIRequest* aRequest, nsISupports* aContext)
00492 {
00493   if (mListener)
00494     return mListener->OnStartRequest(this, aContext);
00495   return NS_OK;
00496 }
00497 
00498 NS_IMETHODIMP nsIconChannel::OnStopRequest(nsIRequest* aRequest, nsISupports* aContext, nsresult aStatus)
00499 {
00500   if (mListener) {
00501     mListener->OnStopRequest(this, aContext, aStatus);
00502     mListener = nsnull;
00503   }
00504 
00505   // Remove from load group
00506   if (mLoadGroup)
00507     mLoadGroup->RemoveRequest(this, nsnull, aStatus);
00508 
00509   // Drop notification callbacks to prevent cycles.
00510   mCallbacks = nsnull;
00511 
00512   return NS_OK;
00513 }
00514 
00515 // nsIStreamListener methods
00516 NS_IMETHODIMP nsIconChannel::OnDataAvailable(nsIRequest* aRequest,
00517                                              nsISupports* aContext,
00518                                              nsIInputStream* aStream,
00519                                              PRUint32 aOffset,
00520                                              PRUint32 aCount)
00521 {
00522   if (mListener)
00523     return mListener->OnDataAvailable(this, aContext, aStream, aOffset, aCount);
00524   return NS_OK;
00525 }