示例#1
0
/**
 * Delete the profile directory being reset after a backup and delete the local profile directory.
 */
nsresult
ProfileResetCleanup(nsIToolkitProfile* aOldProfile)
{
  nsresult rv;
  nsCOMPtr<nsIFile> profileDir;
  rv = aOldProfile->GetRootDir(getter_AddRefs(profileDir));
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIFile> profileLocalDir;
  rv = aOldProfile->GetLocalDir(getter_AddRefs(profileLocalDir));
  if (NS_FAILED(rv)) return rv;

  // Get the friendly name for the backup directory.
  nsCOMPtr<nsIStringBundleService> sbs = mozilla::services::GetStringBundleService();
  if (!sbs) return NS_ERROR_FAILURE;

  nsCOMPtr<nsIStringBundle> sb;
  rv = sbs->CreateBundle(kProfileProperties, getter_AddRefs(sb));
  if (!sb) return NS_ERROR_FAILURE;

  NS_ConvertUTF8toUTF16 appName(gAppData->name);
  const PRUnichar* params[] = {appName.get(), appName.get()};

  nsXPIDLString resetBackupDirectoryName;

  static const PRUnichar* kResetBackupDirectory = NS_LITERAL_STRING("resetBackupDirectory").get();
  rv = sb->FormatStringFromName(kResetBackupDirectory, params, 2,
                                getter_Copies(resetBackupDirectoryName));

  // Get info to copy the old root profile dir to the desktop as a backup.
  nsCOMPtr<nsIFile> backupDest, containerDest, profileDest;
  rv = NS_GetSpecialDirectory(NS_OS_DESKTOP_DIR, getter_AddRefs(backupDest));
  if (NS_FAILED(rv)) {
    // Fall back to the home directory if the desktop is not available.
    rv = NS_GetSpecialDirectory(NS_OS_HOME_DIR, getter_AddRefs(backupDest));
    if (NS_FAILED(rv)) return rv;
  }

  // Try to create a directory for all the backups
  backupDest->Clone(getter_AddRefs(containerDest));
  containerDest->Append(resetBackupDirectoryName);
  rv = containerDest->Create(nsIFile::DIRECTORY_TYPE, 0700);
  // It's OK if it already exists, if and only if it is a directory
  if (rv == NS_ERROR_FILE_ALREADY_EXISTS) {
    bool containerIsDir;
    rv = containerDest->IsDirectory(&containerIsDir);
    if (NS_FAILED(rv) || !containerIsDir) {
      return rv;
    }
  } else if (NS_FAILED(rv)) {
    return rv;
  }

  // Get the name of the profile
  nsAutoString leafName;
  rv = profileDir->GetLeafName(leafName);
  if (NS_FAILED(rv)) return rv;

  // Try to create a unique directory for the profile:
  containerDest->Clone(getter_AddRefs(profileDest));
  profileDest->Append(leafName);
  rv = profileDest->CreateUnique(nsIFile::DIRECTORY_TYPE, 0700);
  if (NS_FAILED(rv)) return rv;

  // Get the unique profile name
  rv = profileDest->GetLeafName(leafName);
  if (NS_FAILED(rv)) return rv;

  // Delete the empty directory that CreateUnique just created.
  rv = profileDest->Remove(false);
  if (NS_FAILED(rv)) return rv;

  // Show a progress window while the cleanup happens since the disk I/O can take time.
  nsCOMPtr<nsIWindowWatcher> windowWatcher(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
  if (!windowWatcher) return NS_ERROR_FAILURE;

  nsCOMPtr<nsIAppStartup> appStartup(do_GetService(NS_APPSTARTUP_CONTRACTID));
  if (!appStartup) return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMWindow> progressWindow;
  rv = windowWatcher->OpenWindow(nullptr,
                                 kResetProgressURL,
                                 "_blank",
                                 "centerscreen,chrome,titlebar",
                                 NULL,
                                 getter_AddRefs(progressWindow));
  if (NS_FAILED(rv)) return rv;

  // Create a new thread to do the bulk of profile cleanup to stay responsive.
  nsCOMPtr<nsIThreadManager> tm = do_GetService(NS_THREADMANAGER_CONTRACTID);
  nsCOMPtr<nsIThread> cleanupThread;
  rv = tm->NewThread(0, 0, getter_AddRefs(cleanupThread));
  if (NS_SUCCEEDED(rv)) {
    nsCOMPtr<nsIRunnable> runnable = new ProfileResetCleanupAsyncTask(profileDir, profileLocalDir,
                                                                      containerDest, leafName);
    cleanupThread->Dispatch(runnable, nsIThread::DISPATCH_NORMAL);
    // The result callback will shut down the worker thread.

    nsIThread *thread = NS_GetCurrentThread();
    // Wait for the cleanup thread to complete.
    while(!gProfileResetCleanupCompleted) {
      NS_ProcessNextEvent(thread);
    }
  } else {
    gProfileResetCleanupCompleted = true;
    NS_WARNING("Cleanup thread creation failed");
    return rv;
  }
  // Close the progress window now that the cleanup thread is done.
  progressWindow->Close();

  // Delete the old profile from profiles.ini. The folder was already deleted by the thread above.
  rv = aOldProfile->Remove(false);
  if (NS_FAILED(rv)) NS_WARNING("Could not remove the profile");

  return rv;
}
nsresult
nsMsgAccountManagerDataSource::appendGenericSettingsResources(nsIMsgIncomingServer *server, nsISupportsArray *aNodeArray)
{
  nsresult rv;

  nsCOMPtr<nsICategoryManager> catman = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsISimpleEnumerator> e;
  rv = catman->EnumerateCategory(MAILNEWS_ACCOUNTMANAGER_EXTENSIONS, getter_AddRefs(e));
  if(NS_SUCCEEDED(rv) && e) {
    while (PR_TRUE) {
      nsCOMPtr<nsISupportsCString> catEntry;
      rv = e->GetNext(getter_AddRefs(catEntry));
      if (NS_FAILED(rv) || !catEntry)
        break;

      nsCAutoString entryString;
      rv = catEntry->GetData(entryString);
      if (NS_FAILED(rv))
        break;

      nsCString contractidString;
      rv = catman->GetCategoryEntry(MAILNEWS_ACCOUNTMANAGER_EXTENSIONS, entryString.get(), getter_Copies(contractidString));
      if (NS_FAILED(rv))
        break;

      nsCOMPtr <nsIMsgAccountManagerExtension> extension =
        do_GetService(contractidString.get(), &rv);
      if (NS_FAILED(rv) || !extension)
        break;

      PRBool showPanel;
      rv = extension->ShowPanel(server, &showPanel);
      if (NS_FAILED(rv))
        break;

      if (showPanel) {
        nsCString name;
        rv = extension->GetName(name);
        if (NS_FAILED(rv))
          break;

        rv = appendGenericSetting(name.get(), aNodeArray);
        if (NS_FAILED(rv))
          break;
      }
    }
  }
  return NS_OK;
}
//------------------------------------------------------------------
// Displays the native Print Dialog
static nsresult 
ShowNativePrintDialog(HWND              aHWnd,
                      nsIPrintSettings* aPrintSettings)
{
  //NS_ENSURE_ARG_POINTER(aHWnd);
  NS_ENSURE_ARG_POINTER(aPrintSettings);

  gDialogWasExtended  = false;

  HGLOBAL hGlobalDevMode = NULL;
  HGLOBAL hDevNames      = NULL;

  // Get the Print Name to be used
  nsXPIDLString printerName;
  aPrintSettings->GetPrinterName(getter_Copies(printerName));

  // If there is no name then use the default printer
  if (printerName.IsEmpty()) {
    GetDefaultPrinterNameFromGlobalPrinters(printerName);
  } else {
    HANDLE hPrinter = NULL;
    if(!::OpenPrinterW(const_cast<wchar_t*>(printerName.get()), &hPrinter, NULL)) {
      // If the last used printer is not found, we should use default printer.
      GetDefaultPrinterNameFromGlobalPrinters(printerName);
    } else {
      ::ClosePrinter(hPrinter);
    }
  }

  // Now create a DEVNAMES struct so the the dialog is initialized correctly.

  uint32_t len = printerName.Length();
  hDevNames = (HGLOBAL)::GlobalAlloc(GHND, sizeof(wchar_t) * (len + 1) + 
                                     sizeof(DEVNAMES));
  if (!hDevNames) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  DEVNAMES* pDevNames = (DEVNAMES*)::GlobalLock(hDevNames);
  if (!pDevNames) {
    ::GlobalFree(hDevNames);
    return NS_ERROR_FAILURE;
  }
  pDevNames->wDriverOffset = sizeof(DEVNAMES)/sizeof(wchar_t);
  pDevNames->wDeviceOffset = sizeof(DEVNAMES)/sizeof(wchar_t);
  pDevNames->wOutputOffset = sizeof(DEVNAMES)/sizeof(wchar_t)+len;
  pDevNames->wDefault      = 0;

  memcpy(pDevNames+1, printerName, (len + 1) * sizeof(wchar_t));
  ::GlobalUnlock(hDevNames);

  // Create a Moveable Memory Object that holds a new DevMode
  // from the Printer Name
  // The PRINTDLG.hDevMode requires that it be a moveable memory object
  // NOTE: We only need to free hGlobalDevMode when the dialog is cancelled
  // When the user prints, it comes back in the printdlg struct and 
  // is used and cleaned up later
  hGlobalDevMode = CreateGlobalDevModeAndInit(printerName, aPrintSettings);

  // Prepare to Display the Print Dialog
  PRINTDLGW  prntdlg;
  memset(&prntdlg, 0, sizeof(PRINTDLGW));

  prntdlg.lStructSize = sizeof(prntdlg);
  prntdlg.hwndOwner   = aHWnd;
  prntdlg.hDevMode    = hGlobalDevMode;
  prntdlg.hDevNames   = hDevNames;
  prntdlg.hDC         = NULL;
  prntdlg.Flags       = PD_ALLPAGES | PD_RETURNIC | 
                        PD_USEDEVMODECOPIESANDCOLLATE | PD_COLLATE;

  // if there is a current selection then enable the "Selection" radio button
  int16_t howToEnableFrameUI = nsIPrintSettings::kFrameEnableNone;
  bool isOn;
  aPrintSettings->GetPrintOptions(nsIPrintSettings::kEnableSelectionRB, &isOn);
  if (!isOn) {
    prntdlg.Flags |= PD_NOSELECTION;
  }
  aPrintSettings->GetHowToEnableFrameUI(&howToEnableFrameUI);

  int32_t pg = 1;
  aPrintSettings->GetStartPageRange(&pg);
  prntdlg.nFromPage           = pg;
  
  aPrintSettings->GetEndPageRange(&pg);
  prntdlg.nToPage             = pg;

  prntdlg.nMinPage            = 1;
  prntdlg.nMaxPage            = 0xFFFF;
  prntdlg.nCopies             = 1;
  prntdlg.lpfnSetupHook       = NULL;
  prntdlg.lpSetupTemplateName = NULL;
  prntdlg.hPrintTemplate      = NULL;
  prntdlg.hSetupTemplate      = NULL;

  prntdlg.hInstance           = NULL;
  prntdlg.lpPrintTemplateName = NULL;

  if (!ShouldExtendPrintDialog()) {
    prntdlg.lCustData         = 0;
    prntdlg.lpfnPrintHook     = NULL;
  } else {
    // Set up print dialog "hook" procedure for extending the dialog
    prntdlg.lCustData         = (DWORD)howToEnableFrameUI;
    prntdlg.lpfnPrintHook     = (LPPRINTHOOKPROC)PrintHookProc;
    prntdlg.Flags            |= PD_ENABLEPRINTHOOK;
  }

  BOOL result = ::PrintDlgW(&prntdlg);

  if (TRUE == result) {
    // check to make sure we don't have any NULL pointers
    NS_ENSURE_TRUE(aPrintSettings && prntdlg.hDevMode, NS_ERROR_FAILURE);

    if (prntdlg.hDevNames == NULL) {
      ::GlobalFree(hGlobalDevMode);
      return NS_ERROR_FAILURE;
    }
    // Lock the deviceNames and check for NULL
    DEVNAMES *devnames = (DEVNAMES *)::GlobalLock(prntdlg.hDevNames);
    if (devnames == NULL) {
      ::GlobalFree(hGlobalDevMode);
      return NS_ERROR_FAILURE;
    }

    wchar_t* device = &(((wchar_t *)devnames)[devnames->wDeviceOffset]);
    wchar_t* driver = &(((wchar_t *)devnames)[devnames->wDriverOffset]);

    // Check to see if the "Print To File" control is checked
    // then take the name from devNames and set it in the PrintSettings
    //
    // NOTE:
    // As per Microsoft SDK documentation the returned value offset from
    // devnames->wOutputOffset is either "FILE:" or NULL
    // if the "Print To File" checkbox is checked it MUST be "FILE:"
    // We assert as an extra safety check.
    if (prntdlg.Flags & PD_PRINTTOFILE) {
      wchar_t* fileName = &(((wchar_t *)devnames)[devnames->wOutputOffset]);
      NS_ASSERTION(wcscmp(fileName, L"FILE:") == 0, "FileName must be `FILE:`");
      aPrintSettings->SetToFileName(fileName);
      aPrintSettings->SetPrintToFile(true);
    } else {
      // clear "print to file" info
      aPrintSettings->SetPrintToFile(false);
      aPrintSettings->SetToFileName(nullptr);
    }

    nsCOMPtr<nsIPrintSettingsWin> psWin(do_QueryInterface(aPrintSettings));
    if (!psWin) {
      ::GlobalFree(hGlobalDevMode);
      return NS_ERROR_FAILURE;
    }

    // Setup local Data members
    psWin->SetDeviceName(device);
    psWin->SetDriverName(driver);

#if defined(DEBUG_rods) || defined(DEBUG_dcone)
    wprintf(L"printer: driver %s, device %s  flags: %d\n", driver, device, prntdlg.Flags);
#endif
    // fill the print options with the info from the dialog

    aPrintSettings->SetPrinterName(device);

    if (prntdlg.Flags & PD_SELECTION) {
      aPrintSettings->SetPrintRange(nsIPrintSettings::kRangeSelection);

    } else if (prntdlg.Flags & PD_PAGENUMS) {
      aPrintSettings->SetPrintRange(nsIPrintSettings::kRangeSpecifiedPageRange);
      aPrintSettings->SetStartPageRange(prntdlg.nFromPage);
      aPrintSettings->SetEndPageRange(prntdlg.nToPage);

    } else { // (prntdlg.Flags & PD_ALLPAGES)
      aPrintSettings->SetPrintRange(nsIPrintSettings::kRangeAllPages);
    }

    if (howToEnableFrameUI != nsIPrintSettings::kFrameEnableNone) {
      // make sure the dialog got extended
      if (gDialogWasExtended) {
        // check to see about the frame radio buttons
        switch (gFrameSelectedRadioBtn) {
          case rad4: 
            aPrintSettings->SetPrintFrameType(nsIPrintSettings::kFramesAsIs);
            break;
          case rad5: 
            aPrintSettings->SetPrintFrameType(nsIPrintSettings::kSelectedFrame);
            break;
          case rad6: 
            aPrintSettings->SetPrintFrameType(nsIPrintSettings::kEachFrameSep);
            break;
        } // switch
      } else {
        // if it didn't get extended then have it default to printing
        // each frame separately
        aPrintSettings->SetPrintFrameType(nsIPrintSettings::kEachFrameSep);
      }
    } else {
      aPrintSettings->SetPrintFrameType(nsIPrintSettings::kNoFrames);
    }
    // Unlock DeviceNames
    ::GlobalUnlock(prntdlg.hDevNames);

    // Transfer the settings from the native data to the PrintSettings
    LPDEVMODEW devMode = (LPDEVMODEW)::GlobalLock(prntdlg.hDevMode);
    if (devMode == NULL) {
      ::GlobalFree(hGlobalDevMode);
      return NS_ERROR_FAILURE;
    }
    psWin->SetDevMode(devMode); // copies DevMode
    SetPrintSettingsFromDevMode(aPrintSettings, devMode);
    ::GlobalUnlock(prntdlg.hDevMode);

#if defined(DEBUG_rods) || defined(DEBUG_dcone)
    bool    printSelection = prntdlg.Flags & PD_SELECTION;
    bool    printAllPages  = prntdlg.Flags & PD_ALLPAGES;
    bool    printNumPages  = prntdlg.Flags & PD_PAGENUMS;
    int32_t fromPageNum    = 0;
    int32_t toPageNum      = 0;

    if (printNumPages) {
      fromPageNum = prntdlg.nFromPage;
      toPageNum   = prntdlg.nToPage;
    } 
    if (printSelection) {
      printf("Printing the selection\n");

    } else if (printAllPages) {
      printf("Printing all the pages\n");

    } else {
      printf("Printing from page no. %d to %d\n", fromPageNum, toPageNum);
    }
#endif
    
  } else {
    ::SetFocus(aHWnd);
    aPrintSettings->SetIsCancelled(true);
    if (hGlobalDevMode) ::GlobalFree(hGlobalDevMode);
    return NS_ERROR_ABORT;
  }

  return NS_OK;
}
nsresult
nsOperaProfileMigrator::CopySmartKeywords(nsINavBookmarksService* aBMS, 
                                          nsIStringBundle* aBundle,
                                          PRInt64 aParentFolder)
{
  nsresult rv;

  nsCOMPtr<nsIFile> smartKeywords;
  mOperaProfile->Clone(getter_AddRefs(smartKeywords));
  smartKeywords->Append(NS_LITERAL_STRING("search.ini"));

  nsCOMPtr<nsILocalFile> lf(do_QueryInterface(smartKeywords));
  nsINIParser parser;
  if (!lf || NS_FAILED(parser.Init(lf)))
    return NS_OK;

  nsString sourceNameOpera;
  rv = aBundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(),
                                  getter_Copies(sourceNameOpera));
  NS_ENSURE_SUCCESS(rv, rv);

  const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() };
  nsString importedSearchUrlsTitle;
  rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchURLsFolder").get(),
                                     sourceNameStrings, 1, 
                                     getter_Copies(importedSearchUrlsTitle));
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt64 keywordsFolder;
  rv = aBMS->CreateFolder(aParentFolder,
                          NS_ConvertUTF16toUTF8(importedSearchUrlsTitle),
                          nsINavBookmarksService::DEFAULT_INDEX,
                          &keywordsFolder);
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt32 sectionIndex = 1;
  nsCAutoString name, url, keyword;
  do {
    nsCAutoString section("Search Engine ");
    section.AppendInt(sectionIndex++);

    rv = parser.GetString(section.get(), "Name", name);
    if (NS_FAILED(rv)) {
      // No more smart keywords found, stop parsing the file.
      break;
    }
    if (name.IsEmpty())
      continue;

    rv = parser.GetString(section.get(), "URL", url);
    if (NS_FAILED(rv) || url.IsEmpty())
      continue;

    rv = parser.GetString(section.get(), "Key", keyword);
    if (NS_FAILED(rv) || keyword.IsEmpty())
      continue;

    PRInt32 post;
    rv = GetInteger(parser, section.get(), "Is post", &post);
    if (NS_SUCCEEDED(rv) && post)
      continue;

    PRUint32 length = name.Length();
    PRInt32 index = 0;
    do {
      index = name.FindChar('&', index);
      if ((PRUint32)index >= length - 2)
        break;

      // Assume "&&" is an escaped ampersand in the search query title. 
      if (name.CharAt(index + 1) == '&') {
        name.Cut(index, 1);
        index += 2;
        continue;
      }

      name.Cut(index, 1);
    }
    while ((PRUint32)index < length);

    nsCOMPtr<nsIURI> uri;
    if (NS_FAILED(NS_NewURI(getter_AddRefs(uri), url.get())) || !uri)
      continue;

    nsCAutoString hostCStr;
    uri->GetHost(hostCStr);
    NS_ConvertASCIItoUTF16 host(hostCStr);

    const PRUnichar* descStrings[] = { NS_ConvertUTF8toUTF16(keyword).get(),
                                       host.get() };
    nsString keywordDesc;
    rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchUrlDesc").get(),
                                       descStrings, 2,
                                       getter_Copies(keywordDesc));
    NS_ENSURE_SUCCESS(rv, rv);

    PRInt64 newId;
    rv = aBMS->InsertBookmark(keywordsFolder, uri,
                              nsINavBookmarksService::DEFAULT_INDEX,
                              name, &newId);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = aBMS->SetKeywordForBookmark(newId, NS_ConvertUTF8toUTF16(keyword));
    NS_ENSURE_SUCCESS(rv, rv);
    // TODO Bug 397771: set bookmark description to keywordDesc.
  }
  while (1);
  
  return rv;
}
NS_METHOD Comm4xMailRegister(nsIComponentManager *aCompMgr,
                       nsIFile *aPath, const char *registryLocation,
                       const char *componentType,
                       const nsModuleComponentInfo *info)
{   
    nsresult rv;

    nsCOMPtr<nsICategoryManager> catMan = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
    if (NS_SUCCEEDED(rv)) {
        nsXPIDLCString  replace;
        char *theCID = kComm4xMailImportCID.ToString();
        rv = catMan->AddCategoryEntry("mailnewsimport", theCID, kComm4xMailSupportsString, PR_TRUE, PR_TRUE, getter_Copies(replace));
        nsCRT::free(theCID);
    }

    if (NS_FAILED(rv)) {
        IMPORT_LOG0("*** ERROR: Problem registering Comm4xMail Import component in the category manager\n");
    }

    return rv;
}
示例#6
0
nsresult
nsThebesDeviceContext::SetDPI()
{
    float dpi = -1.0f;

    // PostScript, PDF and Mac (when printing) all use 72 dpi
    // Use a printing DC to determine the other dpi values
    if (mPrintingSurface) {
        switch (mPrintingSurface->GetType()) {
            case gfxASurface::SurfaceTypePDF:
            case gfxASurface::SurfaceTypePS:
            case gfxASurface::SurfaceTypeQuartz:
                dpi = 72.0f;
                break;
#ifdef XP_WIN
            case gfxASurface::SurfaceTypeWin32:
            case gfxASurface::SurfaceTypeWin32Printing: {
                PRInt32 OSVal = GetDeviceCaps(GetPrintHDC(), LOGPIXELSY);
                dpi = 144.0f;
                mPrintingScale = float(OSVal) / dpi;
                break;
            }
#endif
#ifdef XP_OS2
            case gfxASurface::SurfaceTypeOS2:
                LONG lDPI;
                if (DevQueryCaps(GetPrintHDC(), CAPS_VERTICAL_FONT_RES, 1, &lDPI))
                    dpi = lDPI;
                break;
#endif
            default:
                NS_NOTREACHED("Unexpected printing surface type");
                break;
        }

        mAppUnitsPerDevNotScaledPixel =
          NS_lround((AppUnitsPerCSSPixel() * 96) / dpi);
    } else {
        nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);

        // A value of -1 means use the maximum of 96 and the system DPI.
        // A value of 0 means use the system DPI. A positive value is used as the DPI.
        // This sets the physical size of a device pixel and thus controls the
        // interpretation of physical units.
        PRInt32 prefDPI = -1;
        if (prefs) {
            nsresult rv = prefs->GetIntPref("layout.css.dpi", &prefDPI);
            if (NS_FAILED(rv)) {
                prefDPI = -1;
            }
        }

        if (prefDPI > 0) {
            dpi = prefDPI;
        } else if (mWidget) {
            dpi = mWidget->GetDPI();

            if (prefDPI < 0) {
                dpi = PR_MAX(96.0f, dpi);
            }
        } else {
            dpi = 96.0f;
        }

        // The number of device pixels per CSS pixel. A value <= 0 means choose
        // automatically based on the DPI. A positive value is used as-is. This effectively
        // controls the size of a CSS "px".
        float devPixelsPerCSSPixel = -1.0;

        if (prefs) {
            nsXPIDLCString prefString;
            nsresult rv = prefs->GetCharPref("layout.css.devPixelsPerPx", getter_Copies(prefString));
            if (NS_SUCCEEDED(rv) && !prefString.IsEmpty()) {
                devPixelsPerCSSPixel = static_cast<float>(atof(prefString));
            }
        }

        if (devPixelsPerCSSPixel <= 0) {
            if (mWidget) {
                devPixelsPerCSSPixel = mWidget->GetDefaultScale();
            } else {
                devPixelsPerCSSPixel = 1.0;
            }
        }

        mAppUnitsPerDevNotScaledPixel =
            PR_MAX(1, NS_lround(AppUnitsPerCSSPixel() / devPixelsPerCSSPixel));
    }

    NS_ASSERTION(dpi != -1.0, "no dpi set");

    mAppUnitsPerPhysicalInch = NS_lround(dpi * mAppUnitsPerDevNotScaledPixel);
    UpdateScaledAppUnits();

    return NS_OK;
}
示例#7
0
RefPtr<NrIceCtx> NrIceCtx::Create(const std::string& name,
                                  bool offerer,
                                  bool allow_loopback,
                                  bool tcp_enabled,
                                  bool allow_link_local,
                                  bool hide_non_default,
                                  Policy policy) {
   RefPtr<NrIceCtx> ctx = new NrIceCtx(name, offerer, policy);

  // Initialize the crypto callbacks and logging stuff
  if (!initialized) {
    NR_reg_init(NR_REG_MODE_LOCAL);
    RLogRingBuffer::CreateInstance();
    nr_crypto_vtbl = &nr_ice_crypto_nss_vtbl;
    initialized = true;

    // Set the priorites for candidate type preferences.
    // These numbers come from RFC 5245 S. 4.1.2.2
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_SRV_RFLX, 100);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_PEER_RFLX, 110);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_HOST, 126);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_RELAYED, 5);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_SRV_RFLX_TCP, 99);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_PEER_RFLX_TCP, 109);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_HOST_TCP, 125);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_RELAYED_TCP, 0);

    int32_t stun_client_maximum_transmits = 7;
    int32_t ice_trickle_grace_period = 5000;
    int32_t ice_tcp_so_sock_count = 3;
    int32_t ice_tcp_listen_backlog = 10;
    nsAutoCString force_net_interface;
#ifndef MOZILLA_XPCOMRT_API
    nsresult res;
    nsCOMPtr<nsIPrefService> prefs =
      do_GetService("@mozilla.org/preferences-service;1", &res);

    if (NS_SUCCEEDED(res)) {
      nsCOMPtr<nsIPrefBranch> branch = do_QueryInterface(prefs);
      if (branch) {
        branch->GetIntPref(
            "media.peerconnection.ice.stun_client_maximum_transmits",
            &stun_client_maximum_transmits);
        branch->GetIntPref(
            "media.peerconnection.ice.trickle_grace_period",
            &ice_trickle_grace_period);
        branch->GetIntPref(
            "media.peerconnection.ice.tcp_so_sock_count",
            &ice_tcp_so_sock_count);
        branch->GetIntPref(
            "media.peerconnection.ice.tcp_listen_backlog",
            &ice_tcp_listen_backlog);
        branch->GetCharPref(
            "media.peerconnection.ice.force_interface",
            getter_Copies(force_net_interface));
      }
    }
#endif
    NR_reg_set_uint4((char *)"stun.client.maximum_transmits",
                     stun_client_maximum_transmits);
    NR_reg_set_uint4((char *)NR_ICE_REG_TRICKLE_GRACE_PERIOD,
                     ice_trickle_grace_period);
    NR_reg_set_int4((char *)NR_ICE_REG_ICE_TCP_SO_SOCK_COUNT,
                     ice_tcp_so_sock_count);
    NR_reg_set_int4((char *)NR_ICE_REG_ICE_TCP_LISTEN_BACKLOG,
                     ice_tcp_listen_backlog);

    NR_reg_set_char((char *)NR_ICE_REG_ICE_TCP_DISABLE, !tcp_enabled);

    if (allow_loopback) {
      NR_reg_set_char((char *)NR_STUN_REG_PREF_ALLOW_LOOPBACK_ADDRS, 1);
    }

    if (allow_link_local) {
      NR_reg_set_char((char *)NR_STUN_REG_PREF_ALLOW_LINK_LOCAL_ADDRS, 1);
    }
    if (force_net_interface.Length() > 0) {
      // Stupid cast.... but needed
      const nsCString& flat = PromiseFlatCString(static_cast<nsACString&>(force_net_interface));
      NR_reg_set_string((char *)NR_ICE_REG_PREF_FORCE_INTERFACE_NAME, const_cast<char*>(flat.get()));
    }
  }

  // Create the ICE context
  int r;

  UINT4 flags = offerer ? NR_ICE_CTX_FLAGS_OFFERER:
      NR_ICE_CTX_FLAGS_ANSWERER;
  flags |= NR_ICE_CTX_FLAGS_AGGRESSIVE_NOMINATION;
  if (policy == ICE_POLICY_RELAY) {
    flags |= NR_ICE_CTX_FLAGS_RELAY_ONLY;
  }

  if (hide_non_default)
    flags |= NR_ICE_CTX_FLAGS_ONLY_DEFAULT_ADDRS;

  r = nr_ice_ctx_create(const_cast<char *>(name.c_str()), flags,
                        &ctx->ctx_);
  if (r) {
    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE ctx for '" << name << "'");
    return nullptr;
  }

  nr_interface_prioritizer *prioritizer = CreateInterfacePrioritizer();
  if (!prioritizer) {
    MOZ_MTLOG(LogLevel::Error, "Couldn't create interface prioritizer.");
    return nullptr;
  }

  r = nr_ice_ctx_set_interface_prioritizer(ctx->ctx_, prioritizer);
  if (r) {
    MOZ_MTLOG(LogLevel::Error, "Couldn't set interface prioritizer.");
    return nullptr;
  }

  if (ctx->generating_trickle()) {
    r = nr_ice_ctx_set_trickle_cb(ctx->ctx_, &NrIceCtx::trickle_cb, ctx);
    if (r) {
      MOZ_MTLOG(ML_ERROR, "Couldn't set trickle cb for '" << name << "'");
      return nullptr;
    }
  }

  // Create the handler objects
  ctx->ice_handler_vtbl_ = new nr_ice_handler_vtbl();
  ctx->ice_handler_vtbl_->select_pair = &NrIceCtx::select_pair;
  ctx->ice_handler_vtbl_->stream_ready = &NrIceCtx::stream_ready;
  ctx->ice_handler_vtbl_->stream_failed = &NrIceCtx::stream_failed;
  ctx->ice_handler_vtbl_->ice_completed = &NrIceCtx::ice_completed;
  ctx->ice_handler_vtbl_->msg_recvd = &NrIceCtx::msg_recvd;
  ctx->ice_handler_vtbl_->ice_checking = &NrIceCtx::ice_checking;

  ctx->ice_handler_ = new nr_ice_handler();
  ctx->ice_handler_->vtbl = ctx->ice_handler_vtbl_;
  ctx->ice_handler_->obj = ctx;

  // Create the peer ctx. Because we do not support parallel forking, we
  // only have one peer ctx.
  std::string peer_name = name + ":default";
  r = nr_ice_peer_ctx_create(ctx->ctx_, ctx->ice_handler_,
                             const_cast<char *>(peer_name.c_str()),
                             &ctx->peer_);
  if (r) {
    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE peer ctx for '" << name << "'");
    return nullptr;
  }

  nsresult rv;
  ctx->sts_target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);

  if (!NS_SUCCEEDED(rv))
    return nullptr;

  return ctx;
}
示例#8
0
nsresult
PrintingParent::ShowPrintDialog(PBrowserParent* aParent,
                                const PrintData& aData,
                                PrintData* aResult)
{
  // If aParent is null this call is just being used to get print settings from
  // the printer for print preview.
  bool isPrintPreview = !aParent;
  nsCOMPtr<nsPIDOMWindowOuter> parentWin;
  if (aParent) {
    parentWin = DOMWindowFromBrowserParent(aParent);
    if (!parentWin) {
      return NS_ERROR_FAILURE;
    }
  }

  nsCOMPtr<nsIPrintingPromptService> pps(do_GetService("@mozilla.org/embedcomp/printingprompt-service;1"));
  if (!pps) {
    return NS_ERROR_FAILURE;
  }

  // The initSettings we got can be wrapped using
  // PrintDataUtils' MockWebBrowserPrint, which implements enough of
  // nsIWebBrowserPrint to keep the dialogs happy.
  nsCOMPtr<nsIWebBrowserPrint> wbp = new MockWebBrowserPrint(aData);

  // Use the existing RemotePrintJob and its settings, if we have one, to make
  // sure they stay current.
  RemotePrintJobParent* remotePrintJob =
    static_cast<RemotePrintJobParent*>(aData.remotePrintJobParent());
  nsCOMPtr<nsIPrintSettings> settings;
  nsresult rv;
  if (remotePrintJob) {
    settings = remotePrintJob->GetPrintSettings();
  } else {
    rv = mPrintSettingsSvc->GetNewPrintSettings(getter_AddRefs(settings));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // We only want to use the print silently setting from the parent.
  bool printSilently;
  rv = settings->GetPrintSilent(&printSilently);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mPrintSettingsSvc->DeserializeToPrintSettings(aData, settings);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = settings->SetPrintSilent(printSilently);
  NS_ENSURE_SUCCESS(rv, rv);

  // If this is for print preview or we are printing silently then we just need
  // to initialize the print settings with anything specific from the printer.
  if (isPrintPreview || printSilently ||
      Preferences::GetBool("print.always_print_silent", printSilently)) {
    nsXPIDLString printerName;
    rv = settings->GetPrinterName(getter_Copies(printerName));
    NS_ENSURE_SUCCESS(rv, rv);

    settings->SetIsInitializedFromPrinter(false);
    mPrintSettingsSvc->InitPrintSettingsFromPrinter(printerName, settings);
  } else {
    rv = pps->ShowPrintDialog(parentWin, wbp, settings);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (isPrintPreview) {
    // For print preview we don't want a RemotePrintJob just the settings.
    rv = mPrintSettingsSvc->SerializeToPrintData(settings, nullptr, aResult);
  } else {
    rv = SerializeAndEnsureRemotePrintJob(settings, nullptr, remotePrintJob,
                                          aResult);
  }

  return rv;
}
示例#9
0
nsresult
nsProfileMigrator::GetDefaultMailMigratorKey(nsACString& aKey, nsCOMPtr<nsIMailProfileMigrator>& mailMigrator)
{
  // look up the value of profile.force.migration in case we are supposed to force migration using a particular
  // migrator....
  nsresult rv = NS_OK;
  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString forceMigrationType;
  prefs->GetCharPref("profile.force.migration", getter_Copies(forceMigrationType));

  // if we are being forced to migrate to a particular migration type, then create an instance of that migrator
  // and return it.
  NS_NAMED_LITERAL_CSTRING(migratorPrefix,
                           NS_MAILPROFILEMIGRATOR_CONTRACTID_PREFIX);
  nsCAutoString migratorID;
  if (!forceMigrationType.IsEmpty())
  {
    bool exists = false;
    migratorID = migratorPrefix;
    migratorID.Append(forceMigrationType);
    mailMigrator = do_CreateInstance(migratorID.get());
    if (!mailMigrator)
      return NS_ERROR_NOT_AVAILABLE;

    mailMigrator->GetSourceExists(&exists);
    /* trying to force migration on a source which doesn't
     * have any profiles.
     */
    if (!exists)
      return NS_ERROR_NOT_AVAILABLE;
    aKey = forceMigrationType;
    return NS_OK;
  }

  #define MAX_SOURCE_LENGTH 10
  const char sources[][MAX_SOURCE_LENGTH] = {
    "seamonkey",
    "oexpress",
    "outlook",
    "eudora",
    ""
  };
  for (PRUint32 i = 0; sources[i][0]; ++i)
  {
    migratorID = migratorPrefix;
    migratorID.Append(sources[i]);
    mailMigrator = do_CreateInstance(migratorID.get());
    if (!mailMigrator)
      continue;

    bool exists = false;
    mailMigrator->GetSourceExists(&exists);
    if (exists)
    {
      mailMigrator = nsnull;
      return NS_OK;
    }
  }

  return NS_ERROR_NOT_AVAILABLE;
}
示例#10
0
NS_IMETHODIMP
nsIndexedToHTML::OnIndexAvailable(nsIRequest *aRequest,
                                  nsISupports *aCtxt,
                                  nsIDirIndex *aIndex) {
    nsresult rv;
    if (!aIndex)
        return NS_ERROR_NULL_POINTER;

    nsCString pushBuffer;
    pushBuffer.AppendLiteral("<tr");

    // We don't know the file's character set yet, so retrieve the raw bytes
    // which will be decoded by the HTML parser.
    nsXPIDLCString loc;
    aIndex->GetLocation(getter_Copies(loc));

    // Adjust the length in case unescaping shortened the string.
    loc.Truncate(nsUnescapeCount(loc.BeginWriting()));
    if (loc.First() == PRUnichar('.'))
        pushBuffer.AppendLiteral(" class=\"hidden-object\"");

    pushBuffer.AppendLiteral(">\n <td sortable-data=\"");

    // The sort key is the name of the item, prepended by either 0, 1 or 2
    // in order to group items.
    uint32_t type;
    aIndex->GetType(&type);
    switch (type) {
        case nsIDirIndex::TYPE_SYMLINK:
            pushBuffer.Append('0');
            break;
        case nsIDirIndex::TYPE_DIRECTORY:
            pushBuffer.Append('1');
            break;
        default:
            pushBuffer.Append('2');
            break;
    }
    nsAdoptingCString escaped(nsEscapeHTML(loc));
    pushBuffer.Append(escaped);

    pushBuffer.AppendLiteral("\"><table class=\"ellipsis\"><tbody><tr><td><a class=\"");
    switch (type) {
        case nsIDirIndex::TYPE_DIRECTORY:
            pushBuffer.AppendLiteral("dir");
            break;
        case nsIDirIndex::TYPE_SYMLINK:
            pushBuffer.AppendLiteral("symlink");
            break;
        default:
            pushBuffer.AppendLiteral("file");
            break;
    }

    pushBuffer.AppendLiteral("\" href=\"");

    // need to escape links
    nsAutoCString locEscaped;

    // Adding trailing slash helps to recognize whether the URL points to a file
    // or a directory (bug #214405).
    if ((type == nsIDirIndex::TYPE_DIRECTORY) && (loc.Last() != '/')) {
        loc.Append('/');
    }

    // now minimally re-escape the location...
    uint32_t escFlags;
    // for some protocols, we expect the location to be absolute.
    // if so, and if the location indeed appears to be a valid URI, then go
    // ahead and treat it like one.
    if (mExpectAbsLoc &&
        NS_SUCCEEDED(net_ExtractURLScheme(loc, nullptr, nullptr, nullptr))) {
        // escape as absolute 
        escFlags = esc_Forced | esc_AlwaysCopy | esc_Minimal;
    }
    else {
        // escape as relative
        // esc_Directory is needed because directories have a trailing slash.
        // Without it, the trailing '/' will be escaped, and links from within
        // that directory will be incorrect
        escFlags = esc_Forced | esc_AlwaysCopy | esc_FileBaseName | esc_Colon | esc_Directory;
    }
    NS_EscapeURL(loc.get(), loc.Length(), escFlags, locEscaped);
    // esc_Directory does not escape the semicolons, so if a filename
    // contains semicolons we need to manually escape them.
    // This replacement should be removed in bug #473280
    locEscaped.ReplaceSubstring(";", "%3b");
    nsAdoptingCString htmlEscapedURL(nsEscapeHTML(locEscaped.get()));
    pushBuffer.Append(htmlEscapedURL);

    pushBuffer.AppendLiteral("\">");

    if (type == nsIDirIndex::TYPE_FILE || type == nsIDirIndex::TYPE_UNKNOWN) {
        pushBuffer.AppendLiteral("<img src=\"moz-icon://");
        int32_t lastDot = locEscaped.RFindChar('.');
        if (lastDot != kNotFound) {
            locEscaped.Cut(0, lastDot);
            nsAdoptingCString htmlFileExt(nsEscapeHTML(locEscaped.get()));
            pushBuffer.Append(htmlFileExt);
        } else {
            pushBuffer.AppendLiteral("unknown");
        }
        pushBuffer.AppendLiteral("?size=16\" alt=\"");

        nsXPIDLString altText;
        rv = mBundle->GetStringFromName(MOZ_UTF16("DirFileLabel"),
                                        getter_Copies(altText));
        if (NS_FAILED(rv)) return rv;
        AppendNonAsciiToNCR(altText, pushBuffer);
        pushBuffer.AppendLiteral("\">");
    }

    pushBuffer.Append(escaped);
    pushBuffer.AppendLiteral("</a></td></tr></tbody></table></td>\n <td");

    if (type == nsIDirIndex::TYPE_DIRECTORY || type == nsIDirIndex::TYPE_SYMLINK) {
        pushBuffer.Append('>');
    } else {
        int64_t size;
        aIndex->GetSize(&size);

        if (uint64_t(size) != UINT64_MAX) {
            pushBuffer.AppendLiteral(" sortable-data=\"");
            pushBuffer.AppendInt(size);
            pushBuffer.AppendLiteral("\">");
            nsAutoCString sizeString;
            FormatSizeString(size, sizeString);
            pushBuffer.Append(sizeString);
        } else {
            pushBuffer.Append('>');
        }
    }
    pushBuffer.AppendLiteral("</td>\n <td");

    PRTime t;
    aIndex->GetLastModified(&t);

    if (t == -1) {
        pushBuffer.AppendLiteral("></td>\n <td>");
    } else {
        pushBuffer.AppendLiteral(" sortable-data=\"");
        pushBuffer.AppendInt(static_cast<int64_t>(t));
        pushBuffer.AppendLiteral("\">");
        nsAutoString formatted;
        mDateTime->FormatPRTime(nullptr,
                                kDateFormatShort,
                                kTimeFormatNone,
                                t,
                                formatted);
        AppendNonAsciiToNCR(formatted, pushBuffer);
        pushBuffer.AppendLiteral("</td>\n <td>");
        mDateTime->FormatPRTime(nullptr,
                                kDateFormatNone,
                                kTimeFormatSeconds,
                                t,
                                formatted);
        // use NCR to show date in any doc charset
        AppendNonAsciiToNCR(formatted, pushBuffer);
    }

    pushBuffer.AppendLiteral("</td>\n</tr>");

    return SendToListener(aRequest, aCtxt, pushBuffer);
}
示例#11
0
// This method is largely cribbed from
// nsExternalResourceMap::PendingLoad::SetupViewer.
nsresult
SVGDocumentWrapper::SetupViewer(nsIRequest* aRequest,
                                nsIContentViewer** aViewer,
                                nsILoadGroup** aLoadGroup)
{
  nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
  NS_ENSURE_TRUE(chan, NS_ERROR_UNEXPECTED);

  // Check for HTTP error page
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
  if (httpChannel) {
    bool requestSucceeded;
    if (NS_FAILED(httpChannel->GetRequestSucceeded(&requestSucceeded)) ||
        !requestSucceeded) {
      return NS_ERROR_FAILURE;
    }
  }

  // Give this document its own loadgroup
  nsCOMPtr<nsILoadGroup> loadGroup;
  chan->GetLoadGroup(getter_AddRefs(loadGroup));

  nsCOMPtr<nsILoadGroup> newLoadGroup =
        do_CreateInstance(NS_LOADGROUP_CONTRACTID);
  NS_ENSURE_TRUE(newLoadGroup, NS_ERROR_OUT_OF_MEMORY);
  newLoadGroup->SetLoadGroup(loadGroup);

  nsCOMPtr<nsICategoryManager> catMan =
    do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
  NS_ENSURE_TRUE(catMan, NS_ERROR_NOT_AVAILABLE);
  nsXPIDLCString contractId;
  nsresult rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", IMAGE_SVG_XML,
                                         getter_Copies(contractId));
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIDocumentLoaderFactory> docLoaderFactory =
    do_GetService(contractId);
  NS_ENSURE_TRUE(docLoaderFactory, NS_ERROR_NOT_AVAILABLE);

  nsCOMPtr<nsIContentViewer> viewer;
  nsCOMPtr<nsIStreamListener> listener;
  rv = docLoaderFactory->CreateInstance("external-resource", chan,
                                        newLoadGroup,
                                        NS_LITERAL_CSTRING(IMAGE_SVG_XML),
                                        nullptr, nullptr,
                                        getter_AddRefs(listener),
                                        getter_AddRefs(viewer));
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED);

  nsCOMPtr<nsIParser> parser = do_QueryInterface(listener);
  NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED);

  // XML-only, because this is for SVG content
  nsIContentSink* sink = parser->GetContentSink();
  nsCOMPtr<nsIXMLContentSink> xmlSink = do_QueryInterface(sink);
  NS_ENSURE_TRUE(sink, NS_ERROR_UNEXPECTED);

  listener.swap(mListener);
  viewer.forget(aViewer);
  newLoadGroup.forget(aLoadGroup);

  RegisterForXPCOMShutdown();
  return NS_OK;
}
示例#12
0
nsresult
nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, nsISupports *aContext,
                                  nsCString& aBuffer) {
    nsresult rv;

    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
    nsCOMPtr<nsIURI> uri;
    rv = channel->GetURI(getter_AddRefs(uri));
    if (NS_FAILED(rv)) return rv;

    channel->SetContentType(NS_LITERAL_CSTRING("text/html"));

    mParser = do_CreateInstance("@mozilla.org/dirIndexParser;1",&rv);
    if (NS_FAILED(rv)) return rv;

    rv = mParser->SetListener(this);
    if (NS_FAILED(rv)) return rv;
    
    rv = mParser->OnStartRequest(request, aContext);
    if (NS_FAILED(rv)) return rv;

    nsAutoCString baseUri, titleUri;
    rv = uri->GetAsciiSpec(baseUri);
    if (NS_FAILED(rv)) return rv;
    titleUri = baseUri;

    nsCString parentStr;

    nsCString buffer;
    buffer.AppendLiteral("<!DOCTYPE html>\n<html>\n<head>\n");

    // XXX - should be using the 300: line from the parser.
    // We can't guarantee that that comes before any entry, so we'd have to
    // buffer, and do other painful stuff.
    // I'll deal with this when I make the changes to handle welcome messages
    // The .. stuff should also come from the lower level protocols, but that
    // would muck up the XUL display
    // - bbaetz

    bool isScheme = false;
    bool isSchemeFile = false;
    if (NS_SUCCEEDED(uri->SchemeIs("ftp", &isScheme)) && isScheme) {

        // strip out the password here, so it doesn't show in the page title
        // This is done by the 300: line generation in ftp, but we don't use
        // that - see above
        
        nsAutoCString pw;
        rv = uri->GetPassword(pw);
        if (NS_FAILED(rv)) return rv;
        if (!pw.IsEmpty()) {
             nsCOMPtr<nsIURI> newUri;
             rv = uri->Clone(getter_AddRefs(newUri));
             if (NS_FAILED(rv)) return rv;
             rv = newUri->SetPassword(EmptyCString());
             if (NS_FAILED(rv)) return rv;
             rv = newUri->GetAsciiSpec(titleUri);
             if (NS_FAILED(rv)) return rv;
        }

        nsAutoCString path;
        rv = uri->GetPath(path);
        if (NS_FAILED(rv)) return rv;

        if (!path.EqualsLiteral("//") && !path.LowerCaseEqualsLiteral("/%2f")) {
            rv = uri->Resolve(NS_LITERAL_CSTRING(".."),parentStr);
            if (NS_FAILED(rv)) return rv;
        }
    } else if (NS_SUCCEEDED(uri->SchemeIs("file", &isSchemeFile)) && isSchemeFile) {
        nsCOMPtr<nsIFileURL> fileUrl = do_QueryInterface(uri);
        nsCOMPtr<nsIFile> file;
        rv = fileUrl->GetFile(getter_AddRefs(file));
        if (NS_FAILED(rv)) return rv;
        file->SetFollowLinks(true);
        
        nsAutoCString url;
        rv = net_GetURLSpecFromFile(file, url);
        if (NS_FAILED(rv)) return rv;
        baseUri.Assign(url);
        
        nsCOMPtr<nsIFile> parent;
        rv = file->GetParent(getter_AddRefs(parent));
        
        if (parent && NS_SUCCEEDED(rv)) {
            net_GetURLSpecFromDir(parent, url);
            if (NS_FAILED(rv)) return rv;
            parentStr.Assign(url);
        }

        // Directory index will be always encoded in UTF-8 if this is file url
        buffer.AppendLiteral("<meta charset=\"UTF-8\">\n");

    } else if (NS_SUCCEEDED(uri->SchemeIs("jar", &isScheme)) && isScheme) {
        nsAutoCString path;
        rv = uri->GetPath(path);
        if (NS_FAILED(rv)) return rv;

        // a top-level jar directory URL is of the form jar:foo.zip!/
        // path will be of the form foo.zip!/, and its last two characters
        // will be "!/"
        //XXX this won't work correctly when the name of the directory being
        //XXX displayed ends with "!", but then again, jar: URIs don't deal
        //XXX particularly well with such directories anyway
        if (!StringEndsWith(path, NS_LITERAL_CSTRING("!/"))) {
            rv = uri->Resolve(NS_LITERAL_CSTRING(".."), parentStr);
            if (NS_FAILED(rv)) return rv;
        }
    }
    else {
        // default behavior for other protocols is to assume the channel's
        // URL references a directory ending in '/' -- fixup if necessary.
        nsAutoCString path;
        rv = uri->GetPath(path);
        if (NS_FAILED(rv)) return rv;
        if (baseUri.Last() != '/') {
            baseUri.Append('/');
            path.Append('/');
            uri->SetPath(path);
        }
        if (!path.EqualsLiteral("/")) {
            rv = uri->Resolve(NS_LITERAL_CSTRING(".."), parentStr);
            if (NS_FAILED(rv)) return rv;
        }
    }

    buffer.AppendLiteral("<style type=\"text/css\">\n"
                         ":root {\n"
                         "  font-family: sans-serif;\n"
                         "}\n"
                         "img {\n"
                         "  border: 0;\n"
                         "}\n"
                         "th {\n"
                         "  text-align: start;\n"
                         "  white-space: nowrap;\n"
                         "}\n"
                         "th > a {\n"
                         "  color: inherit;\n"
                         "}\n"
                         "table[order] > thead > tr > th {\n"
                         "  cursor: pointer;\n"
                         "}\n"
                         "table[order] > thead > tr > th::after {\n"
                         "  display: none;\n"
                         "  width: .8em;\n"
                         "  -moz-margin-end: -.8em;\n"
                         "  text-align: end;\n"
                         "}\n"
                         "table[order=\"asc\"] > thead > tr > th::after {\n"
                         "  content: \"\\2193\"; /* DOWNWARDS ARROW (U+2193) */\n"
                         "}\n"
                         "table[order=\"desc\"] > thead > tr > th::after {\n"
                         "  content: \"\\2191\"; /* UPWARDS ARROW (U+2191) */\n"
                         "}\n"
                         "table[order][order-by=\"0\"] > thead > tr > th:first-child > a ,\n"
                         "table[order][order-by=\"1\"] > thead > tr > th:first-child + th > a ,\n"
                         "table[order][order-by=\"2\"] > thead > tr > th:first-child + th + th > a {\n"
                         "  text-decoration: underline;\n"
                         "}\n"
                         "table[order][order-by=\"0\"] > thead > tr > th:first-child::after ,\n"
                         "table[order][order-by=\"1\"] > thead > tr > th:first-child + th::after ,\n"
                         "table[order][order-by=\"2\"] > thead > tr > th:first-child + th + th::after {\n"
                         "  display: inline-block;\n"
                         "}\n"
                         "table.remove-hidden > tbody > tr.hidden-object {\n"
                         "  display: none;\n"
                         "}\n"
                         "td {\n"
                         "  white-space: nowrap;\n"
                         "}\n"
                         "table.ellipsis {\n"
                         "  width: 100%;\n"
                         "  table-layout: fixed;\n"
                         "  border-spacing: 0;\n"
                         "}\n"
                         "table.ellipsis > tbody > tr > td {\n"
                         "  padding: 0;\n"
                         "  overflow: hidden;\n"
                         "  text-overflow: ellipsis;\n"
                         "}\n"
                         "/* name */\n"
                         "/* name */\n"
                         "th:first-child {\n"
                         "  -moz-padding-end: 2em;\n"
                         "}\n"
                         "/* size */\n"
                         "th:first-child + th {\n"
                         "  -moz-padding-end: 1em;\n"
                         "}\n"
                         "td:first-child + td {\n"
                         "  text-align: end;\n"
                         "  -moz-padding-end: 1em;\n"
                         "}\n"
                         "/* date */\n"
                         "td:first-child + td + td {\n"
                         "  -moz-padding-start: 1em;\n"
                         "  -moz-padding-end: .5em;\n"
                         "}\n"
                         "/* time */\n"
                         "td:first-child + td + td + td {\n"
                         "  -moz-padding-start: .5em;\n"
                         "}\n"
                         ".symlink {\n"
                         "  font-style: italic;\n"
                         "}\n"
                         ".dir ,\n"
                         ".symlink ,\n"
                         ".file {\n"
                         "  -moz-margin-start: 20px;\n"
                         "}\n"
                         ".dir::before ,\n"
                         ".file > img {\n"
                         "  -moz-margin-end: 4px;\n"
                         "  -moz-margin-start: -20px;\n"
                         "  max-width: 16px;\n"
                         "  max-height: 16px;\n"
                         "  vertical-align: middle;\n"
                         "}\n"
                         ".dir::before {\n"
                         "  content: url(resource://gre/res/html/folder.png);\n"
                         "}\n"
                         "</style>\n"
                         "<link rel=\"stylesheet\" media=\"screen, projection\" type=\"text/css\""
                         " href=\"chrome://global/skin/dirListing/dirListing.css\">\n"
                         "<script type=\"application/javascript\">\n"
                         "var gTable, gOrderBy, gTBody, gRows, gUI_showHidden;\n"
                         "document.addEventListener(\"DOMContentLoaded\", function() {\n"
                         "  gTable = document.getElementsByTagName(\"table\")[0];\n"
                         "  gTBody = gTable.tBodies[0];\n"
                         "  if (gTBody.rows.length < 2)\n"
                         "    return;\n"
                         "  gUI_showHidden = document.getElementById(\"UI_showHidden\");\n"
                         "  var headCells = gTable.tHead.rows[0].cells,\n"
                         "      hiddenObjects = false;\n"
                         "  function rowAction(i) {\n"
                         "    return function(event) {\n"
                         "      event.preventDefault();\n"
                         "      orderBy(i);\n"
                         "    }\n"
                         "  }\n"
                         "  for (var i = headCells.length - 1; i >= 0; i--) {\n"
                         "    var anchor = document.createElement(\"a\");\n"
                         "    anchor.href = \"\";\n"
                         "    anchor.appendChild(headCells[i].firstChild);\n"
                         "    headCells[i].appendChild(anchor);\n"
                         "    headCells[i].addEventListener(\"click\", rowAction(i), true);\n"
                         "  }\n"
                         "  if (gUI_showHidden) {\n"
                         "    gRows = Array.slice(gTBody.rows);\n"
                         "    hiddenObjects = gRows.some(function (row) row.className == \"hidden-object\");\n"
                         "  }\n"
                         "  gTable.setAttribute(\"order\", \"\");\n"
                         "  if (hiddenObjects) {\n"
                         "    gUI_showHidden.style.display = \"block\";\n"
                         "    updateHidden();\n"
                         "  }\n"
                         "}, \"false\");\n"
                         "function compareRows(rowA, rowB) {\n"
                         "  var a = rowA.cells[gOrderBy].getAttribute(\"sortable-data\") || \"\";\n"
                         "  var b = rowB.cells[gOrderBy].getAttribute(\"sortable-data\") || \"\";\n"
                         "  var intA = +a;\n"
                         "  var intB = +b;\n"
                         "  if (a == intA && b == intB) {\n"
                         "    a = intA;\n"
                         "    b = intB;\n"
                         "  } else {\n"
                         "    a = a.toLowerCase();\n"
                         "    b = b.toLowerCase();\n"
                         "  }\n"
                         "  if (a < b)\n"
                         "    return -1;\n"
                         "  if (a > b)\n"
                         "    return 1;\n"
                         "  return 0;\n"
                         "}\n"
                         "function orderBy(column) {\n"
                         "  if (!gRows)\n"
                         "    gRows = Array.slice(gTBody.rows);\n"
                         "  var order;\n"
                         "  if (gOrderBy == column) {\n"
                         "    order = gTable.getAttribute(\"order\") == \"asc\" ? \"desc\" : \"asc\";\n"
                         "  } else {\n"
                         "    order = \"asc\";\n"
                         "    gOrderBy = column;\n"
                         "    gTable.setAttribute(\"order-by\", column);\n"
                         "    gRows.sort(compareRows);\n"
                         "  }\n"
                         "  gTable.removeChild(gTBody);\n"
                         "  gTable.setAttribute(\"order\", order);\n"
                         "  if (order == \"asc\")\n"
                         "    for (var i = 0; i < gRows.length; i++)\n"
                         "      gTBody.appendChild(gRows[i]);\n"
                         "  else\n"
                         "    for (var i = gRows.length - 1; i >= 0; i--)\n"
                         "      gTBody.appendChild(gRows[i]);\n"
                         "  gTable.appendChild(gTBody);\n"
                         "}\n"
                         "function updateHidden() {\n"
                         "  gTable.className = gUI_showHidden.getElementsByTagName(\"input\")[0].checked ?\n"
                         "                     \"\" :\n"
                         "                     \"remove-hidden\";\n"
                         "}\n"
                         "</script>\n");

    buffer.AppendLiteral("<link rel=\"icon\" type=\"image/png\" href=\"");
    nsCOMPtr<nsIURI> innerUri = NS_GetInnermostURI(uri);
    if (!innerUri)
        return NS_ERROR_UNEXPECTED;
    nsCOMPtr<nsIFileURL> fileURL(do_QueryInterface(innerUri));
    //XXX bug 388553: can't use skinnable icons here due to security restrictions
    if (fileURL) {
        //buffer.AppendLiteral("chrome://global/skin/dirListing/local.png");
        buffer.AppendLiteral("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB"
                             "AAAAAQCAYAAAAf8%2F9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
                             "ZSBJbWFnZVJlYWR5ccllPAAAAjFJREFUeNqsU8uOElEQPffR"
                             "3XQ3ONASdBJCSBxHos5%2B3Bg3rvkCv8PElS78gPkO%2FATj"
                             "QoUdO2ftrJiRh6aneTb9sOpC4weMN6lcuFV16pxDIfI8x12O"
                             "YIDhcPiu2Wx%2B%2FHF5CW1Z6Jyegt%2FTNEWSJIjjGFEUIQ"
                             "xDrFYrWFSzXC4%2FdLvd95pRKpXKy%2BpRFZ7nwaWo1%2BsG"
                             "nQG2260BKJfLKJVKGI1GEEJw7ateryd0v993W63WEwjgxfn5"
                             "obGYzgCbzcaEbdsIggDj8Riu6z6iUk9SYZMSx8W0LMsM%2FS"
                             "KK75xnJlIq80anQXdbEp0OhcPJ0eiaJnGRMEyyPDsAKKUM9c"
                             "lkYoDo3SZJzzSdp0VSKYmfV1co%2Bz580kw5KDIM8RbRfEnU"
                             "f1HzxtQyMAGcaGruTKczMzEIaqhKifV6jd%2BzGQQB5llunF"
                             "%2FM52BizC2K5sYPYvZcu653tjOM9O93wnYc08gmkgg4VAxi"
                             "xfqFUJT36AYBZGd6PJkFCZnnlBxMp38gqIgLpZB0y4Nph18l"
                             "yWh5FFbrOSxbl3V4G%2BVB7T4ajYYxTyuLtO%2BCvWGgJE1M"
                             "c7JNsJEhvgw%2FQV4fo%2F24nbEsX2u1d5sVyn8sJO0ZAQiI"
                             "YnFh%2BxrfLz%2Fj29cBS%2FO14zg3i8XigW3ZkErDtmKoeM"
                             "%2BAJGRMnXeEPGKf0nCD1ydvkDzU9Jbc6OpR7WIw6L8lQ%2B"
                             "4pQ1%2FlPF0RGM9Ns91Wmptk0GfB4EJkt77vXYj%2F8m%2B8"
                             "y%2FkrwABHbz2H9V68DQAAAABJRU5ErkJggg%3D%3D");
    } else {
        //buffer.AppendLiteral("chrome://global/skin/dirListing/remote.png");
        buffer.AppendLiteral("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB"
                             "AAAAAQCAYAAAAf8%2F9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
                             "ZSBJbWFnZVJlYWR5ccllPAAAAeBJREFUeNqcU81O20AQ%2Ft"
                             "Z2AgQSYQRqL1UPVG2hAUQkxLEStz4DrXpLpD5Drz31Cajax%"
                             "2Bghhx6qHIJURBTxIwQRwopCBbZjHMcOTrzermPipsSt1Iw0"
                             "3p3ZmW%2B%2B2R0TxhgOD34wjCHZlQ0iDYz9yvEfhxMTCYhE"
                             "QDIZhkxKd2sqzX2TOD2vBQCQhpPefng1ZP2dVPlLLdpL8SEM"
                             "cxng%2Fbs0RIHhtgs4twxOh%2BHjZxvzDx%2F3GQQiDFISiR"
                             "BLFMPKTRMollzcWECrDVhtxtdRVsL9youPxGj%2FbdfFlUZh"
                             "tDyYbYqWRUdai1oQRZ5oHeHl2gNM%2B01Uqio8RlH%2Bnsaz"
                             "JzNwXcq1B%2BiXPHprlEEymeBfXs1w8XxxihfyuXqoHqpoGj"
                             "ZM04bddgG%2F9%2B8WGj87qDdsrK9m%2BoA%2BpbhQTDh2l1"
                             "%2Bi2weNbSHMZyjvNXmVbqh9Fj5Oz27uEoP%2BSTxANruJs9"
                             "L%2FT6P0ewqPx5nmiAG5f6AoCtN1PbJzuRyJAyDBzzSQYvEr"
                             "f06yYxhGXlEa8H2KVGoasjwLx3Ewk858opQWXm%2B%2Fib9E"
                             "QrBzclLLLy89xYvlpchvtixcX6uo1y%2FzsiwHrkIsgKbp%2"
                             "BYWFOWicuqppoNTnStHzPFCPQhBEBOyGAX4JMADFetubi4BS"
                             "YAAAAABJRU5ErkJggg%3D%3D");
    }
    buffer.AppendLiteral("\">\n<title>");

    // Everything needs to end in a /,
    // otherwise we end up linking to file:///foo/dirfile

    if (!mTextToSubURI) {
        mTextToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
        if (NS_FAILED(rv)) return rv;
    }

    nsXPIDLCString encoding;
    rv = uri->GetOriginCharset(encoding);
    if (NS_FAILED(rv)) return rv;
    if (encoding.IsEmpty()) {
      encoding.AssignLiteral("UTF-8");
    }

    nsXPIDLString unEscapeSpec;
    rv = mTextToSubURI->UnEscapeAndConvert(encoding, titleUri.get(),
                                           getter_Copies(unEscapeSpec));
    // unescape may fail because
    // 1. file URL may be encoded in platform charset for backward compatibility
    // 2. query part may not be encoded in UTF-8 (see bug 261929)
    // so try the platform's default if this is file url
    if (NS_FAILED(rv) && isSchemeFile) {
        nsCOMPtr<nsIPlatformCharset> platformCharset(do_GetService(NS_PLATFORMCHARSET_CONTRACTID, &rv));
        NS_ENSURE_SUCCESS(rv, rv);
        nsAutoCString charset;
        rv = platformCharset->GetCharset(kPlatformCharsetSel_FileName, charset);
        NS_ENSURE_SUCCESS(rv, rv);

        rv = mTextToSubURI->UnEscapeAndConvert(charset.get(), titleUri.get(),
                                               getter_Copies(unEscapeSpec));
    }
    if (NS_FAILED(rv)) return rv;

    nsXPIDLString htmlEscSpec;
    htmlEscSpec.Adopt(nsEscapeHTML2(unEscapeSpec.get(),
                                    unEscapeSpec.Length()));

    nsXPIDLString title;
    const char16_t* formatTitle[] = {
        htmlEscSpec.get()
    };

    rv = mBundle->FormatStringFromName(MOZ_UTF16("DirTitle"),
                                       formatTitle,
                                       sizeof(formatTitle)/sizeof(char16_t*),
                                       getter_Copies(title));
    if (NS_FAILED(rv)) return rv;

    // we want to convert string bundle to NCR
    // to ensure they're shown in any charsets
    AppendNonAsciiToNCR(title, buffer);

    buffer.AppendLiteral("</title>\n");    

    // If there is a quote character in the baseUri, then
    // lets not add a base URL.  The reason for this is that
    // if we stick baseUri containing a quote into a quoted
    // string, the quote character will prematurely close
    // the base href string.  This is a fall-back check;
    // that's why it is OK to not use a base rather than
    // trying to play nice and escaping the quotes.  See bug
    // 358128.

    if (baseUri.FindChar('"') == kNotFound)
    {
        // Great, the baseUri does not contain a char that
        // will prematurely close the string.  Go ahead an
        // add a base href.
        buffer.AppendLiteral("<base href=\"");
        nsAdoptingCString htmlEscapedUri(nsEscapeHTML(baseUri.get()));
        buffer.Append(htmlEscapedUri);
        buffer.AppendLiteral("\" />\n");
    }
    else
    {
        NS_ERROR("broken protocol handler didn't escape double-quote.");
    }

    nsCString direction(NS_LITERAL_CSTRING("ltr"));
    nsCOMPtr<nsIXULChromeRegistry> reg =
      mozilla::services::GetXULChromeRegistryService();
    if (reg) {
      bool isRTL = false;
      reg->IsLocaleRTL(NS_LITERAL_CSTRING("global"), &isRTL);
      if (isRTL) {
        direction.AssignLiteral("rtl");
      }
    }

    buffer.AppendLiteral("</head>\n<body dir=\"");
    buffer.Append(direction);
    buffer.AppendLiteral("\">\n<h1>");
    
    const char16_t* formatHeading[] = {
        htmlEscSpec.get()
    };

    rv = mBundle->FormatStringFromName(MOZ_UTF16("DirTitle"),
                                       formatHeading,
                                       sizeof(formatHeading)/sizeof(char16_t*),
                                       getter_Copies(title));
    if (NS_FAILED(rv)) return rv;
    
    AppendNonAsciiToNCR(title, buffer);
    buffer.AppendLiteral("</h1>\n");

    if (!parentStr.IsEmpty()) {
        nsXPIDLString parentText;
        rv = mBundle->GetStringFromName(MOZ_UTF16("DirGoUp"),
                                        getter_Copies(parentText));
        if (NS_FAILED(rv)) return rv;

        buffer.AppendLiteral("<p id=\"UI_goUp\"><a class=\"up\" href=\"");

        nsAdoptingCString htmlParentStr(nsEscapeHTML(parentStr.get()));
        buffer.Append(htmlParentStr);
        buffer.AppendLiteral("\">");
        AppendNonAsciiToNCR(parentText, buffer);
        buffer.AppendLiteral("</a></p>\n");
    }

    if (isSchemeFile) {
        nsXPIDLString showHiddenText;
        rv = mBundle->GetStringFromName(MOZ_UTF16("ShowHidden"),
                                        getter_Copies(showHiddenText));
        if (NS_FAILED(rv)) return rv;

        buffer.AppendLiteral("<p id=\"UI_showHidden\" style=\"display:none\"><label><input type=\"checkbox\" checked onchange=\"updateHidden()\">");
        AppendNonAsciiToNCR(showHiddenText, buffer);
        buffer.AppendLiteral("</label></p>\n");
    }

    buffer.AppendLiteral("<table>\n");

    nsXPIDLString columnText;

    buffer.AppendLiteral(" <thead>\n"
                         "  <tr>\n"
                         "   <th>");

    rv = mBundle->GetStringFromName(MOZ_UTF16("DirColName"),
                                    getter_Copies(columnText));
    if (NS_FAILED(rv)) return rv;
    AppendNonAsciiToNCR(columnText, buffer);
    buffer.AppendLiteral("</th>\n"
                         "   <th>");

    rv = mBundle->GetStringFromName(MOZ_UTF16("DirColSize"),
                                    getter_Copies(columnText));
    if (NS_FAILED(rv)) return rv;
    AppendNonAsciiToNCR(columnText, buffer);
    buffer.AppendLiteral("</th>\n"
                         "   <th colspan=\"2\">");

    rv = mBundle->GetStringFromName(MOZ_UTF16("DirColMTime"),
                                    getter_Copies(columnText));
    if (NS_FAILED(rv)) return rv;
    AppendNonAsciiToNCR(columnText, buffer);
    buffer.AppendLiteral("</th>\n"
                         "  </tr>\n"
                         " </thead>\n");
    buffer.AppendLiteral(" <tbody>\n");

    aBuffer = buffer;
    return rv;
}
示例#13
0
NS_METHOD OutlookRegister(nsIComponentManager *aCompMgr,
                          nsIFile *aPath, const char *registryLocation,
                          const char *componentType,
                          const nsModuleComponentInfo *info)
{
  nsresult rv;

  nsCOMPtr<nsICategoryManager> catMan = do_GetService( NS_CATEGORYMANAGER_CONTRACTID, &rv);
  if (NS_SUCCEEDED( rv)) {
    nsCString replace;
    char *theCID = kOutlookImportCID.ToString();
    rv = catMan->AddCategoryEntry( "mailnewsimport", theCID, kOutlookSupportsString, PR_TRUE, PR_TRUE, getter_Copies( replace));
    NS_Free( theCID);
  }

  return( rv);
}
NS_IMETHODIMP
nsFormSigningDialog::ConfirmSignText(nsIInterfaceRequestor *aContext, 
                                     const nsAString &aHost,
                                     const nsAString &aSignText,
                                     const PRUnichar **aCertNickList,
                                     const PRUnichar **aCertDetailsList,
                                     PRUint32 aCount, PRInt32 *aSelectedIndex,
                                     nsAString &aPassword, PRBool *aCanceled) 
{
  *aCanceled = PR_TRUE;

  // Get the parent window for the dialog
  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(aContext);

  nsresult rv;
  nsCOMPtr<nsIDialogParamBlock> block =
    do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  block->SetNumberStrings(3 + aCount * 2);

  rv = block->SetString(0, PromiseFlatString(aHost).get());
  NS_ENSURE_SUCCESS(rv, rv);

  rv = block->SetString(1, PromiseFlatString(aSignText).get());
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 i;
  for (i = 0; i < aCount; ++i) {
    rv = block->SetString(2 + 2 * i, aCertNickList[i]);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = block->SetString(2 + (2 * i + 1), aCertDetailsList[i]);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  rv = block->SetInt(0, aCount);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = nsNSSDialogHelper::openDialog(parent,
                                     "chrome://pippki/content/formsigning.xul",
                                     block);
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt32 status;
  rv = block->GetInt(0, &status);
  NS_ENSURE_SUCCESS(rv, rv);

  if (status == 0) {
    *aCanceled = PR_TRUE;
  }
  else {
    *aCanceled = PR_FALSE;

    rv = block->GetInt(1, aSelectedIndex);
    NS_ENSURE_SUCCESS(rv, rv);

    nsXPIDLString pw;
    rv = block->GetString(0, getter_Copies(pw));
    NS_ENSURE_SUCCESS(rv, rv);

    aPassword = pw;
  }

  return NS_OK;
}
nsresult
nsLocalMoveCopyMsgTxn::UndoTransactionInternal()
{
    nsresult rv = NS_ERROR_FAILURE;

    if (mUndoFolderListener)
    {
        nsCOMPtr<nsIMsgMailSession> mailSession =
            do_GetService(NS_MSGMAILSESSION_CONTRACTID, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        rv = mailSession->RemoveFolderListener(mUndoFolderListener);
        NS_ENSURE_SUCCESS(rv,rv);

        NS_RELEASE(mUndoFolderListener);
        mUndoFolderListener = nullptr;
    }

    nsCOMPtr<nsIMsgDatabase> srcDB;
    nsCOMPtr<nsIMsgDatabase> dstDB;
    nsCOMPtr<nsIMsgFolder> srcFolder = do_QueryReferent(m_srcFolder, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCOMPtr<nsIMsgFolder> dstFolder = do_QueryReferent(m_dstFolder, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = srcFolder->GetMsgDatabase(getter_AddRefs(srcDB));
    if(NS_FAILED(rv)) return rv;

    rv = dstFolder->GetMsgDatabase(getter_AddRefs(dstDB));
    if (NS_FAILED(rv)) return rv;

    uint32_t count = m_srcKeyArray.Length();
    uint32_t i;
    nsCOMPtr<nsIMsgDBHdr> oldHdr;
    nsCOMPtr<nsIMsgDBHdr> newHdr;

    // protect against a bogus undo txn without any source keys
    // see bug #179856 for details
    NS_ASSERTION(count, "no source keys");
    if (!count)
        return NS_ERROR_UNEXPECTED;

    if (m_isMove)
    {
        if (m_srcIsImap4)
        {
            bool deleteFlag = true;  //message has been deleted -we are trying to undo it
            CheckForToggleDelete(srcFolder, m_srcKeyArray[0], &deleteFlag); //there could have been a toggle.
            rv = UndoImapDeleteFlag(srcFolder, m_srcKeyArray, deleteFlag);
        }
        else if (m_canUndelete)
        {
            nsCOMPtr<nsIMutableArray> srcMessages =
                do_CreateInstance(NS_ARRAY_CONTRACTID);
            nsCOMPtr<nsIMutableArray> dstMessages =
                do_CreateInstance(NS_ARRAY_CONTRACTID);

            srcDB->StartBatch();
            for (i = 0; i < count; i++)
            {
                rv = dstDB->GetMsgHdrForKey(m_dstKeyArray[i],
                                            getter_AddRefs(oldHdr));
                NS_ASSERTION(oldHdr, "fatal ... cannot get old msg header\n");
                if (NS_SUCCEEDED(rv) && oldHdr)
                {
                    rv = srcDB->CopyHdrFromExistingHdr(m_srcKeyArray[i],
                                                       oldHdr, true,
                                                       getter_AddRefs(newHdr));
                    NS_ASSERTION(newHdr,
                                 "fatal ... cannot create new msg header\n");
                    if (NS_SUCCEEDED(rv) && newHdr)
                    {
                        newHdr->SetStatusOffset(m_srcStatusOffsetArray[i]);
                        srcDB->UndoDelete(newHdr);
                        srcMessages->AppendElement(newHdr, false);
                        // (we want to keep these two lists in sync)
                        dstMessages->AppendElement(oldHdr, false);
                    }
                }
            }
            srcDB->EndBatch();

            nsCOMPtr<nsIMsgFolderNotificationService>
            notifier(do_GetService(NS_MSGNOTIFICATIONSERVICE_CONTRACTID));
            if (notifier)
            {
                // Remember that we're actually moving things back from the destination
                //  to the source!
                notifier->NotifyMsgsMoveCopyCompleted(true, dstMessages,
                                                      srcFolder, srcMessages);
            }

            nsCOMPtr <nsIMsgLocalMailFolder> localFolder = do_QueryInterface(srcFolder);
            if (localFolder)
                localFolder->MarkMsgsOnPop3Server(srcMessages, POP3_NONE /*deleteMsgs*/);
        }
        else // undoing a move means moving the messages back.
        {
            nsCOMPtr<nsIMutableArray> dstMessages =
                do_CreateInstance(NS_ARRAY_CONTRACTID);
            nsCOMPtr<nsIMsgDBHdr> dstHdr;
            m_numHdrsCopied = 0;
            m_srcKeyArray.Clear();
            for (i = 0; i < count; i++)
            {
                dstDB->GetMsgHdrForKey(m_dstKeyArray[i], getter_AddRefs(dstHdr));
                NS_ASSERTION(dstHdr, "fatal ... cannot get old msg header\n");
                if (dstHdr)
                {
                    nsCString messageId;
                    dstHdr->GetMessageId(getter_Copies(messageId));
                    dstMessages->AppendElement(dstHdr, false);
                    m_copiedMsgIds.AppendElement(messageId);
                }
            }
            srcFolder->AddFolderListener(this);
            m_undoing = true;
            return srcFolder->CopyMessages(dstFolder, dstMessages,
                                           true, nullptr, nullptr, false,
                                           false);
        }
        srcDB->SetSummaryValid(true);
    }

    dstDB->DeleteMessages(m_dstKeyArray.Length(), m_dstKeyArray.Elements(), nullptr);
    dstDB->SetSummaryValid(true);

    return rv;
}
/* nsISimpleEnumerator GetTargets (in nsIRDFResource aSource, in nsIRDFResource aProperty, in boolean aTruthValue); */
NS_IMETHODIMP
nsRDFDataSourceDataSource::GetTargets(nsIRDFResource *aSource,
                                      nsIRDFResource *aProperty,
                                      PRBool aTruthValue,
                                      nsISimpleEnumerator **_retval)
{
  nsXPIDLCString sourceval;
  aSource->GetValue(getter_Copies(sourceval));
  nsXPIDLCString propval;
  aProperty->GetValue(getter_Copies(propval));
#ifdef DEBUG_alecf
  printf("GetTargets(%s, %s,..)\n", (const char*)sourceval,
         (const char*)propval);
#endif
  
  nsresult rv;
  PRBool isProp;
  nsCOMPtr<nsISupportsArray> arcs;
  nsISimpleEnumerator *enumerator;
  
  if (NS_SUCCEEDED(aProperty->EqualsNode(kNC_Child, &isProp)) &&
      isProp) {

    // here we need to determine if we need to extract out the source
    // or use aSource?
    if (StringBeginsWith(sourceval, NS_LITERAL_CSTRING("dsresource:"))) {
      // somehow get the source
      // XXX ? rv = mDataSource->ArcLabelsOut(realsource, &enumerator);      
      rv = mDataSource->ArcLabelsOut(aSource, &enumerator);      
    } else {
      rv = mDataSource->ArcLabelsOut(aSource, &enumerator);
    }
    // enumerate all the children and create the composite resources
    PRBool hasMoreArcs=PR_FALSE;

    rv = enumerator->HasMoreElements(&hasMoreArcs);
    while (NS_SUCCEEDED(rv) && hasMoreArcs) {
      
      // get the next arc
      nsCOMPtr<nsISupports> arcSupports;
      rv = enumerator->GetNext(getter_AddRefs(arcSupports));
      nsCOMPtr<nsIRDFResource> arc = do_QueryInterface(arcSupports, &rv);

      // get all the resources on the ends of the arc arcs
      nsCOMPtr<nsISimpleEnumerator> targetEnumerator;
      rv = mDataSource->GetTargets(aSource, arc, PR_TRUE,
                                   getter_AddRefs(targetEnumerator));

      PRBool hasMoreTargets;
      rv = targetEnumerator->HasMoreElements(&hasMoreTargets);
      while (NS_SUCCEEDED(rv) && hasMoreTargets) {
        // get the next target
        nsCOMPtr<nsISupports> targetSupports;
        rv = enumerator->GetNext(getter_AddRefs(targetSupports));
        nsCOMPtr<nsIRDFResource> target=do_QueryInterface(targetSupports, &rv);

        // now we have an (arc, target) tuple that will be our node
        // arc will become #Name
        // target will become #Value
#ifdef DEBUG_alecf
        nsXPIDLString arcValue;
        nsXPIDLString targetValue;

        arc->GetValue(getter_Copies(arcValue));
        target->GetValue(getter_Copies(targetValue));
        printf("#child of %s:\n\t%s = %s\n",
               (const char*)sourceval
#endif

      }
      
      rv = enumerator->HasMoreElements(&hasMoreArcs);
    }
    
  } else if (NS_SUCCEEDED(aProperty->EqualsNode(kNC_Name, &isProp)) &&
NS_IMETHODIMP
nsLocalMoveCopyMsgTxn::RedoTransaction()
{
    nsresult rv;
    nsCOMPtr<nsIMsgDatabase> srcDB;
    nsCOMPtr<nsIMsgDatabase> dstDB;

    nsCOMPtr<nsIMsgFolder> srcFolder = do_QueryReferent(m_srcFolder, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCOMPtr<nsIMsgFolder> dstFolder = do_QueryReferent(m_dstFolder, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = srcFolder->GetMsgDatabase(getter_AddRefs(srcDB));
    if(NS_FAILED(rv)) return rv;
    rv = dstFolder->GetMsgDatabase(getter_AddRefs(dstDB));
    if (NS_FAILED(rv)) return rv;

    uint32_t count = m_srcKeyArray.Length();
    uint32_t i;
    nsCOMPtr<nsIMsgDBHdr> oldHdr;
    nsCOMPtr<nsIMsgDBHdr> newHdr;

    nsCOMPtr<nsIMutableArray> srcMessages = do_CreateInstance(NS_ARRAY_CONTRACTID);
    nsCOMPtr <nsISupports> msgSupports;

    for (i=0; i<count; i++)
    {
        rv = srcDB->GetMsgHdrForKey(m_srcKeyArray[i],
                                    getter_AddRefs(oldHdr));
        NS_ASSERTION(oldHdr, "fatal ... cannot get old msg header\n");

        if (NS_SUCCEEDED(rv) && oldHdr)
        {
            msgSupports =do_QueryInterface(oldHdr);
            srcMessages->AppendElement(msgSupports, false);

            if (m_canUndelete)
            {
                rv = dstDB->CopyHdrFromExistingHdr(m_dstKeyArray[i],
                                                   oldHdr, true,
                                                   getter_AddRefs(newHdr));
                NS_ASSERTION(newHdr, "fatal ... cannot get new msg header\n");
                if (NS_SUCCEEDED(rv) && newHdr)
                {
                    if (i < m_dstSizeArray.Length())
                        rv = newHdr->SetMessageSize(m_dstSizeArray[i]);
                    dstDB->UndoDelete(newHdr);
                }
            }
        }
    }
    dstDB->SetSummaryValid(true);

    if (m_isMove)
    {
        if (m_srcIsImap4)
        {
            // protect against a bogus undo txn without any source keys
            // see bug #179856 for details
            NS_ASSERTION(!m_srcKeyArray.IsEmpty(), "no source keys");
            if (m_srcKeyArray.IsEmpty())
                return NS_ERROR_UNEXPECTED;

            bool deleteFlag = false; //message is un-deleted- we are trying to redo
            CheckForToggleDelete(srcFolder, m_srcKeyArray[0], &deleteFlag); // there could have been a toggle
            rv = UndoImapDeleteFlag(srcFolder, m_srcKeyArray, deleteFlag);
        }
        else if (m_canUndelete)
        {
            nsCOMPtr <nsIMsgLocalMailFolder> localFolder = do_QueryInterface(srcFolder);
            if (localFolder)
                localFolder->MarkMsgsOnPop3Server(srcMessages, POP3_DELETE /*deleteMsgs*/);

            rv = srcDB->DeleteMessages(m_srcKeyArray.Length(), m_srcKeyArray.Elements(), nullptr);
            srcDB->SetSummaryValid(true);
        }
        else
        {
            nsCOMPtr<nsIMsgDBHdr> srcHdr;
            m_numHdrsCopied = 0;
            m_dstKeyArray.Clear();
            for (i = 0; i < count; i++)
            {
                srcDB->GetMsgHdrForKey(m_srcKeyArray[i], getter_AddRefs(srcHdr));
                NS_ASSERTION(srcHdr, "fatal ... cannot get old msg header\n");
                if (srcHdr)
                {
                    nsCString messageId;
                    srcHdr->GetMessageId(getter_Copies(messageId));
                    m_copiedMsgIds.AppendElement(messageId);
                }
            }
            dstFolder->AddFolderListener(this);
            m_undoing = false;
            return dstFolder->CopyMessages(srcFolder, srcMessages, true, nullptr,
                                           nullptr, false, false);
        }
    }

    return rv;
}
NS_IMETHODIMP
nsDownload::OnStateChange(nsIWebProgress* aWebProgress,
                          nsIRequest* aRequest, PRUint32 aStateFlags,
                          nsresult aStatus)
{
    // Record the start time only if it hasn't been set.
    if (LL_IS_ZERO(mStartTime) && (aStateFlags & STATE_START))
        SetStartTime(PR_Now());

    // When we break the ref cycle with mPersist, we don't want to lose
    // access to out member vars!
    nsRefPtr<nsDownload> kungFuDeathGrip(this);

    // We need to update mDownloadState before updating the dialog, because
    // that will close and call CancelDownload if it was the last open window.
    nsresult rv = NS_OK;
    if (aStateFlags & STATE_STOP) {
        if (mDownloadState == DOWNLOADING || mDownloadState == NOTSTARTED) {
            mDownloadState = FINISHED;

            // Set file size at the end of a transfer (for unknown transfer amounts)
            if (mMaxBytes == -1)
                mMaxBytes = mCurrBytes;

            // Files less than 1Kb shouldn't show up as 0Kb.
            if (mMaxBytes < 1024) {
                mCurrBytes = 1024;
                mMaxBytes  = 1024;
            }

            mPercentComplete = 100;

            // Play a sound or show an alert when the download finishes
            PRBool playSound = PR_FALSE;
            PRBool showAlert = PR_FALSE;
            nsXPIDLCString soundStr;

            nsCOMPtr<nsIPrefService> prefs = do_GetService("@mozilla.org/preferences-service;1");

            if (prefs) {
                nsCOMPtr<nsIPrefBranch> prefBranch;
                prefs->GetBranch(nsnull, getter_AddRefs(prefBranch));
                if (prefBranch) {
                    rv = prefBranch->GetBoolPref("browser.download.finished_download_sound", &playSound);
                    if (NS_SUCCEEDED(rv) && playSound)
                        prefBranch->GetCharPref("browser.download.finished_sound_url", getter_Copies(soundStr));
                    rv = prefBranch->GetBoolPref("browser.download.finished_download_alert", &showAlert);
                    if (NS_FAILED(rv))
                        showAlert = PR_FALSE;
                }
            }

            if (!soundStr.IsEmpty()) {
                if (!mDownloadManager->mSoundInterface) {
                    mDownloadManager->mSoundInterface = do_CreateInstance("@mozilla.org/sound;1");
                }
                if (mDownloadManager->mSoundInterface) {
                    nsCOMPtr<nsIURI> soundURI;

                    NS_NewURI(getter_AddRefs(soundURI), soundStr);
                    nsCOMPtr<nsIURL> soundURL(do_QueryInterface(soundURI));
                    if (soundURL)
                        mDownloadManager->mSoundInterface->Play(soundURL);
                    else
                        mDownloadManager->mSoundInterface->Beep();
                }
            }
            if (showAlert)
                DisplayDownloadFinishedAlert();

            nsCAutoString path;
            rv = GetFilePathUTF8(mTarget, path);
            // can't do an early return; have to break reference cycle below
            if (NS_SUCCEEDED(rv)) {
                mDownloadManager->DownloadEnded(path, nsnull);
            }
        }

        // break the cycle we created in AddDownload
        mCancelable = nsnull;
        // and the one with the progress dialog
        if (mDialog) {
            mDialog->SetObserver(nsnull);
            mDialog = nsnull;
        }
    }

    if (mDownloadManager->MustUpdateUI()) {
        nsCOMPtr<nsIDownloadProgressListener> internalListener;
        mDownloadManager->GetInternalListener(getter_AddRefs(internalListener));
        if (internalListener)
            internalListener->OnStateChange(aWebProgress, aRequest, aStateFlags, aStatus, this);
    }

    if (mDialogListener) {
        mDialogListener->OnStateChange(aWebProgress, aRequest, aStateFlags, aStatus, this);
        if (aStateFlags & STATE_STOP) {
            // Break this cycle, too
            mDialogListener = nsnull;
        }
    }

    return rv;
}
NS_IMETHODIMP
nsGNOMEShellService::SetDesktopBackground(nsIDOMElement* aElement, 
                                          PRInt32 aPosition)
{
  nsresult rv;
  nsCOMPtr<nsIImageLoadingContent> imageContent = do_QueryInterface(aElement, &rv);
  if (!imageContent) return rv;

  // get the image container
  nsCOMPtr<imgIRequest> request;
  rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                                getter_AddRefs(request));
  if (!request) return rv;
  nsCOMPtr<imgIContainer> container;
  rv = request->GetImage(getter_AddRefs(container));
  if (!container) return rv;

  // Write the background file to the home directory.
  nsCAutoString filePath(PR_GetEnv("HOME"));

  // get the product brand name from localized strings
  nsString brandName;
  nsCID bundleCID = NS_STRINGBUNDLESERVICE_CID;
  nsCOMPtr<nsIStringBundleService> bundleService(do_GetService(bundleCID));
  if (bundleService) {
    nsCOMPtr<nsIStringBundle> brandBundle;
    rv = bundleService->CreateBundle(BRAND_PROPERTIES,
                                     getter_AddRefs(brandBundle));
    if (NS_SUCCEEDED(rv) && brandBundle) {
      rv = brandBundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(),
                                          getter_Copies(brandName));
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  // build the file name
  filePath.Append('/');
  filePath.Append(NS_ConvertUTF16toUTF8(brandName));
  filePath.Append("_wallpaper.png");

  // write the image to a file in the home dir
  rv = WriteImage(filePath, container);

  // if the file was written successfully, set it as the system wallpaper
  nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);

  nsCAutoString options;
  if (aPosition == BACKGROUND_TILE)
    options.Assign("wallpaper");
  else if (aPosition == BACKGROUND_STRETCH)
    options.Assign("stretched");
  else
    options.Assign("centered");

  gconf->SetString(NS_LITERAL_CSTRING(kDesktopOptionsKey), options);

  // Set the image to an empty string first to force a refresh
  // (since we could be writing a new image on top of an existing
  // Firefox_wallpaper.png and nautilus doesn't monitor the file for changes)
  gconf->SetString(NS_LITERAL_CSTRING(kDesktopImageKey),
                   EmptyCString());

  gconf->SetString(NS_LITERAL_CSTRING(kDesktopImageKey), filePath);
  gconf->SetBool(NS_LITERAL_CSTRING(kDesktopDrawBGKey), PR_TRUE);

  return rv;
}
nsresult
nsDownloadManager::AssertProgressInfoFor(const nsACString& aTargetPath)
{
    nsDownload* internalDownload = mCurrDownloads.GetWeak(aTargetPath);
    if (!internalDownload)
        return NS_ERROR_FAILURE;

    nsresult rv;
    PRInt32 percentComplete;
    nsCOMPtr<nsIRDFNode> oldTarget;
    nsCOMPtr<nsIRDFInt> intLiteral;
    nsCOMPtr<nsIRDFResource> res;
    nsCOMPtr<nsIRDFLiteral> literal;

    gRDFService->GetResource(aTargetPath, getter_AddRefs(res));

    DownloadState state = internalDownload->GetDownloadState();

    // update progress mode
    nsAutoString progressMode;
    if (state == DOWNLOADING)
        progressMode.AssignLiteral("normal");
    else
        progressMode.AssignLiteral("none");

    gRDFService->GetLiteral(progressMode.get(), getter_AddRefs(literal));

    rv = mDataSource->GetTarget(res, gNC_ProgressMode, PR_TRUE, getter_AddRefs(oldTarget));

    if (oldTarget)
        rv = mDataSource->Change(res, gNC_ProgressMode, oldTarget, literal);
    else
        rv = mDataSource->Assert(res, gNC_ProgressMode, literal, PR_TRUE);
    if (NS_FAILED(rv)) return rv;

    // update download state (not started, downloading, queued, finished, etc...)
    gRDFService->GetIntLiteral(state, getter_AddRefs(intLiteral));

    mDataSource->GetTarget(res, gNC_DownloadState, PR_TRUE, getter_AddRefs(oldTarget));

    if (oldTarget) {
        rv = mDataSource->Change(res, gNC_DownloadState, oldTarget, intLiteral);
        if (NS_FAILED(rv)) return rv;
    }

    nsAutoString strKey;
    if (state == NOTSTARTED)
        strKey.AssignLiteral("notStarted");
    else if (state == DOWNLOADING)
        strKey.AssignLiteral("downloading");
    else if (state == FINISHED)
        strKey.AssignLiteral("finished");
    else if (state == FAILED)
        strKey.AssignLiteral("failed");
    else if (state == CANCELED)
        strKey.AssignLiteral("canceled");

    nsXPIDLString value;
    rv = mBundle->GetStringFromName(strKey.get(), getter_Copies(value));
    if (NS_FAILED(rv)) return rv;

    gRDFService->GetLiteral(value, getter_AddRefs(literal));

    rv = mDataSource->GetTarget(res, gNC_StatusText, PR_TRUE, getter_AddRefs(oldTarget));

    if (oldTarget) {
        rv = mDataSource->Change(res, gNC_StatusText, oldTarget, literal);
        if (NS_FAILED(rv)) return rv;
    }
    else {
        rv = mDataSource->Assert(res, gNC_StatusText, literal, PR_TRUE);
        if (NS_FAILED(rv)) return rv;
    }

    // update percentage
    internalDownload->GetPercentComplete(&percentComplete);

    mDataSource->GetTarget(res, gNC_ProgressPercent, PR_TRUE, getter_AddRefs(oldTarget));
    gRDFService->GetIntLiteral(percentComplete, getter_AddRefs(intLiteral));

    if (oldTarget)
        rv = mDataSource->Change(res, gNC_ProgressPercent, oldTarget, intLiteral);
    else
        rv = mDataSource->Assert(res, gNC_ProgressPercent, intLiteral, PR_TRUE);
    if (NS_FAILED(rv)) return rv;

    // update transferred
    nsDownload::TransferInformation transferInfo =
        internalDownload->GetTransferInformation();

    // convert from bytes to kbytes for progress display
    PRInt64 current = (transferInfo.mCurrBytes + 512) / 1024;
    PRInt64 max = (transferInfo.mMaxBytes + 512) / 1024;

    nsAutoString currBytes;
    currBytes.AppendInt(current);
    nsAutoString maxBytes;
    maxBytes.AppendInt(max);
    const PRUnichar *strings[] = {
        currBytes.get(),
        maxBytes.get()
    };

    rv = mBundle->FormatStringFromName(NS_LITERAL_STRING("transferred").get(),
                                       strings, 2, getter_Copies(value));
    if (NS_FAILED(rv)) return rv;

    gRDFService->GetLiteral(value, getter_AddRefs(literal));

    mDataSource->GetTarget(res, gNC_Transferred, PR_TRUE, getter_AddRefs(oldTarget));

    if (oldTarget)
        rv = mDataSource->Change(res, gNC_Transferred, oldTarget, literal);
    else
        rv = mDataSource->Assert(res, gNC_Transferred, literal, PR_TRUE);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIRDFRemoteDataSource> remote = do_QueryInterface(mDataSource);
    remote->Flush();

    // XXX should also store and update time elapsed
    return rv;
}
nsresult
nsOperaProfileMigrator::CopyBookmarksBatched(PRBool aReplace)
{
  // Find Opera Bookmarks
  nsCOMPtr<nsIFile> operaBookmarks;
  mOperaProfile->Clone(getter_AddRefs(operaBookmarks));
  operaBookmarks->Append(OPERA_BOOKMARKS_FILE_NAME);

  nsCOMPtr<nsIInputStream> fileInputStream;
  NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), operaBookmarks);
  NS_ENSURE_TRUE(fileInputStream, NS_ERROR_OUT_OF_MEMORY);

  nsCOMPtr<nsILineInputStream> lineInputStream(do_QueryInterface(fileInputStream));

  nsresult rv;
  nsCOMPtr<nsINavBookmarksService> bms =
    do_GetService(NS_NAVBOOKMARKSSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  PRInt64 bookmarksMenuFolderId;
  rv = bms->GetBookmarksMenuFolder(&bookmarksMenuFolderId);
  NS_ENSURE_SUCCESS(rv, rv);
  PRInt64 parentFolder = bookmarksMenuFolderId;

  nsCOMPtr<nsIStringBundleService> bundleService =
    do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIStringBundle> bundle;
  rv = bundleService->CreateBundle(MIGRATION_BUNDLE, getter_AddRefs(bundle));
  NS_ENSURE_SUCCESS(rv, rv);

  if (!aReplace) {
    nsString sourceNameOpera;
    rv = bundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(), 
                                   getter_Copies(sourceNameOpera));
    NS_ENSURE_SUCCESS(rv, rv);

    const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() };
    nsString importedOperaHotlistTitle;
    rv = bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                      sourceNameStrings, 1, 
                                      getter_Copies(importedOperaHotlistTitle));
   NS_ENSURE_SUCCESS(rv, rv);

    rv = bms->CreateFolder(parentFolder,
                           NS_ConvertUTF16toUTF8(importedOperaHotlistTitle),
                           nsINavBookmarksService::DEFAULT_INDEX,
                           &parentFolder);
   NS_ENSURE_SUCCESS(rv, rv);
  }
  else {
    nsCOMPtr<nsIFile> profile;
    GetProfilePath(nsnull, profile);
    rv = InitializeBookmarks(profile);
    NS_ENSURE_SUCCESS(rv, rv);
  }

#if defined(XP_WIN) || (defined(XP_UNIX) && !defined(XP_MACOSX))
  CopySmartKeywords(bms, bundle, parentFolder);
#endif

  PRInt64 bookmarksToolbarFolderId;
  rv = bms->GetToolbarFolder(&bookmarksToolbarFolderId);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = ParseBookmarksFolder(lineInputStream, parentFolder,
                            bookmarksToolbarFolderId, bms);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
NS_IMETHODIMP
nsDownloadManager::Observe(nsISupports* aSubject, const char* aTopic, const PRUnichar* aData)
{
    nsresult rv;
    if (nsCRT::strcmp(aTopic, "profile-approve-change") == 0) {
        // Only run this on profile switch
        if (!NS_LITERAL_STRING("switch").Equals(aData))
            return NS_OK;

        // If count == 0, nothing to do
        if (mCurrDownloads.Count() == 0)
            return NS_OK;

        nsCOMPtr<nsIProfileChangeStatus> changeStatus(do_QueryInterface(aSubject));
        if (!changeStatus)
            return NS_ERROR_UNEXPECTED;

        nsXPIDLString title, text, proceed, cancel;
        nsresult rv = mBundle->GetStringFromName(NS_LITERAL_STRING("profileSwitchTitle").get(),
                      getter_Copies(title));
        NS_ENSURE_SUCCESS(rv, rv);
        rv = mBundle->GetStringFromName(NS_LITERAL_STRING("profileSwitchText").get(),
                                        getter_Copies(text));
        NS_ENSURE_SUCCESS(rv, rv);
        rv = mBundle->GetStringFromName(NS_LITERAL_STRING("profileSwitchContinue").get(),
                                        getter_Copies(proceed));
        NS_ENSURE_SUCCESS(rv, rv);

        nsCOMPtr<nsIPromptService> promptService(do_GetService(NS_PROMPTSERVICE_CONTRACTID, &rv));
        if (NS_FAILED(rv))
            return rv;

        PRInt32 button;
        rv = promptService->ConfirmEx(nsnull, title.get(), text.get(),
                                      nsIPromptService::BUTTON_TITLE_CANCEL * nsIPromptService::BUTTON_POS_0 |
                                      nsIPromptService::BUTTON_TITLE_IS_STRING * nsIPromptService::BUTTON_POS_1,
                                      nsnull,
                                      proceed.get(),
                                      nsnull,
                                      nsnull,
                                      nsnull,
                                      &button);
        if (NS_FAILED(rv))
            return rv;

        if (button == 0)
            changeStatus->VetoChange();
    }
    else if (nsCRT::strcmp(aTopic, "profile-before-change") == 0) {
        nsCOMPtr<nsISupports> supports;
        nsCOMPtr<nsIRDFResource> res;
        nsCOMPtr<nsIRDFInt> intLiteral;

        gRDFService->GetIntLiteral(DOWNLOADING, getter_AddRefs(intLiteral));
        nsCOMPtr<nsISimpleEnumerator> downloads;
        rv = mDataSource->GetSources(gNC_DownloadState, intLiteral, PR_TRUE, getter_AddRefs(downloads));
        if (NS_FAILED(rv)) return rv;

        PRBool hasMoreElements;
        downloads->HasMoreElements(&hasMoreElements);

        while (hasMoreElements) {
            const char* uri;

            downloads->GetNext(getter_AddRefs(supports));
            res = do_QueryInterface(supports);
            res->GetValueConst(&uri);
            CancelDownload(nsDependentCString(uri));
            downloads->HasMoreElements(&hasMoreElements);
        }
    }
    return NS_OK;
}
nsresult
nsOperaProfileMigrator::ParseBookmarksFolder(nsILineInputStream* aStream, 
                                             PRInt64 aParent,
                                             PRInt64 aToolbar,
                                             nsINavBookmarksService* aBMS)
{
  nsresult rv;
  PRBool moreData = PR_FALSE;
  nsAutoString buffer;
  EntryType entryType = EntryType_BOOKMARK;
  nsAutoString keyword, description;
  nsCAutoString url, name;
  PRBool onToolbar = PR_FALSE;
  do {
    nsCAutoString cBuffer;
    rv = aStream->ReadLine(cBuffer, &moreData);
    if (NS_FAILED(rv)) return rv;
    
    CopyUTF8toUTF16(cBuffer, buffer);
    nsString data;
    LineType type = GetLineType(buffer, getter_Copies(data));
    switch(type) {
    case LineType_FOLDER:
      entryType = EntryType_FOLDER;
      break;
    case LineType_BOOKMARK:
      entryType = EntryType_BOOKMARK;
      break;
    case LineType_SEPARATOR:
      // If we're here, we need to break out of the loop for the current folder, 
      // essentially terminating this instance of ParseBookmarksFolder and return
      // to the calling function, which is either ParseBookmarksFolder for a parent
      // folder, or CopyBookmarks (which means we're done parsing all bookmarks).
      goto done;
    case LineType_NAME:
      name.Assign(NS_ConvertUTF16toUTF8(data));
      break;
    case LineType_URL:
      url.Assign(NS_ConvertUTF16toUTF8(data));
      break;
    case LineType_KEYWORD:
      keyword = data;
      break;
    case LineType_DESCRIPTION:
      description = data;
      break;
    case LineType_ONTOOLBAR:
      if (NS_LITERAL_STRING("YES").Equals(data))
        onToolbar = PR_TRUE;
      break;
    case LineType_NL: {
      // XXX We don't know for sure how Opera deals with IDN hostnames in URL.
      // Assuming it's in UTF-8 is rather safe because it covers two cases 
      // (UTF-8 and ASCII) out of three cases (the last is a non-UTF-8
      // multibyte encoding).
      // XXX Todo: |description| is not saved.
      if (entryType == EntryType_BOOKMARK) {
        if (!name.IsEmpty() && !url.IsEmpty()) {
          nsCOMPtr<nsIURI> uri;
          rv = NS_NewURI(getter_AddRefs(uri), url);
          if (NS_FAILED(rv))
            continue;
          PRInt64 id;
          rv = aBMS->InsertBookmark(onToolbar ? aToolbar : aParent,
                                    uri, nsINavBookmarksService::DEFAULT_INDEX,
                                    name, &id);
          if (NS_FAILED(rv))
            continue;
          name.Truncate();
          url.Truncate();
          keyword.Truncate();
          description.Truncate();
          onToolbar = PR_FALSE;
        }
      }
      else if (entryType == EntryType_FOLDER) {
        if (!name.IsEmpty()) {
          PRInt64 newFolder;
          rv = aBMS->CreateFolder(onToolbar ? aToolbar : aParent,
                                  name, nsINavBookmarksService::DEFAULT_INDEX, &newFolder);
          if (NS_FAILED(rv)) 
            continue;
          rv = ParseBookmarksFolder(aStream, newFolder, aToolbar, aBMS);
          name.Truncate();
        }
      }
      break;
    }
    case LineType_OTHER:
      break;
    }
  }
  while (moreData);

done:
  return rv;
}
示例#24
0
// Creates a folder in Local Folders with the module name + mail
// for e.g: Outlook Mail
bool nsImportGenericMail::CreateFolder(nsIMsgFolder **ppFolder)
{
  nsresult rv;
  *ppFolder = nsnull;

  nsCOMPtr<nsIStringBundle> bundle;
  nsCOMPtr<nsIStringBundleService> bundleService =
    mozilla::services::GetStringBundleService();
  if (!bundleService)
      return false;
  rv = bundleService->CreateBundle(IMPORT_MSGS_URL, getter_AddRefs(bundle));
  if (NS_FAILED(rv))
      return false;
  nsString folderName;
  if (!m_pName.IsEmpty()) {
    const PRUnichar *moduleName[] = { m_pName.get() };
    rv = bundle->FormatStringFromName(NS_LITERAL_STRING("ImportModuleFolderName").get(),
                                      moduleName, 1,
                                      getter_Copies(folderName));
  }
  else {
    rv = bundle->GetStringFromName(NS_LITERAL_STRING("DefaultFolderName").get(),
                                   getter_Copies(folderName));
  }
  if (NS_FAILED(rv)) {
      IMPORT_LOG0("*** Failed to get Folder Name!\n");
      return false;
  }
  nsCOMPtr <nsIMsgAccountManager> accMgr = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0("*** Failed to create account manager!\n");
    return false;
  }

  nsCOMPtr <nsIMsgIncomingServer> server;
  rv = accMgr->GetLocalFoldersServer(getter_AddRefs(server));
  // if Local Folders does not exist already, create it
  if (NS_FAILED(rv) || !server)
  {
    rv = accMgr->CreateLocalMailAccount();
    if (NS_FAILED(rv)) {
      IMPORT_LOG0("*** Failed to create Local Folders!\n");
      return false;
    }

    rv = accMgr->GetLocalFoldersServer(getter_AddRefs(server));
  }

  if (NS_SUCCEEDED(rv) && server) {
    nsCOMPtr <nsIMsgFolder> localRootFolder;
    rv = server->GetRootMsgFolder(getter_AddRefs(localRootFolder));
    if (localRootFolder) {
      // we need to call GetSubFolders() so that the folders get initialized
      // if they are not initialized yet.
      nsCOMPtr<nsISimpleEnumerator> aEnumerator;
      rv = localRootFolder->GetSubFolders(getter_AddRefs(aEnumerator));
      if (NS_SUCCEEDED(rv)) {
        // check if the folder name we picked already exists.
        bool exists = false;
        rv = localRootFolder->ContainsChildNamed(folderName, &exists);
        if (exists) {
          nsString name;
          localRootFolder->GenerateUniqueSubfolderName(folderName, nsnull, name);
          if (!name.IsEmpty())
            folderName.Assign(name);
          else {
            IMPORT_LOG0("*** Failed to find a unique folder name!\n");
            return false;
          }
        }
        IMPORT_LOG1("Creating folder for importing mail: '%s'\n", NS_ConvertUTF16toUTF8(folderName).get());

        // Bug 564162 identifies a dataloss design flaw.
        // A working Thunderbird client can have mail in Local Folders and a
        // subsequent import 'Everything' will trigger a migration which
        // overwrites existing mailboxes with the imported mailboxes.
        rv = localRootFolder->CreateSubfolder(folderName, nsnull);
        if (NS_SUCCEEDED(rv)) {
          rv = localRootFolder->GetChildNamed(folderName, ppFolder);
          if (*ppFolder) {
            IMPORT_LOG1("Folder '%s' created successfully\n", NS_ConvertUTF16toUTF8(folderName).get());
            return true;
          }
        }
      }
    } // if localRootFolder
  } // if server
  IMPORT_LOG0("****** FAILED TO CREATE FOLDER FOR IMPORT\n");
  return false;
}
/* nsIRDFNode GetTarget (in nsIRDFResource aSource, in nsIRDFResource property, in boolean aTruthValue); */
NS_IMETHODIMP
nsMsgAccountManagerDataSource::GetTarget(nsIRDFResource *source,
                                         nsIRDFResource *property,
                                         PRBool aTruthValue,
                                         nsIRDFNode **target)
{
  nsresult rv;


  rv = NS_RDF_NO_VALUE;

  nsAutoString str;
  if (property == kNC_Name || property == kNC_FolderTreeName ||
      property == kNC_FolderTreeSimpleName) 
  {
    rv = getStringBundle();
    NS_ENSURE_SUCCESS(rv, rv);

    nsString pageTitle;
    if (source == kNC_PageTitleServer)
      mStringBundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-server").get(),
                                       getter_Copies(pageTitle));

    else if (source == kNC_PageTitleCopies)
      mStringBundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-copies").get(),
                                       getter_Copies(pageTitle));
    else if (source == kNC_PageTitleOfflineAndDiskSpace)
      mStringBundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-offline-and-diskspace").get(),
                                       getter_Copies(pageTitle));
    else if (source == kNC_PageTitleDiskSpace)
      mStringBundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-diskspace").get(),
                                       getter_Copies(pageTitle));
    else if (source == kNC_PageTitleAddressing)
      mStringBundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-addressing").get(),
                                       getter_Copies(pageTitle));
    else if (source == kNC_PageTitleSMTP)
      mStringBundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-smtp").get(),
                                       getter_Copies(pageTitle));
    else if (source == kNC_PageTitleJunk)
      mStringBundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-junk").get(),
                                       getter_Copies(pageTitle));

    else if (source == kNC_PageTitleFakeAccount) {
      PRBool showFakeAccount;
      nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
      if (NS_SUCCEEDED(rv))
        rv = prefBranch->GetBoolPref(PREF_SHOW_FAKE_ACCOUNT, &showFakeAccount);

      if (showFakeAccount) {
        nsCOMPtr<nsIStringBundleService> strBundleService =
          do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
        if (NS_FAILED(rv)) return rv;
        nsCOMPtr<nsIStringBundle> bundle;
        rv = strBundleService->CreateBundle("chrome://messenger/locale/fakeAccount.properties",
                                             getter_AddRefs(bundle));
        if (NS_SUCCEEDED(rv))
          bundle->GetStringFromName(NS_LITERAL_STRING("prefPanel-fake-account").get(),
                                    getter_Copies(pageTitle));
      }
    }

    else {
      // if it's a server, use the pretty name
      nsCOMPtr<nsIMsgFolder> folder = do_QueryInterface(source, &rv);
      if (NS_SUCCEEDED(rv) && folder) {
        PRBool isServer;
        rv = folder->GetIsServer(&isServer);
        if (NS_SUCCEEDED(rv) && isServer)
          rv = folder->GetPrettyName(pageTitle);
      }
      else {
        // allow for the accountmanager to be dynamically extended.

        nsCOMPtr<nsIStringBundleService> strBundleService =
          do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        const char *sourceValue;
        rv = source->GetValueConst(&sourceValue);
        NS_ENSURE_SUCCESS(rv,rv);

        // make sure the pointer math we're about to do is safe.
        NS_ENSURE_TRUE(sourceValue && (strlen(sourceValue) > strlen(NC_RDF_PAGETITLE_PREFIX)), NS_ERROR_UNEXPECTED);

        nsCOMPtr<nsIMsgAccountManager> am = do_QueryReferent(mAccountManager, &rv);
        NS_ENSURE_SUCCESS(rv, PR_FALSE);

        // turn NC#PageTitlefoobar into foobar, so we can get the am-foobar.properties bundle
        nsCString chromePackageName;
        rv = am->GetChromePackageName(nsCString(sourceValue + strlen(NC_RDF_PAGETITLE_PREFIX)), chromePackageName);
        NS_ENSURE_SUCCESS(rv,rv);

        nsCAutoString bundleURL;
        bundleURL = "chrome://";
        bundleURL += chromePackageName;
        bundleURL += "/locale/am-";
        bundleURL += (sourceValue + strlen(NC_RDF_PAGETITLE_PREFIX));
        bundleURL += ".properties";

        nsCOMPtr <nsIStringBundle> bundle;
        rv = strBundleService->CreateBundle(bundleURL.get(), getter_AddRefs(bundle));

        NS_ENSURE_SUCCESS(rv,rv);

        nsAutoString panelTitleName;
        panelTitleName.AssignLiteral("prefPanel-");
        panelTitleName.Append(NS_ConvertASCIItoUTF16(sourceValue + strlen(NC_RDF_PAGETITLE_PREFIX)));
        bundle->GetStringFromName(panelTitleName.get(), getter_Copies(pageTitle));
      }
    }
    str = pageTitle.get();
  }
  else if (property == kNC_PageTag) {
    // do NOT localize these strings. these are the urls of the XUL files
    if (source == kNC_PageTitleServer)
      str.AssignLiteral("am-server.xul");
    else if (source == kNC_PageTitleCopies)
      str.AssignLiteral("am-copies.xul");
    else if ((source == kNC_PageTitleOfflineAndDiskSpace) ||
             (source == kNC_PageTitleDiskSpace))
      str.AssignLiteral("am-offline.xul");
    else if (source == kNC_PageTitleAddressing)
      str.AssignLiteral("am-addressing.xul");
    else if (source == kNC_PageTitleSMTP)
      str.AssignLiteral("am-smtp.xul");
    else if (source == kNC_PageTitleJunk)
      str.AssignLiteral("am-junk.xul");
    else if (source == kNC_PageTitleFakeAccount)
      str.AssignLiteral("am-fakeaccount.xul");
    else {
      nsCOMPtr<nsIMsgFolder> folder = do_QueryInterface(source, &rv);
      if (NS_SUCCEEDED(rv) && folder) {
        /* if this is a server, with no identities, then we show a special panel */
        nsCOMPtr<nsIMsgIncomingServer> server;
        rv = getServerForFolderNode(source, getter_AddRefs(server));
        if (server)
          server->GetAccountManagerChrome(str);
        else 
          str.AssignLiteral("am-main.xul");
      }
      else {
        // allow for the accountmanager to be dynamically extended
        const char *sourceValue;
        rv = source->GetValueConst(&sourceValue);
        NS_ENSURE_SUCCESS(rv,rv);

        // make sure the pointer math we're about to do is safe.
        NS_ENSURE_TRUE(sourceValue && (strlen(sourceValue) > strlen(NC_RDF_PAGETITLE_PREFIX)), NS_ERROR_UNEXPECTED);

        // turn NC#PageTitlefoobar into foobar, so we can get the am-foobar.xul file
        str.AssignLiteral("am-");
        str.Append(NS_ConvertASCIItoUTF16(sourceValue + strlen(NC_RDF_PAGETITLE_PREFIX)));
        str.AppendLiteral(".xul");
      }
    }
  }

  // handle sorting of servers
  else if ((property == kNC_NameSort) ||
           (property == kNC_FolderTreeNameSort)) {

    // order for the folder pane
    // and for the account manager tree is:
    //
    // - default mail account
    // - <other mail accounts>
    // - "Local Folders" account
    // - news accounts
    // - smtp settings (note, this is only in account manager tree)
    // - fake account

    // make sure we're handling a root folder that is a server
    nsCOMPtr<nsIMsgIncomingServer> server;
    rv = getServerForFolderNode(source, getter_AddRefs(server));

    if (NS_SUCCEEDED(rv) && server) {
      PRInt32 accountNum;
      nsCOMPtr<nsIMsgAccountManager> am = do_QueryReferent(mAccountManager);

      if (isDefaultServer(server))
        str.AssignLiteral("0000");
      else {
        rv = am->FindServerIndex(server, &accountNum);
        if (NS_FAILED(rv)) return rv;

        // this is a hack for now - hardcode server order by type
        nsCString serverType;
        server->GetType(serverType);

        if (serverType.LowerCaseEqualsLiteral("none"))
          accountNum += 2000;
        else if (serverType.LowerCaseEqualsLiteral("nntp"))
          accountNum += 3000;
        else
          accountNum += 1000;     // default is to appear at the top

        str.AppendInt(accountNum);
      }
    }
    else {
      const char *sourceValue;
      rv = source->GetValueConst(&sourceValue);
      NS_ENSURE_SUCCESS(rv, NS_RDF_NO_VALUE);

      // if this is a page (which we determine by the prefix of the URI)
      // we want to generate a sort value
      // so that we can sort the categories in the account manager tree
      // (or the folder pane)
      //
      // otherwise, return NS_RDF_NO_VALUE
      // so that the folder data source will take care of it.
      if (sourceValue && (strncmp(sourceValue, NC_RDF_PAGETITLE_PREFIX, strlen(NC_RDF_PAGETITLE_PREFIX)) == 0)) {
        if (source == kNC_PageTitleSMTP)
          str.AssignLiteral("4000");
        else if (source == kNC_PageTitleFakeAccount)
          str.AssignLiteral("5000");
        else if (source == kNC_PageTitleServer)
          str.AssignLiteral("1");
        else if (source == kNC_PageTitleCopies)
          str.AssignLiteral("2");
        else if (source == kNC_PageTitleAddressing)
          str.AssignLiteral("3");
        else if (source == kNC_PageTitleOfflineAndDiskSpace)
          str.AssignLiteral("4");
        else if (source == kNC_PageTitleDiskSpace)
          str.AssignLiteral("4");
        else if (source == kNC_PageTitleJunk)
          str.AssignLiteral("5");
        else {
          // allow for the accountmanager to be dynamically extended
          // all the other pages come after the standard ones
          // server, copies, addressing, disk space (or offline & disk space)
          CopyASCIItoUTF16(sourceValue, str);
        }
      }
      else {
        return NS_RDF_NO_VALUE;
      }
    }
  }

  // GetTargets() stuff - need to return a valid answer so that
  // twisties will appear
  else if (property == kNC_Settings) {
    nsCOMPtr<nsIMsgFolder> folder = do_QueryInterface(source,&rv);
    if (NS_FAILED(rv))
      return NS_RDF_NO_VALUE;

    PRBool isServer=PR_FALSE;
    folder->GetIsServer(&isServer);
    // no need to localize this!
    if (isServer)
      str.AssignLiteral("ServerSettings");
  }

  else if (property == kNC_IsDefaultServer) {
    nsCOMPtr<nsIMsgIncomingServer> thisServer;
    rv = getServerForFolderNode(source, getter_AddRefs(thisServer));
    if (NS_FAILED(rv) || !thisServer) return NS_RDF_NO_VALUE;

    if (isDefaultServer(thisServer))
      str.AssignLiteral("true");
  }

  else if (property == kNC_SupportsFilters) {
    nsCOMPtr<nsIMsgIncomingServer> server;
    rv = getServerForFolderNode(source, getter_AddRefs(server));
    if (NS_FAILED(rv) || !server) return NS_RDF_NO_VALUE;

    if (supportsFilters(server))
      str.AssignLiteral("true");
  }
  else if (property == kNC_CanGetMessages) {
    nsCOMPtr<nsIMsgIncomingServer> server;
    rv = getServerForFolderNode(source, getter_AddRefs(server));
    if (NS_FAILED(rv) || !server) return NS_RDF_NO_VALUE;

    if (canGetMessages(server))
      str.AssignLiteral("true");
  }
  else if (property == kNC_CanGetIncomingMessages) {
    nsCOMPtr<nsIMsgIncomingServer> server;
    rv = getServerForFolderNode(source, getter_AddRefs(server));
    if (NS_FAILED(rv) || !server) return NS_RDF_NO_VALUE;

    if (canGetIncomingMessages(server))
      str.AssignLiteral("true");
  }
  else if (property == kNC_PageTitleFakeAccount) {
    if (source == kNC_PageTitleFakeAccount)
      str.AssignLiteral("true");
  }
  if (!str.IsEmpty())
    rv = createNode(str.get(), target, getRDFService());

  //if we have an empty string and we don't have an error value, then
  //we don't have a value for RDF.
  else if(NS_SUCCEEDED(rv))
    rv = NS_RDF_NO_VALUE;

  return rv;
}
示例#26
0
nsresult
nsAlertsIconListener::InitAlertAsync(const nsAString & aImageUrl,
                                     const nsAString & aAlertTitle, 
                                     const nsAString & aAlertText,
                                     bool aAlertTextClickable,
                                     const nsAString & aAlertCookie,
                                     nsIObserver * aAlertListener,
                                     bool aInPrivateBrowsing)
{
  if (!libNotifyHandle)
    return NS_ERROR_FAILURE;

  if (!notify_is_initted()) {
    // Give the name of this application to libnotify
    nsCOMPtr<nsIStringBundleService> bundleService = 
      do_GetService(NS_STRINGBUNDLE_CONTRACTID);

    nsAutoCString appShortName;
    if (bundleService) {
      nsCOMPtr<nsIStringBundle> bundle;
      bundleService->CreateBundle("chrome://branding/locale/brand.properties",
                                  getter_AddRefs(bundle));
      nsAutoString appName;

      if (bundle) {
        bundle->GetStringFromName(MOZ_UTF16("brandShortName"),
                                  getter_Copies(appName));
        appShortName = NS_ConvertUTF16toUTF8(appName);
      } else {
        NS_WARNING("brand.properties not present, using default application name");
        appShortName.AssignLiteral("Mozilla");
      }
    } else {
      appShortName.AssignLiteral("Mozilla");
    }

    if (!notify_init(appShortName.get()))
      return NS_ERROR_FAILURE;

    GList *server_caps = notify_get_server_caps();
    if (server_caps) {
      gHasCaps = true;
      for (GList* cap = server_caps; cap != nullptr; cap = cap->next) {
        if (!strcmp((char*) cap->data, "actions")) {
          gHasActions = true;
          break;
        }
      }
      g_list_foreach(server_caps, (GFunc)g_free, nullptr);
      g_list_free(server_caps);
    }
  }

  if (!gHasCaps) {
    // if notify_get_server_caps() failed above we need to assume
    // there is no notification-server to display anything
    return NS_ERROR_FAILURE;
  }

  if (!gHasActions && aAlertTextClickable)
    return NS_ERROR_FAILURE; // No good, fallback to XUL

  nsCOMPtr<nsIObserverService> obsServ =
      do_GetService("@mozilla.org/observer-service;1");
  if (obsServ)
    obsServ->AddObserver(this, "quit-application", true);

  // Workaround for a libnotify bug - blank titles aren't dealt with
  // properly so we use a space
  if (aAlertTitle.IsEmpty()) {
    mAlertTitle = NS_LITERAL_CSTRING(" ");
  } else {
    mAlertTitle = NS_ConvertUTF16toUTF8(aAlertTitle);
  }

  mAlertText = NS_ConvertUTF16toUTF8(aAlertText);
  mAlertHasAction = aAlertTextClickable;

  mAlertListener = aAlertListener;
  mAlertCookie = aAlertCookie;

  return StartRequest(aImageUrl, aInPrivateBrowsing);
}
nsresult nsAbLDAPProcessChangeLogData::GetAuthData()
{
    if(!mInitialized) 
        return NS_ERROR_NOT_INITIALIZED;

    nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
    if (!wwatch)
        return NS_ERROR_FAILURE;
    
    nsCOMPtr<nsIAuthPrompt> dialog;
    nsresult rv = wwatch->GetNewAuthPrompter(0, getter_AddRefs(dialog));
    if (NS_FAILED(rv))
        return rv;
    if (!dialog) 
        return NS_ERROR_FAILURE;

    nsCOMPtr<nsILDAPURL> url;
    rv = mQuery->GetReplicationURL(getter_AddRefs(url));
    if (NS_FAILED(rv))
        return rv;

    nsAutoCString serverUri;
    rv = url->GetSpec(serverUri);
    if (NS_FAILED(rv)) 
        return rv;

    nsCOMPtr<nsIStringBundleService> bundleService =
      mozilla::services::GetStringBundleService();
    NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED);
    nsCOMPtr<nsIStringBundle> bundle;
    rv = bundleService->CreateBundle("chrome://messenger/locale/addressbook/addressBook.properties", getter_AddRefs(bundle));
    if (NS_FAILED (rv)) 
        return rv ;

    nsString title;
    rv = bundle->GetStringFromName(NS_LITERAL_STRING("AuthDlgTitle").get(), getter_Copies(title));
    if (NS_FAILED (rv)) 
        return rv ;

    nsString desc;
    rv = bundle->GetStringFromName(NS_LITERAL_STRING("AuthDlgDesc").get(), getter_Copies(desc));
    if (NS_FAILED (rv)) 
        return rv ;

    nsString username;
    nsString password;
    bool btnResult = false;
	rv = dialog->PromptUsernameAndPassword(title, desc, 
                                            NS_ConvertUTF8toUTF16(serverUri).get(), 
                                            nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY,
                                            getter_Copies(username), getter_Copies(password), 
                                            &btnResult);
    if(NS_SUCCEEDED(rv) && btnResult) {
        CopyUTF16toUTF8(username, mAuthUserID);
        CopyUTF16toUTF8(password, mAuthPswd);
    }
    else
        rv = NS_ERROR_FAILURE;

    return rv;
}
NS_IMETHODIMP
nsDragService::SetupDragSession(
                                nsISupportsArray *aTransferables,
                                uint32_t aActionType)
{
    uint32_t itemCount = 0;
    aTransferables->Count(&itemCount);
    if (0 == itemCount)
    {
        NS_WARNING("No items to drag?");
        return NS_ERROR_FAILURE;
    }

    if (1 != itemCount)
    {
        NS_WARNING("Dragging more than one item, cannot do (yet?)");
        return NS_ERROR_NOT_IMPLEMENTED;
    }

    SetDropActionType(aActionType);

    QMimeData *mimeData = new QMimeData;

    nsCOMPtr<nsISupports> genericItem;
    aTransferables->GetElementAt(0, getter_AddRefs(genericItem));
    nsCOMPtr<nsITransferable> transferable(do_QueryInterface(genericItem));

    if (transferable)
    {
        nsCOMPtr <nsISupportsArray> flavorList;
        transferable->FlavorsTransferableCanExport(getter_AddRefs(flavorList));

        if (flavorList)
        {
            uint32_t flavorCount;
            flavorList->Count( &flavorCount );

            for (uint32_t flavor=0; flavor < flavorCount; flavor++)
            {
                nsCOMPtr<nsISupports> genericWrapper;
                flavorList->GetElementAt(flavor, getter_AddRefs(genericWrapper));
                nsCOMPtr<nsISupportsCString> currentFlavor;
                currentFlavor = do_QueryInterface(genericWrapper);

                if (currentFlavor)
                {
                    nsCOMPtr<nsISupports> data;
                    uint32_t dataLen = 0;
                    nsXPIDLCString flavorStr;
                    currentFlavor->ToString(getter_Copies(flavorStr));

                    // Is it some flavor we think we could support?
                    if (!strcmp(kURLMime, flavorStr.get())
                     || !strcmp(kURLDataMime, flavorStr.get())
                     || !strcmp(kURLDescriptionMime, flavorStr.get())
                     || !strcmp(kHTMLMime, flavorStr.get())
                     || !strcmp(kUnicodeMime, flavorStr.get())
                        )
                    {
                        transferable->GetTransferData(flavorStr,getter_AddRefs(data),&dataLen);

                        nsCOMPtr<nsISupportsString> wideString;
                        wideString = do_QueryInterface(data);
                        if (!wideString)
                        {
                            return NS_ERROR_FAILURE;
                        }

                        nsAutoString utf16string;
                        wideString->GetData(utf16string);
                        QByteArray ba((const char*) utf16string.get(), dataLen);

                        mimeData->setData(flavorStr.get(), ba);
                    }
                }
            }
        }
    }

    if (qApp->thread() != QThread::currentThread()) {
        NS_WARNING("Cannot initialize drag session in non main thread");
        return NS_OK;
    }

    if (!mHiddenWidget) {
      mHiddenWidget = new QWidget();
    }
    mDrag = new QDrag( mHiddenWidget ); // TODO: Better drag source here?
    mDrag->setMimeData(mimeData);

    // mDrag and mimeData SHOULD NOT be destroyed. They are destroyed by QT.

    return NS_OK;
}
示例#29
0
NS_IMETHODIMP
nsGNOMEShellService::SetDefaultBrowser(PRBool aClaimAllTypes,
                                       PRBool aForAllUsers)
{
#ifdef DEBUG
  if (aForAllUsers)
    NS_WARNING("Setting the default browser for all users is not yet supported");
#endif

  nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);

  nsCAutoString schemeList;
  nsCAutoString appKeyValue(mAppPath + NS_LITERAL_CSTRING(" \"%s\""));
  unsigned int i;

  for (i = 0; i < NS_ARRAY_LENGTH(appProtocols); ++i) {
    schemeList.Append(nsDependentCString(appProtocols[i].name)
                      + NS_LITERAL_CSTRING(","));

    if (appProtocols[i].essential || aClaimAllTypes) {
      gconf->SetAppForProtocol(nsDependentCString(appProtocols[i].name),
                               appKeyValue);
    }
  }

  if (aClaimAllTypes) {
    nsCOMPtr<nsIGnomeVFSService> vfs =
      do_GetService(NS_GNOMEVFSSERVICE_CONTRACTID);

    nsCOMPtr<nsIStringBundleService> bundleService =
      do_GetService(NS_STRINGBUNDLE_CONTRACTID);
    NS_ENSURE_TRUE(bundleService, NS_ERROR_OUT_OF_MEMORY);

    nsCOMPtr<nsIStringBundle> brandBundle;
    bundleService->CreateBundle(BRAND_PROPERTIES, getter_AddRefs(brandBundle));
    NS_ENSURE_TRUE(brandBundle, NS_ERROR_FAILURE);

    nsXPIDLString brandShortName, brandFullName;
    brandBundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(),
                                   getter_Copies(brandShortName));
    brandBundle->GetStringFromName(NS_LITERAL_STRING("brandFullName").get(),
                                   getter_Copies(brandFullName));

    // use brandShortName as the application id.
    NS_ConvertUTF16toUTF8 id(brandShortName);

    vfs->SetAppStringKey(id, nsIGnomeVFSService::APP_KEY_COMMAND, mAppPath);
    vfs->SetAppStringKey(id, nsIGnomeVFSService::APP_KEY_NAME,
                         NS_ConvertUTF16toUTF8(brandFullName));

    // We don't want to be the default handler for "file:", but we do
    // want Nautilus to know that we support file: if the MIME type is
    // one that we can handle.

    schemeList.Append("file");

    vfs->SetAppStringKey(id, nsIGnomeVFSService::APP_KEY_SUPPORTED_URI_SCHEMES,
                         schemeList);

    vfs->SetAppStringKey(id, nsIGnomeVFSService::APP_KEY_EXPECTS_URIS,
                         NS_LITERAL_CSTRING("true"));

    vfs->SetAppBoolKey(id, nsIGnomeVFSService::APP_KEY_CAN_OPEN_MULTIPLE,
                       PR_FALSE);

    vfs->SetAppBoolKey(id, nsIGnomeVFSService::APP_KEY_REQUIRES_TERMINAL,
                       PR_FALSE);

    // Copy icons/document.png to ~/.icons/firefox-document.png
    nsCAutoString iconFilePath(mAppPath);
    PRInt32 lastSlash = iconFilePath.RFindChar(PRUnichar('/'));
    if (lastSlash == -1) {
      NS_ERROR("no slash in executable path?");
    } else {
      iconFilePath.Truncate(lastSlash);
      nsCOMPtr<nsILocalFile> iconFile;
      NS_NewNativeLocalFile(iconFilePath, PR_FALSE, getter_AddRefs(iconFile));
      if (iconFile) {
        iconFile->AppendRelativeNativePath(NS_LITERAL_CSTRING("icons/document.png"));

        nsCOMPtr<nsILocalFile> userIconPath;
        NS_NewNativeLocalFile(nsDependentCString(PR_GetEnv("HOME")), PR_FALSE,
                              getter_AddRefs(userIconPath));
        if (userIconPath) {
          userIconPath->AppendNative(NS_LITERAL_CSTRING(".icons"));
          iconFile->CopyToNative(userIconPath,
                                 nsDependentCString(kDocumentIconPath));
        }
      }
    }

    for (i = 0; i < NS_ARRAY_LENGTH(appTypes); ++i) {
      vfs->AddMimeType(id, nsDependentCString(appTypes[i].mimeType));
      vfs->SetMimeExtensions(nsDependentCString(appTypes[i].mimeType),
                             nsDependentCString(appTypes[i].extensions));
      vfs->SetAppForMimeType(nsDependentCString(appTypes[i].mimeType), id);
      vfs->SetIconForMimeType(nsDependentCString(appTypes[i].mimeType),
                              NS_LITERAL_CSTRING(kDocumentIconPath));
    }

    vfs->SyncAppRegistry();
  }

  return NS_OK;
}
示例#30
0
nsDBFolderInfo::nsDBFolderInfo(nsMsgDatabase *mdb)
    : m_flags(0),
      m_expiredMark(0),
      m_expiredMarkColumnToken(0)
{
    m_mdbTable = NULL;
    m_mdbRow = NULL;
    m_version = 1; // for upgrading...
    m_IMAPHierarchySeparator = 0; // imap path separator
    // mail only (for now)
    m_folderSize = 0;
    m_folderDate = 0;
    m_expungedBytes = 0; // sum of size of deleted messages in folder
    m_highWaterMessageKey = 0;

    m_numUnreadMessages = 0;
    m_numMessages = 0;
    // IMAP only
    m_ImapUidValidity = kUidUnknown;
    m_totalPendingMessages =0;
    m_unreadPendingMessages = 0;

    m_mdbTokensInitialized = false;
    m_charSetOverride = false;

    if (!gFolderCharsetObserver)
    {
        nsresult rv;
        nsCOMPtr<nsIPrefService> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
        nsCOMPtr<nsIPrefBranch> prefBranch;
        if (NS_SUCCEEDED(rv))
        {
            rv = prefs->GetBranch(nullptr, getter_AddRefs(prefBranch));
        }
        if (NS_SUCCEEDED(rv))
        {
            nsCOMPtr<nsIPrefLocalizedString> pls;
            rv = prefBranch->GetComplexValue(kMAILNEWS_VIEW_DEFAULT_CHARSET,
                                             NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(pls));
            if (NS_SUCCEEDED(rv))
            {
                nsString ucsval;
                pls->ToString(getter_Copies(ucsval));
                if (!ucsval.IsEmpty())
                {
                    if (!gDefaultCharacterSet)
                        gDefaultCharacterSet = new nsCString;

                    if (gDefaultCharacterSet)
                        CopyUTF16toUTF8(ucsval, *gDefaultCharacterSet);
                }
            }
            rv = prefBranch->GetBoolPref(kMAILNEWS_DEFAULT_CHARSET_OVERRIDE, &gDefaultCharacterOverride);

            gFolderCharsetObserver = new nsFolderCharsetObserver();
            NS_ASSERTION(gFolderCharsetObserver, "failed to create observer");

            // register prefs callbacks
            if (gFolderCharsetObserver)
            {
                NS_ADDREF(gFolderCharsetObserver);
                rv = prefBranch->AddObserver(kMAILNEWS_VIEW_DEFAULT_CHARSET, gFolderCharsetObserver, false);
                rv = prefBranch->AddObserver(kMAILNEWS_DEFAULT_CHARSET_OVERRIDE, gFolderCharsetObserver, false);

                // also register for shutdown
                nsCOMPtr<nsIObserverService> observerService =
                    mozilla::services::GetObserverService();
                if (observerService)
                {
                    rv = observerService->AddObserver(gFolderCharsetObserver, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
                }
            }
        }
    }

    m_mdb = mdb;
    if (mdb)
    {
        mdb_err err;

        //		mdb->AddRef();
        err = m_mdb->GetStore()->StringToToken(mdb->GetEnv(), kDBFolderInfoScope, &m_rowScopeToken);
        if (NS_SUCCEEDED(err))
        {
            err = m_mdb->GetStore()->StringToToken(mdb->GetEnv(), kDBFolderInfoTableKind, &m_tableKindToken);
            if (NS_SUCCEEDED(err))
            {
                gDBFolderInfoOID.mOid_Scope = m_rowScopeToken;
                gDBFolderInfoOID.mOid_Id = 1;
            }
        }
        InitMDBInfo();
    }
}