Пример #1
0
TEST(Encoding, BackwardsSurrogatePair)
{
  // When this string is decoded, the two surrogates are wrongly ordered and
  // must each be interpreted as U+FFFD.
  const char16_t backwardsPairData[] = { 0xDDDD, 0xD863, 0x65, 0x78, 0x0 };
  nsDependentString backwardsPair16(backwardsPairData);

  uint32_t byteCount = 0;
  char* backwardsPair8 = ToNewUTF8String(backwardsPair16, &byteCount);
  EXPECT_TRUE(!!backwardsPair8);

  EXPECT_EQ(byteCount, 8u);

  const unsigned char expected8[] =
    { 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0x65, 0x78, 0x0 };
  EXPECT_EQ(0, memcmp(expected8, backwardsPair8, sizeof(expected8)));

  // This takes a different code path from the above, so test it to make sure
  // the UTF-16 enumeration remains in sync with the UTF-8 enumeration.
  nsDependentCString expected((const char*)expected8);
  EXPECT_EQ(0, CompareUTF8toUTF16(expected, backwardsPair16));

  NS_Free(backwardsPair8);
}
Пример #2
0
TEST(Encoding, MalformedUTF16OrphanHighSurrogate)
{
  // When this string is decoded, the high surrogate should be replaced and the
  // rest of the string is specified by indexes 1 onward.
  const char16_t highSurrogateData[] = { 0xD863, 0x74, 0x65, 0x78, 0x74, 0x0 };
  nsDependentString highSurrogate16(highSurrogateData);

  uint32_t byteCount = 0;
  char* highSurrogate8 = ToNewUTF8String(highSurrogate16, &byteCount);
  EXPECT_TRUE(!!highSurrogate8);

  EXPECT_EQ(byteCount, 7u);

  const unsigned char expected8[] =
    { 0xEF, 0xBF, 0xBD, 0x74, 0x65, 0x78, 0x74, 0x0 };
  EXPECT_EQ(0, memcmp(expected8, highSurrogate8, sizeof(expected8)));

  // This takes a different code path from the above, so test it to make sure
  // the UTF-16 enumeration remains in sync with the UTF-8 enumeration.
  nsDependentCString expected((const char*)expected8);
  EXPECT_EQ(0, CompareUTF8toUTF16(expected, highSurrogate16));

  NS_Free(highSurrogate8);
}
Пример #3
0
NS_IMETHODIMP
nsScriptErrorBase::ToString(nsACString& /*UTF8*/ aResult)
{
    static const char format0[] =
        "[%s: \"%s\" {file: \"%s\" line: %d column: %d source: \"%s\"}]";
    static const char format1[] =
        "[%s: \"%s\" {file: \"%s\" line: %d}]";
    static const char format2[] =
        "[%s: \"%s\"]";

    static const char error[]   = "JavaScript Error";
    static const char warning[] = "JavaScript Warning";

    const char* severity = !(mFlags & JSREPORT_WARNING) ? error : warning;

    char* temp;
    char* tempMessage = nullptr;
    char* tempSourceName = nullptr;
    char* tempSourceLine = nullptr;

    if (!mMessage.IsEmpty())
        tempMessage = ToNewUTF8String(mMessage);
    if (!mSourceName.IsEmpty())
        // Use at most 512 characters from mSourceName.
        tempSourceName = ToNewUTF8String(StringHead(mSourceName, 512));
    if (!mSourceLine.IsEmpty())
        // Use at most 512 characters from mSourceLine.
        tempSourceLine = ToNewUTF8String(StringHead(mSourceLine, 512));

    if (nullptr != tempSourceName && nullptr != tempSourceLine)
        temp = JS_smprintf(format0,
                           severity,
                           tempMessage,
                           tempSourceName,
                           mLineNumber,
                           mColumnNumber,
                           tempSourceLine);
    else if (!mSourceName.IsEmpty())
        temp = JS_smprintf(format1,
                           severity,
                           tempMessage,
                           tempSourceName,
                           mLineNumber);
    else
        temp = JS_smprintf(format2,
                           severity,
                           tempMessage);

    if (nullptr != tempMessage)
        free(tempMessage);
    if (nullptr != tempSourceName)
        free(tempSourceName);
    if (nullptr != tempSourceLine)
        free(tempSourceLine);

    if (!temp)
        return NS_ERROR_OUT_OF_MEMORY;

    aResult.Assign(temp);
    JS_smprintf_free(temp);
    return NS_OK;
}
NS_IMETHODIMP RenameFolderTask::Run() {
	int ret = EWS_FAIL;
	nsresult rv;

	if (EWS_FAIL == NotifyBegin(this)) {
		return NS_OK;
	}
	
	ews_session * session = NULL;
	nsCOMPtr<IMailEwsMsgIncomingServer> ewsServer(do_QueryInterface(m_pIncomingServer, &rv));
	NS_ENSURE_SUCCESS(rv, rv);

	nsCOMPtr<IMailEwsService> ewsService;
	rv = ewsServer->GetService(getter_AddRefs(ewsService));
	NS_ENSURE_SUCCESS(rv, rv);

	nsresult rv1 = ewsService->GetNewSession(&session);

	if (NS_SUCCEEDED(rv)
	    && NS_SUCCEEDED(rv1)
	    && session) {
		nsCOMPtr<IMailEwsMsgFolder> curFolder(do_QueryInterface(m_Folder));
		
		nsCString savedFolderId;
		rv = curFolder->GetFolderId(savedFolderId);
		if (NS_FAILED(rv)) {
			NotifyError(this, EWS_FAIL, "unable to get folder id");
			return NS_OK;
		}

		nsCString change_key;
		rv = curFolder->GetChangeKey(change_key);
		if (NS_FAILED(rv)) {
			NotifyError(this, EWS_FAIL, "unable to get folder change key");
			return NS_OK;
		}
  
		ews_folder * folder = (ews_folder *)malloc(sizeof(char) * sizeof(ews_folder));
		memset(folder, 0, sizeof(ews_folder));
		char * display_name = ToNewUTF8String(m_NewName);
		folder->display_name = strdup(display_name);
		folder->id = strdup(savedFolderId.get());
		folder->change_key = strdup(change_key.get());
		NS_Free(display_name);
		
		char * err_msg = NULL;

		ret = ews_update_folder(session,
		                            folder,
		                            &err_msg);

		if (ret != EWS_SUCCESS) {
			mailews_logger << "rename folder on server fail:"
			          << ret
			          << ","
			          << err_msg
			          << std::endl;
			NotifyError(this, ret, err_msg);
		}

		if (err_msg) free(err_msg);

		ews_free_folder(folder);
	} else {
		NotifyError(this, session ? EWS_FAIL : 401, NULL);
	}

	ewsService->ReleaseSession(session);
	
	nsCOMPtr<nsIRunnable> resultrunnable =
			new RenameFolderDoneTask(ret,
			                         m_Folder,
			                         m_NewName,
			                         m_MsgWindow,
			                         m_pEwsTaskCallbacks,
			                         this);
		
	NS_DispatchToMainThread(resultrunnable);

	return NS_OK;
}
Пример #5
0
bool CMapiMessage::AddAttachment(DWORD aNum)
{
  LPATTACH lpAttach = NULL;
  HRESULT hr = m_lpMsg->OpenAttach(aNum, NULL, 0, &lpAttach);
  if (HR_FAILED(hr)) {
    MAPI_TRACE2("\t\t****Attachment error, unable to open attachment: %d, 0x%lx\r\n", idx, hr);
    return false;
  }

  bool bResult = false;
  attach_data *data = new attach_data;
  ULONG aMethod;
  if (data) {
    bResult = true;

    // 1. Get the file that contains the attachment data
    LPSPropValue pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_METHOD);
    if (pVal) {
      aMethod = CMapiApi::GetLongFromProp(pVal);
      switch (aMethod) {
      case ATTACH_BY_VALUE:
        MAPI_TRACE1("\t\t** Attachment #%d by value.\r\n", aNum);
        bResult = CopyBinAttachToFile(lpAttach, getter_AddRefs(data->tmp_file));
        data->delete_file = true;
        break;
      case ATTACH_BY_REFERENCE:
      case ATTACH_BY_REF_RESOLVE:
      case ATTACH_BY_REF_ONLY:
        pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_PATHNAME_W);
        if (pVal) {
          nsCString path;
          CMapiApi::GetStringFromProp(pVal, path);
          nsresult rv;
          data->tmp_file = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
          if (NS_FAILED(rv) || !data->tmp_file) {
            MAPI_TRACE0("*** Error creating file spec for attachment\n");
            bResult = false;
          }
          else data->tmp_file->InitWithNativePath(path);
        }
        MAPI_TRACE2("\t\t** Attachment #%d by ref: %s\r\n",
          aNum, m_attachPath.get());
        break;
      case ATTACH_EMBEDDED_MSG:
        MAPI_TRACE1("\t\t** Attachment #%d by Embedded Message??\r\n", aNum);
        // Convert the embedded IMessage from PR_ATTACH_DATA_OBJ to rfc822 attachment
        // (see http://msdn.microsoft.com/en-us/library/cc842329.aspx)
        // This is a recursive call.
        bResult = CopyMsgAttachToFile(lpAttach, getter_AddRefs(data->tmp_file));
        data->delete_file = true;
        break;
      case ATTACH_OLE:
        MAPI_TRACE1("\t\t** Attachment #%d by OLE - yuck!!!\r\n", aNum);
        break;
      default:
        MAPI_TRACE2("\t\t** Attachment #%d unknown attachment method - 0x%lx\r\n", aNum, aMethod);
        bResult = false;
      }
    }
    else
      bResult = false;

    if (bResult)
      bResult = data->tmp_file;

    if (bResult) {
      bool isFile = false;
      bool exists = false;
      data->tmp_file->Exists(&exists);
      data->tmp_file->IsFile(&isFile);

      if (!exists || !isFile) {
        bResult = false;
        MAPI_TRACE0("Attachment file does not exist\n");
      }
    }

    if (bResult)
      bResult = GetURL(data->tmp_file, getter_AddRefs(data->orig_url));

    if (bResult) {
      // Now we have the file; proceed to the other properties

      data->encoding = NS_strdup(ENCODING_BINARY);

      nsString fname, fext;
      pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_LONG_FILENAME_W);
      if (!pVal)
        pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_FILENAME_W);
      CMapiApi::GetStringFromProp(pVal, fname);
      pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_EXTENSION_W);
      CMapiApi::GetStringFromProp(pVal, fext);
      MAPI_TRACE2("\t\t\t--- File name: %s, extension: %s\r\n",
        fname.get(), fext.get());

      if (fext.IsEmpty()) {
        int idx = fname.RFindChar(L'.');
        if (idx != -1)
          fext = Substring(fname, idx);
      }
      else if (fname.RFindChar(L'.') == -1) {
        fname += L".";
        fname += fext;
      }
      if (fname.IsEmpty()) {
        // If no description use "Attachment i" format.
        fname = L"Attachment ";
        fname.AppendInt(static_cast<uint32_t>(aNum));
      }
      data->real_name = ToNewUTF8String(fname);

      nsCString tmp;
       // We have converted it to the rfc822 document
      if (aMethod == ATTACH_EMBEDDED_MSG) {
        data->type = NS_strdup(MESSAGE_RFC822);
      } else {
        pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_MIME_TAG_A);
        CMapiApi::GetStringFromProp(pVal, tmp);
        MAPI_TRACE1("\t\t\t--- Mime type: %s\r\n", tmp.get());
        if (tmp.IsEmpty()) {
          uint8_t *pType = NULL;
          if (!fext.IsEmpty()) {
            pType = CMimeTypes::GetMimeType(fext);
          }
          if (pType)
            data->type = NS_strdup((PC_S8)pType);
          else
            data->type = NS_strdup(APPLICATION_OCTET_STREAM);
        }
        else
          data->type = ToNewCString(tmp);
      }

      pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_CONTENT_ID_A);
      CMapiApi::GetStringFromProp(pVal, tmp);
      if (!tmp.IsEmpty())
        data->cid = ToNewCString(tmp);
    }
    if (bResult) {
      // Now we need to decide if this attachment is embedded or not.
      // At first, I tried to simply check for the presence of the Content-Id.
      // But it turned out that this method is unreliable, since there exist cases
      // when an attachment has a Content-Id while isn't embedded (even in a message
      // with a plain-text body!). So next I tried to look for <img> tags that contain
      // the found Content-Id. But this is unreliable, too, because there exist cases
      // where other places of HTML reference the embedded messages (e.g. it may be
      // a background of a table cell, or some CSS; further, it is possible that the
      // reference to an embedded object is not in the main body, but in another
      // embedded object - like body references a CSS attachment that in turn references
      // a picture as a background of its element). From the other hand, it's unreliable
      // to relax the search criteria to any occurence of the Content-Id string in the body -
      // partly because the string may be simply in a text or other non-referencing part,
      // partly because of the abovementioned possibility that the reference is outside
      // the body at all.
      // There exist the PR_ATTACH_FLAGS property of the attachment. The MS documentation
      // tells about two possible flags in it: ATT_INVISIBLE_IN_HTML and ATT_INVISIBLE_IN_RTF.
      // There is at least one more undocumented flag: ATT_MHTML_REF. Some sources in Internet
      // suggest simply check for the latter flag to distinguish between the embedded
      // and ordinary attachments. But my observations indicate that even if the flags
      // don't include ATT_MHTML_REF, the attachment is still may be embedded.
      // However, my observations always show that the message is embedded if the flags
      // is not 0.
      // So now I will simply test for the non-zero flags to decide whether the attachment
      // is embedded or not. Possible advantage is reliability (I hope).
      // Another advantage is that it's much faster than search the body for Content-Id.

      DWORD flags = 0;

      pVal = CMapiApi::GetMapiProperty(lpAttach, PR_ATTACH_FLAGS);
      if (pVal)
        flags = CMapiApi::GetLongFromProp(pVal);
      if (m_bodyIsHtml && data->cid && (flags != 0)) // this is the embedded attachment
        m_embattachments.push_back(data);
      else // this is ordinary attachment
        m_stdattachments.push_back(data);
    }
    else {
      delete data;
    }
  }

  lpAttach->Release();
  return bResult;
}
Пример #6
0
//-------------------------------------------------------------------------
//
// Show - Display the file dialog
//
//-------------------------------------------------------------------------
NS_IMETHODIMP nsFilePicker::Show(PRInt16 *aReturnVal)
{
    PRInt32 flags = 0;
    char *btn1;

    NS_ENSURE_ARG_POINTER(aReturnVal);

    if (mMode == modeGetFolder) {
        flags |= Pt_FSR_SELECT_DIRS|Pt_FSR_NO_SELECT_FILES;
        btn1 = "&Select";
    }
    else if (mMode == modeOpen) {
        btn1 = "&Open";
    }
    else if (mMode == modeSave) {
        flags |= Pt_FSR_NO_FCHECK;
        btn1 = "&Save";
    }
    else if( mMode == modeOpenMultiple ) {
        flags |= Pt_FSR_MULTIPLE;
        btn1 = "&Select";
    }
    else {
        printf("nsFilePicker::Show() wrong mode");
        return PR_FALSE;
    }

    char *title = ToNewUTF8String( mTitle );

    nsCAutoString initialDir;
    if (mDisplayDirectory)
        mDisplayDirectory->GetNativePath(initialDir);
    // If no display directory, re-use the last one.
    if(initialDir.IsEmpty()) {
        // Allocate copy of last used dir.
        initialDir = mLastUsedDirectory;
    }

    if( !mDefault.IsEmpty() ) {
        initialDir.AppendWithConversion( NS_LITERAL_STRING( "/" ) );
        initialDir.AppendWithConversion( mDefault );
    }

    char extensionBuffer[MAX_EXTENSION_LENGTH+1] = "*";
    if( !mFilterList.IsEmpty() ) {
        char *text = ToNewUTF8String( mFilterList );
        if( text ) {
            extensionBuffer[0] = 0;

            /* eliminate the ';' and the duplicates */
            char buffer[MAX_EXTENSION_LENGTH+1], buf[MAX_EXTENSION_LENGTH+1], *q, *delims = "; ", *dummy;
            strcpy( buffer, text );
            q = strtok_r( buffer, delims, &dummy );
            while( q ) {
                sprintf( buf, "%s ", q );
                if( !strstr( extensionBuffer, buf ) )
                    strcat( extensionBuffer, buf );
                q = strtok_r( NULL, delims, &dummy );
            }

            nsMemory::Free( text );
        }
    }
    else if (!mDefaultExtension.IsEmpty()) {
        // Someone was cool and told us what to do
        char *convertedExt = ToNewUTF8String( mDefaultExtension );
        if (!convertedExt) {
            mDefaultExtension.ToCString(extensionBuffer, MAX_EXTENSION_LENGTH);
        }
        else {
            PL_strncpyz(extensionBuffer, convertedExt, MAX_EXTENSION_LENGTH+1);
            nsMemory::Free( convertedExt );
        }
    }

    PtFileSelectionInfo_t info;
    memset( &info, 0, sizeof( info ) );

    if( PtFileSelection( mParentWidget, NULL, title, initialDir.get(),
                         extensionBuffer, btn1, "&Cancel", "nsd", &info, flags ) ) {
        if (title) nsMemory::Free( title );
        return NS_ERROR_FAILURE;
    }

    *aReturnVal = returnOK;

    if( info.ret == Pt_FSDIALOG_BTN2 ) {
        *aReturnVal = returnCancel;
    }
    else if( mMode != modeOpenMultiple ) {
        mFile.SetLength(0);
        mFile.Append( info.path );

        if( mMode == modeSave ) {
            nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1"));
            NS_ENSURE_TRUE(file, NS_ERROR_FAILURE);

            file->InitWithNativePath( mFile );

            PRBool exists = PR_FALSE;
            file->Exists(&exists);
            if (exists)
                *aReturnVal = returnReplace;
        }
    }
    else { /* here mMode is modeOpenMultiple */
        PtFileSelectorInfo_t *minfo = info.minfo;
        if( minfo ) {
            nsresult rv = NS_NewISupportsArray(getter_AddRefs(mFiles));
            NS_ENSURE_SUCCESS(rv,rv);

            for( int i=0; i<minfo->nitems; i++ ) {
                nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
                NS_ENSURE_SUCCESS(rv,rv);

                nsCString s ( minfo->multipath[i] );
                rv = file->InitWithNativePath( s );
                NS_ENSURE_SUCCESS(rv,rv);

                rv = mFiles->AppendElement(file);
                NS_ENSURE_SUCCESS(rv,rv);
            }

            PtFSFreeInfo( &info ); /* clean the info structure if the multiple mode is set */
        }
    }

    PL_strncpyz( mLastUsedDirectory, info.path, PATH_MAX+1 );
    if (!mDisplayDirectory)
        mDisplayDirectory = do_CreateInstance("@mozilla.org/file/local;1");
    if (mDisplayDirectory)
        mDisplayDirectory->InitWithNativePath( nsDependentCString(mLastUsedDirectory) );

    if( title ) nsMemory::Free( title );

    return NS_OK;

// TODO: implement filters
}
Пример #7
0
static int MimeInlineText_initializeCharset(MimeObject *obj)
{
  MimeInlineText  *text = (MimeInlineText *) obj;

  text->inputAutodetect = false;
  text->charsetOverridable = false;
  
  /* Figure out an appropriate charset for this object.
  */
  if (!text->charset && obj->headers)
  {
    if (obj->options && obj->options->override_charset)
    {
      text->charset = strdup(obj->options->default_charset);
    }
    else
    {
      char *ct = MimeHeaders_get (obj->headers, HEADER_CONTENT_TYPE,
                                  false, false);
      if (ct)
      {
        text->charset = MimeHeaders_get_parameter (ct, "charset", NULL, NULL);
        PR_Free(ct);
      }
    
      if (!text->charset)
      {
        /* If we didn't find "Content-Type: ...; charset=XX" then look
           for "X-Sun-Charset: XX" instead.  (Maybe this should be done
           in MimeSunAttachmentClass, but it's harder there than here.)
         */
        text->charset = MimeHeaders_get (obj->headers,
                                          HEADER_X_SUN_CHARSET,
                                          false, false);
      }

      /* iMIP entities without an explicit charset parameter default to
       US-ASCII (RFC 2447, section 2.4). However, Microsoft Outlook generates
       UTF-8 but omits the charset parameter.
       When no charset is defined by the container (e.g. iMIP), iCalendar
       files default to UTF-8 (RFC 2445, section 4.1.4).
       */
      if (!text->charset &&
          obj->content_type &&
          !PL_strcasecmp(obj->content_type, TEXT_CALENDAR))
        text->charset = strdup("UTF-8");

      if (!text->charset)
      {
        nsresult res;
        
        text->charsetOverridable = true;

        nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &res)); 
        if (NS_SUCCEEDED(res))
        {
          nsCOMPtr<nsIPrefLocalizedString> str;
          if (NS_SUCCEEDED(prefBranch->GetComplexValue("intl.charset.detector", NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(str)))) {
            //only if we can get autodetector name correctly, do we set this to true
            text->inputAutodetect = true;
          }
        }
        
        if (obj->options && obj->options->default_charset)
          text->charset = strdup(obj->options->default_charset);
        else
        {
          if (NS_SUCCEEDED(res))
          {
            nsString value;
            NS_GetLocalizedUnicharPreferenceWithDefault(prefBranch, "mailnews.view_default_charset", EmptyString(), value);
            text->charset = ToNewUTF8String(value);
          }
          else
            text->charset = strdup("");
        }
      } 
    }
  }
  
  if (text->inputAutodetect)
  {
    //we need to prepare lineDam for charset detection
    text->lineDamBuffer = (char*)PR_Malloc(DAM_MAX_BUFFER_SIZE);
    text->lineDamPtrs = (char**)PR_Malloc(DAM_MAX_LINES*sizeof(char*));
    text->curDamOffset = 0;
    text->lastLineInDam = 0;
    if (!text->lineDamBuffer || !text->lineDamPtrs)
    {
      text->inputAutodetect = false;
      PR_FREEIF(text->lineDamBuffer);
      PR_FREEIF(text->lineDamPtrs);
    }
  }

  text->initializeCharset = true;

  return 0;
}
Пример #8
0
void
nsClipboard::SelectionGetEvent (GtkWidget        *aWidget,
                                GtkSelectionData *aSelectionData,
                                guint             aTime)
{
    // Someone has asked us to hand them something.  The first thing
    // that we want to do is see if that something includes text.  If
    // it does, try to give it text/unicode after converting it to
    // utf-8.

    PRInt32 whichClipboard;

    // which clipboard?
    if (aSelectionData->selection == GDK_SELECTION_PRIMARY)
        whichClipboard = kSelectionClipboard;
    else if (aSelectionData->selection == GDK_SELECTION_CLIPBOARD)
        whichClipboard = kGlobalClipboard;
    else
        return; // THAT AINT NO CLIPBOARD I EVER HEARD OF

    nsCOMPtr<nsITransferable> trans = GetTransferable(whichClipboard);

    nsresult rv;
    nsCOMPtr<nsISupports> item;
    PRUint32 len;

    // Check to see if the selection data includes any of the string
    // types that we support.
    if (aSelectionData->target == gdk_atom_intern ("STRING", FALSE) ||
            aSelectionData->target == gdk_atom_intern ("TEXT", FALSE) ||
            aSelectionData->target == gdk_atom_intern ("COMPOUND_TEXT", FALSE) ||
            aSelectionData->target == gdk_atom_intern ("UTF8_STRING", FALSE)) {
        // Try to convert our internal type into a text string.  Get
        // the transferable for this clipboard and try to get the
        // text/unicode type for it.
        rv = trans->GetTransferData("text/unicode", getter_AddRefs(item),
                                    &len);
        if (!item || NS_FAILED(rv))
            return;

        nsCOMPtr<nsISupportsString> wideString;
        wideString = do_QueryInterface(item);
        if (!wideString)
            return;

        nsAutoString ucs2string;
        wideString->GetData(ucs2string);
        char *utf8string = ToNewUTF8String(ucs2string);
        if (!utf8string)
            return;

        gtk_selection_data_set_text (aSelectionData, utf8string,
                                     strlen(utf8string));

        nsMemory::Free(utf8string);
        return;
    }

    // Try to match up the selection data target to something our
    // transferable provides.
    gchar *target_name = gdk_atom_name(aSelectionData->target);
    if (!target_name)
        return;

    rv = trans->GetTransferData(target_name, getter_AddRefs(item), &len);
    // nothing found?
    if (!item || NS_FAILED(rv)) {
        g_free(target_name);
        return;
    }

    void *primitive_data = nsnull;
    nsPrimitiveHelpers::CreateDataFromPrimitive(target_name, item,
            &primitive_data, len);

    if (primitive_data) {
        // Check to see if the selection data is text/html
        if (aSelectionData->target == gdk_atom_intern (kHTMLMime, FALSE)) {
            /*
             * "text/html" can be encoded UCS2. It is recommended that
             * documents transmitted as UCS2 always begin with a ZERO-WIDTH
             * NON-BREAKING SPACE character (hexadecimal FEFF, also called
             * Byte Order Mark (BOM)). Adding BOM can help other app to
             * detect mozilla use UCS2 encoding when copy-paste.
             */
            guchar *buffer = (guchar *)
                             nsMemory::Alloc((len * sizeof(guchar)) + sizeof(PRUnichar));
            if (!buffer)
                return;
            PRUnichar prefix = 0xFEFF;
            memcpy(buffer, &prefix, sizeof(prefix));
            memcpy(buffer + sizeof(prefix), primitive_data, len);
            nsMemory::Free((guchar *)primitive_data);
            primitive_data = (guchar *)buffer;
            len += sizeof(prefix);
        }

        gtk_selection_data_set(aSelectionData, aSelectionData->target,
                               8, /* 8 bits in a unit */
                               (const guchar *)primitive_data, len);
        nsMemory::Free(primitive_data);
    }

    g_free(target_name);

}
Пример #9
0
}

/* dpoIKernel compileKernel (in AString source, in AString kernelName, [optional] in AString options); */
NS_IMETHODIMP dpoCContext::CompileKernel(const nsAString & source, const nsAString & kernelName, const nsAString & options, dpoIKernel **_retval NS_OUTPARAM)
{
	cl_program program;
	cl_kernel kernel;
	cl_int err_code;
	cl_uint numDevices;
	cl_device_id *devices = NULL;
	size_t actual;
	char *sourceStr, *optionsStr, *kernelNameStr;
	nsCOMPtr<dpoCKernel> ret;
	nsresult result;

	sourceStr = ToNewUTF8String(source);
	DEBUG_LOG_STATUS("CompileKernel", "Source: " << sourceStr);
	program = clCreateProgramWithSource(context, 1, (const char**)&sourceStr, NULL, &err_code);
	nsMemory::Free(sourceStr);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code);
		return NS_ERROR_ILLEGAL_VALUE;
	}

	optionsStr = ToNewUTF8String(options);
	err_code = clBuildProgram(program, 0, NULL, optionsStr, NULL, NULL);
	nsMemory::Free(optionsStr);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code);

		if (buildLog == NULL) {
Пример #10
0
/* [noscript] long init (in AString query); */
NS_IMETHODIMP jxMySQL50Statement::Init(const nsAString & query, PRInt32 *_retval)
{
    nsresult rv = NS_OK;

	if (mConnection == nsnull)
    {
        SET_ERROR_RETURN (JX_MYSQL50_ERROR_NOT_CONNECTED);
    }

    if (mSTMT != nsnull)
    {
        SET_ERROR_RETURN (JX_MYSQL50_ERROR_STMT_ALREADY_INITIALIZED);
    }

	MYSQL * mysql;
	mConnection->GetMysql(&mysql);

	// Create a new statement handle
	if ((mSTMT = mysql_stmt_init(mysql))) 
	{
		// Get the query string
		char * stmt = ToNewUTF8String(query);

		// Prepare the statement
        int ret = mysql_stmt_prepare(mSTMT, stmt, query.Length());
        nsMemory::Free(stmt);
			
		if (ret) 
		{
			// Statement prep failed
#if 0
            char err[512];
            sprintf(err, " %s", mysql_stmt_error(mSTMT));
#endif
            *_retval = ret;
            SET_ERROR_RETURN (JX_MYSQL50_MYSQL_ERROR);
		}
		else 
		{
			mIn.mCount = mysql_stmt_param_count(mSTMT);
			mOut.mCount = mysql_stmt_field_count(mSTMT);

			// Statement prep succeeded
            *_retval = 0;

            // Allocated the BIND array and supporting structures
	        if (mIn.mBIND == nsnull && mIn.mCount > 0) { 
		        rv = mIn.Allocate();
		        if (rv != NS_OK)
                {
                    *_retval = -1;
                    SET_ERROR_RETURN (rv);
                }
            }	    
		}
	}
	else {
		// Statement prep failed
		*_retval = -1;
        SET_ERROR_RETURN (JX_MYSQL50_MYSQL_ERROR);
	}

    return NS_OK;
}
Пример #11
0
void
nsClipboard::SelectionGetEvent(GtkClipboard     *aClipboard,
                               GtkSelectionData *aSelectionData)
{
    // Someone has asked us to hand them something.  The first thing
    // that we want to do is see if that something includes text.  If
    // it does, try to give it text/unicode after converting it to
    // utf-8.

    PRInt32 whichClipboard;

    // which clipboard?
    if (aSelectionData->selection == GDK_SELECTION_PRIMARY)
        whichClipboard = kSelectionClipboard;
    else if (aSelectionData->selection == GDK_SELECTION_CLIPBOARD)
        whichClipboard = kGlobalClipboard;
    else
        return; // THAT AIN'T NO CLIPBOARD I EVER HEARD OF

    nsCOMPtr<nsITransferable> trans = GetTransferable(whichClipboard);
    if (!trans) {
      // We have nothing to serve
#ifdef DEBUG_CLIPBOARD
      printf("nsClipboard::SelectionGetEvent() - %s clipboard is empty!\n",
             whichClipboard == kSelectionClipboard ? "Selection" : "Global");
#endif
      return;
    }

    nsresult rv;
    nsCOMPtr<nsISupports> item;
    PRUint32 len;

    // Check to see if the selection data includes any of the string
    // types that we support.
    if (aSelectionData->target == gdk_atom_intern ("STRING", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("TEXT", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("COMPOUND_TEXT", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("UTF8_STRING", FALSE)) {
        // Try to convert our internal type into a text string.  Get
        // the transferable for this clipboard and try to get the
        // text/unicode type for it.
        rv = trans->GetTransferData("text/unicode", getter_AddRefs(item),
                                    &len);
        if (!item || NS_FAILED(rv))
            return;
        
        nsCOMPtr<nsISupportsString> wideString;
        wideString = do_QueryInterface(item);
        if (!wideString)
            return;

        nsAutoString ucs2string;
        wideString->GetData(ucs2string);
        char *utf8string = ToNewUTF8String(ucs2string);
        if (!utf8string)
            return;
        
        gtk_selection_data_set_text (aSelectionData, utf8string,
                                     strlen(utf8string));

        nsMemory::Free(utf8string);
        return;
    }

    // Check to see if the selection data is an image type
    if (gtk_targets_include_image(&aSelectionData->target, 1, TRUE)) {
        // Look through our transfer data for the image
        static const char* const imageMimeTypes[] = {
            kNativeImageMime, kPNGImageMime, kJPEGImageMime, kGIFImageMime };
        nsCOMPtr<nsISupports> item;
        PRUint32 len;
        nsCOMPtr<nsISupportsInterfacePointer> ptrPrimitive;
        for (PRUint32 i = 0; !ptrPrimitive && i < NS_ARRAY_LENGTH(imageMimeTypes); i++) {
            rv = trans->GetTransferData(imageMimeTypes[i], getter_AddRefs(item), &len);
            ptrPrimitive = do_QueryInterface(item);
        }
        if (!ptrPrimitive)
            return;

        nsCOMPtr<nsISupports> primitiveData;
        ptrPrimitive->GetData(getter_AddRefs(primitiveData));
        nsCOMPtr<imgIContainer> image(do_QueryInterface(primitiveData));
        if (!image) // Not getting an image for an image mime type!?
            return;

        GdkPixbuf* pixbuf = nsImageToPixbuf::ImageToPixbuf(image);
        if (!pixbuf)
            return;

        gtk_selection_data_set_pixbuf(aSelectionData, pixbuf);
        g_object_unref(pixbuf);
        return;
    }

    // Try to match up the selection data target to something our
    // transferable provides.
    gchar *target_name = gdk_atom_name(aSelectionData->target);
    if (!target_name)
        return;

    rv = trans->GetTransferData(target_name, getter_AddRefs(item), &len);
    // nothing found?
    if (!item || NS_FAILED(rv)) {
        g_free(target_name);
        return;
    }

    void *primitive_data = nsnull;
    nsPrimitiveHelpers::CreateDataFromPrimitive(target_name, item,
                                                &primitive_data, len);

    if (primitive_data) {
        // Check to see if the selection data is text/html
        if (aSelectionData->target == gdk_atom_intern (kHTMLMime, FALSE)) {
            /*
             * "text/html" can be encoded UCS2. It is recommended that
             * documents transmitted as UCS2 always begin with a ZERO-WIDTH
             * NON-BREAKING SPACE character (hexadecimal FEFF, also called
             * Byte Order Mark (BOM)). Adding BOM can help other app to
             * detect mozilla use UCS2 encoding when copy-paste.
             */
            guchar *buffer = (guchar *)
                    nsMemory::Alloc((len * sizeof(guchar)) + sizeof(PRUnichar));
            if (!buffer)
                return;
            PRUnichar prefix = 0xFEFF;
            memcpy(buffer, &prefix, sizeof(prefix));
            memcpy(buffer + sizeof(prefix), primitive_data, len);
            nsMemory::Free((guchar *)primitive_data);
            primitive_data = (guchar *)buffer;
            len += sizeof(prefix);
        }
  
        gtk_selection_data_set(aSelectionData, aSelectionData->target,
                               8, /* 8 bits in a unit */
                               (const guchar *)primitive_data, len);
        nsMemory::Free(primitive_data);
    }

    g_free(target_name);
                           
}
Пример #12
0
//-------------------------------------------------------------------------
//
// Show - Display the file dialog
//
//-------------------------------------------------------------------------
NS_IMETHODIMP nsFilePicker::Show(PRInt16 *retval)
{
	PRBool result = PR_TRUE;
	nsFilePanelBeOS *ppanel;
	file_panel_mode panel_mode;
	bool allow_multiple_selection = false;
	uint32 node_flavors;

	if (mMode == modeGetFolder) {
		node_flavors = B_DIRECTORY_NODE;
		panel_mode = B_OPEN_PANEL;
	}
	else if (mMode == modeOpen) {
		node_flavors = B_FILE_NODE;
		panel_mode = B_OPEN_PANEL;
	}
	else if (mMode == modeOpenMultiple) {
		node_flavors = B_FILE_NODE;
		panel_mode = B_OPEN_PANEL;
		allow_multiple_selection = true;
	}
	else if (mMode == modeSave) {
		node_flavors = B_FILE_NODE;
		panel_mode = B_SAVE_PANEL;
	}
	else {
		printf("nsFilePicker::Show() wrong mode");
		return PR_FALSE;
	}

	ppanel = new nsFilePanelBeOS(
	             panel_mode, //file_panel_mode mode
	             node_flavors,  //uint32 node_flavors
	             allow_multiple_selection,  //bool allow_multiple_selection
	             false, //bool modal
	             true //bool hide_when_done
	         );
	if (!ppanel) return PR_FALSE;

	// set title
	if (!mTitle.IsEmpty()) {
		char *title_utf8 = ToNewUTF8String(mTitle);
		ppanel->Window()->SetTitle(title_utf8);
		Recycle(title_utf8);
	}

	// set default text
	if (!mDefault.IsEmpty()) {
		char *defaultText = ToNewUTF8String(mDefault);
		ppanel->SetSaveText(defaultText);
		Recycle(defaultText);
	}

	// set initial directory
	nsCAutoString initialDir;
	if (mDisplayDirectory)
		mDisplayDirectory->GetNativePath(initialDir);
	if(initialDir.IsEmpty()) {
#ifdef FILEPICKER_SAVE_LAST_DIR		
		if (strlen(mLastUsedDirectory) < 2)
			initialDir.Assign("/boot/home");
		else
			initialDir.Assign(mLastUsedDirectory);
#else
		ppanel->SetPanelDirectory(initialDir.get());
#endif			
	}

#ifdef FILEPICKER_SAVE_LAST_DIR
	ppanel->SetPanelDirectory(initialDir.get());
#endif

	// set modal feel
	if (ppanel->LockLooper()) {
		ppanel->Window()->SetFeel(B_MODAL_APP_WINDOW_FEEL);
		ppanel->UnlockLooper();
	}

	// Show File Panel
	ppanel->Show();
	ppanel->WaitForSelection();

	if (ppanel->IsCancelSelected()) {
		result = PR_FALSE;
	}

	if ((mMode == modeOpen || mMode == modeOpenMultiple || mMode == modeGetFolder) && ppanel->IsOpenSelected()) {
		BList *list = ppanel->OpenRefs();
		uint32 numfiles = list->CountItems();
		if ((list) && numfiles >= 1) {
			nsresult rv = NS_NewISupportsArray(getter_AddRefs(mFiles));
			for (uint32 i = 0; i< numfiles; i++) {
				BPath *path = (BPath *)list->ItemAt(i);

				if (path->InitCheck() == B_OK) {
					mFile.Truncate();
					// Single and Multiple are exclusive now, though, maybe there is sense
					// to assign also first list element to mFile even in openMultiple case ?
					if (mMode == modeOpenMultiple) {
						nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
						NS_ENSURE_SUCCESS(rv,rv);
						rv = file->InitWithNativePath(nsDependentCString(path->Path()));
						NS_ENSURE_SUCCESS(rv,rv);
						rv = mFiles->AppendElement(file);
						NS_ENSURE_SUCCESS(rv,rv);
					} else {
						if (i == 0) mFile.Assign(path->Path());
					}
				} else {
					printf("path.init failed \n");
				}
			}
		} else {
			printf("list not init \n");
		}
	}
	else if (mMode == modeSave && ppanel->IsSaveSelected()) {
		BString savefilename = ppanel->SaveFileName();
		entry_ref ref = ppanel->SaveDirRef();
		BPath path(&ref);
		if (path.InitCheck() == B_OK) {
			path.Append(savefilename.String(), true);
			mFile.Assign(path.Path());
		}
	}
	else {
		result = PR_FALSE;
	}

	// set current directory to mDisplayDirectory
	entry_ref dir_ref;
	ppanel->GetPanelDirectory(&dir_ref);
	BEntry dir_entry(&dir_ref);
	BPath dir_path;
	dir_entry.GetPath(&dir_path);
	if (!mDisplayDirectory)
		mDisplayDirectory = do_CreateInstance("@mozilla.org/file/local;1");
	if (mDisplayDirectory)
		mDisplayDirectory->InitWithNativePath(nsDependentCString(dir_path.Path()));

	if (ppanel->Lock()) {
		ppanel->Quit();
	}

	if (result) {
		PRInt16 returnOKorReplace = returnOK;

#ifdef FILEPICKER_SAVE_LAST_DIR
		strncpy(mLastUsedDirectory, dir_path.Path(), B_PATH_NAME_LENGTH+1);
		if (mDisplayDirectory)
			mDisplayDirectory->InitWithNativePath( nsDependentCString(mLastUsedDirectory) );
#endif

		if (mMode == modeSave) {
			//   we must check if file already exists
			PRBool exists = PR_FALSE;
			nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1"));
			NS_ENSURE_TRUE(file, NS_ERROR_FAILURE);

			file->InitWithNativePath(mFile);
			file->Exists(&exists);
			if (exists)
				returnOKorReplace = returnReplace;
		}
		*retval = returnOKorReplace;
	}
	else {
		*retval = returnCancel;
	}
	return NS_OK;

	// TODO: implement filters
}
Пример #13
0
NS_IMETHODIMP nsColorPicker::Open(nsIColorPickerShownCallback *aColorPickerShownCallback)
{

  // Input color string should be 7 length (i.e. a string representing a valid
  // simple color)
  if (mInitialColor.Length() != 7) {
    return NS_ERROR_FAILURE;
  }

  const nsAString& withoutHash  = StringTail(mInitialColor, 6);
  nscolor color;
  if (!NS_HexToRGBA(withoutHash, nsHexColorType::NoAlpha, &color)) {
    return NS_ERROR_FAILURE;
  }

  if (mCallback) {
    // It means Open has already been called: this is not allowed
    NS_WARNING("mCallback is already set. Open called twice?");
    return NS_ERROR_FAILURE;
  }
  mCallback = aColorPickerShownCallback;

  nsXPIDLCString title;
  title.Adopt(ToNewUTF8String(mTitle));
  GtkWindow *parent_window = GTK_WINDOW(mParentWidget->GetNativeData(NS_NATIVE_SHELLWIDGET));
  
#if defined(ACTIVATE_GTK3_COLOR_PICKER) && GTK_CHECK_VERSION(3,4,0)
  GtkWidget* color_chooser = gtk_color_chooser_dialog_new(title, parent_window);
    
  if (parent_window) {
      gtk_window_set_destroy_with_parent(GTK_WINDOW(color_chooser), TRUE);
  }
  
  gtk_color_chooser_set_use_alpha(GTK_COLOR_CHOOSER(color_chooser), FALSE);
  GdkRGBA color_rgba = convertToRgbaColor(color);    
  gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(color_chooser),
                             &color_rgba);
  
  g_signal_connect(GTK_COLOR_CHOOSER(color_chooser), "color-activated",
                   G_CALLBACK(OnColorChanged), this);
#else
  GtkWidget *color_chooser = gtk_color_selection_dialog_new(title);
  
  if (parent_window) {
    GtkWindow *window = GTK_WINDOW(color_chooser);
    gtk_window_set_transient_for(window, parent_window);
    gtk_window_set_destroy_with_parent(window, TRUE);
  }

  GdkColor color_gdk = convertToGdkColor(color);
  gtk_color_selection_set_current_color(WidgetGetColorSelection(color_chooser),
                                        &color_gdk);
  
  g_signal_connect(WidgetGetColorSelection(color_chooser), "color-changed",
                   G_CALLBACK(OnColorChanged), this);
#endif

  NS_ADDREF_THIS();
  
  g_signal_connect(color_chooser, "response", G_CALLBACK(OnResponse), this);
  g_signal_connect(color_chooser, "destroy", G_CALLBACK(OnDestroy), this);
  gtk_widget_show(color_chooser);

  return NS_OK;
}
Пример #14
0
char* PR_CALLBACK
PK11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg) {
  nsNSSShutDownPreventionLock locker;
  nsresult rv = NS_OK;
  PRUnichar *password = nsnull;
  PRBool value = PR_FALSE;
  nsIInterfaceRequestor *ir = static_cast<nsIInterfaceRequestor*>(arg);
  nsCOMPtr<nsIPrompt> proxyPrompt;

  /* TODO: Retry should generate a different dialog message */
/*
  if (retry)
    return nsnull;
*/

  if (!ir)
  {
    nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
    if (!wwatch)
      return nsnull;

    nsCOMPtr<nsIPrompt> prompter;
    wwatch->GetNewPrompter(0, getter_AddRefs(prompter));
    if (!prompter)
      return nsnull;

    NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                         NS_GET_IID(nsIPrompt),
                         prompter, NS_PROXY_SYNC,
                         getter_AddRefs(proxyPrompt));
    if (!proxyPrompt)
      return nsnull;
  }
  else
  {
    // The interface requestor object may not be safe, so
    // proxy the call to get the nsIPrompt.
  
    nsCOMPtr<nsIInterfaceRequestor> proxiedCallbacks;
    NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                         NS_GET_IID(nsIInterfaceRequestor),
                         ir,
                         NS_PROXY_SYNC,
                         getter_AddRefs(proxiedCallbacks));
  
    // Get the desired interface
    nsCOMPtr<nsIPrompt> prompt(do_GetInterface(proxiedCallbacks));
    if (!prompt) {
      NS_ASSERTION(PR_FALSE, "callbacks does not implement nsIPrompt");
      return nsnull;
    }
  
    // Finally, get a proxy for the nsIPrompt
    NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                         NS_GET_IID(nsIPrompt),
                         prompt,
                         NS_PROXY_SYNC,
                         getter_AddRefs(proxyPrompt));
  }

  if (PK11_ProtectedAuthenticationPath(slot))
    return ShowProtectedAuthPrompt(slot, ir);

  nsAutoString promptString;
  nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));

  if (NS_FAILED(rv))
    return nsnull; 

  const PRUnichar* formatStrings[1] = { ToNewUnicode(NS_ConvertUTF8toUTF16(PK11_GetTokenName(slot))) };
  rv = nssComponent->PIPBundleFormatStringFromName("CertPassPrompt",
                                      formatStrings, 1,
                                      promptString);
  nsMemory::Free(const_cast<PRUnichar*>(formatStrings[0]));

  if (NS_FAILED(rv))
    return nsnull;

  {
    nsPSMUITracker tracker;
    if (tracker.isUIForbidden()) {
      rv = NS_ERROR_NOT_AVAILABLE;
    }
    else {
      rv = proxyPrompt->PromptPassword(nsnull, promptString.get(),
                                       &password, nsnull, nsnull, &value);
    }
  }
  
  if (NS_SUCCEEDED(rv) && value) {
    char* str = ToNewUTF8String(nsDependentString(password));
    NS_Free(password);
    return str;
  }

  return nsnull;
}
Пример #15
0
NS_IMETHODIMP
nsFilePicker::Show(PRInt16 *aReturn)
{
  NS_ENSURE_ARG_POINTER(aReturn);

  nsXPIDLCString title;
  title.Adopt(ToNewUTF8String(mTitle));

  GtkWindow *parent_widget = get_gtk_window_for_nsiwidget(mParentWidget);

  GtkFileChooserAction action = GetGtkFileChooserAction(mMode);
  const gchar *accept_button = (mMode == GTK_FILE_CHOOSER_ACTION_SAVE)
                               ? GTK_STOCK_SAVE : GTK_STOCK_OPEN;
  GtkWidget *file_chooser =
      _gtk_file_chooser_dialog_new(title, parent_widget, action,
                                   GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                   accept_button, GTK_RESPONSE_ACCEPT,
                                   NULL);
  if (mAllowURLs) {
    _gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(file_chooser), FALSE);
  }

  if (mMode == GTK_FILE_CHOOSER_ACTION_OPEN || mMode == GTK_FILE_CHOOSER_ACTION_SAVE) {
    GtkWidget *img_preview = _gtk_image_new();
    _gtk_file_chooser_set_preview_widget(GTK_FILE_CHOOSER(file_chooser), img_preview);
    g_signal_connect(file_chooser, "update-preview", G_CALLBACK(UpdateFilePreviewWidget), img_preview);
  }

  if (parent_widget && parent_widget->group) {
    gtk_window_group_add_window(parent_widget->group, GTK_WINDOW(file_chooser));
  }

  if (mMode == nsIFilePicker::modeOpenMultiple) {
    _gtk_file_chooser_set_select_multiple (GTK_FILE_CHOOSER(file_chooser), TRUE);
  } else if (mMode == nsIFilePicker::modeSave) {
    char *default_filename = ToNewUTF8String(mDefault);
    _gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser),
                                       static_cast<const gchar*>(default_filename));
    nsMemory::Free(default_filename);
  }

  gtk_dialog_set_default_response(GTK_DIALOG(file_chooser), GTK_RESPONSE_ACCEPT);

  nsCAutoString directory;
  if (mDisplayDirectory) {
    mDisplayDirectory->GetNativePath(directory);
  } else if (mPrevDisplayDirectory) {
    mPrevDisplayDirectory->GetNativePath(directory);
  }

  if (!directory.IsEmpty()) {
    _gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(file_chooser),
                                         directory.get());
  }

  PRInt32 count = mFilters.Count();
  for (PRInt32 i = 0; i < count; ++i) {
    // This is fun... the GTK file picker does not accept a list of filters
    // so we need to split out each string, and add it manually.

    char **patterns = g_strsplit(mFilters[i]->get(), ";", -1);
    if (!patterns) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    GtkFileFilter *filter = _gtk_file_filter_new ();
    for (int j = 0; patterns[j] != NULL; ++j) {
      _gtk_file_filter_add_pattern (filter, g_strstrip (patterns[j]));
    }

    g_strfreev(patterns);

    if (!mFilterNames[i]->IsEmpty()) {
      // If we have a name for our filter, let's use that.
      const char *filter_name = mFilterNames[i]->get();
      _gtk_file_filter_set_name (filter, filter_name);
    } else {
      // If we don't have a name, let's just use the filter pattern.
      const char *filter_pattern = mFilters[i]->get();
      _gtk_file_filter_set_name (filter, filter_pattern);
    }

    _gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (file_chooser), filter);

    // Set the initially selected filter
    if (mSelectedType == i) {
      _gtk_file_chooser_set_filter (GTK_FILE_CHOOSER(file_chooser), filter);
    }
  }

  PRBool checkForOverwrite = PR_TRUE;
  if (_gtk_file_chooser_set_do_overwrite_confirmation) {
    checkForOverwrite = PR_FALSE;
    // Only available in GTK 2.8
    _gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(file_chooser), PR_TRUE);
  }

  gint response = RunDialog(GTK_DIALOG (file_chooser));

  switch (response) {
    case GTK_RESPONSE_ACCEPT:
    ReadValuesFromFileChooser(file_chooser);
    *aReturn = nsIFilePicker::returnOK;
    if (mMode == nsIFilePicker::modeSave) {
      nsCOMPtr<nsILocalFile> file;
      GetFile(getter_AddRefs(file));
      if (file) {
        PRBool exists = PR_FALSE;
        file->Exists(&exists);
        if (exists) {
          PRBool overwrite = !checkForOverwrite ||
            confirm_overwrite_file (file_chooser, file);

          if (overwrite) {
            *aReturn = nsIFilePicker::returnReplace;
          } else {
            *aReturn = nsIFilePicker::returnCancel;
          }
        }
      }
    }
    break;

    case GTK_RESPONSE_CANCEL:
    case GTK_RESPONSE_CLOSE:
    case GTK_RESPONSE_DELETE_EVENT:
    *aReturn = nsIFilePicker::returnCancel;
    break;

    default:
    NS_WARNING("Unexpected response");
    *aReturn = nsIFilePicker::returnCancel;
    break;
  }

  gtk_widget_destroy(file_chooser);

  return NS_OK;
}
static void TestSaveAsCharset()
{
  printf("==============================\n");
  printf("Start nsISaveAsCharset Test \n");
  printf("==============================\n");

  nsresult res;

  nsString inString;
  inString.Assign(NS_ConvertASCIItoUTF16("\x61\x62\x80\xA0\x63"));
  char *outString;
  
  const PRUnichar *data;
  uint32_t length = NS_StringGetData(inString, &data);

  // first, dump input string
  for (uint32_t i = 0; i < length; i++) {
    printf("%c ", data[i]);
  }
  printf("\n");

  nsCOMPtr <nsISaveAsCharset> saveAsCharset = do_CreateInstance(kSaveAsCharsetCID, &res);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  
  printf("ISO-8859-1 attr_plainTextDefault entityNone\n");
  res = saveAsCharset->Init("ISO-8859-1", 
                                 nsISaveAsCharset::attr_plainTextDefault, 
                                 nsIEntityConverter::entityNone);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  res = saveAsCharset->Convert(inString.get(), &outString);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  if (!outString) {printf("\tFailed!! output null\n");}
  else {printf("%s\n", outString); nsMemory::Free(outString);}

  printf("ISO-2022-JP attr_plainTextDefault entityNone\n");
  res = saveAsCharset->Init("ISO-2022-JP", 
                                 nsISaveAsCharset::attr_plainTextDefault,
                                 nsIEntityConverter::entityNone);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  res = saveAsCharset->Convert(inString.get(), &outString);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  if (!outString) {printf("\tFailed!! output null\n");}
  else {printf("%s\n", outString); nsMemory::Free(outString);}
  if (NS_ERROR_UENC_NOMAPPING == res) {
    outString = ToNewUTF8String(inString);
    if (!outString) {printf("\tFailed!! output null\n");}
    else {printf("Fall back to UTF-8: %s\n", outString); nsMemory::Free(outString);}
  }

  printf("ISO-2022-JP attr_FallbackQuestionMark entityNone\n");
  res = saveAsCharset->Init("ISO-2022-JP", 
                                 nsISaveAsCharset::attr_FallbackQuestionMark,
                                 nsIEntityConverter::entityNone);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  res = saveAsCharset->Convert(inString.get(), &outString);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  if (!outString) {printf("\tFailed!! output null\n");}
  else {printf("%s\n", outString); nsMemory::Free(outString);}

  printf("ISO-2022-JP attr_FallbackEscapeU entityNone\n");
  res = saveAsCharset->Init("ISO-2022-JP", 
                                 nsISaveAsCharset::attr_FallbackEscapeU,
                                 nsIEntityConverter::entityNone);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  res = saveAsCharset->Convert(inString.get(), &outString);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  if (!outString) {printf("\tFailed!! output null\n");}
  else {printf("%s\n", outString); nsMemory::Free(outString);}

  printf("ISO-8859-1 attr_htmlTextDefault html40Latin1\n");
  res = saveAsCharset->Init("ISO-8859-1", 
                                 nsISaveAsCharset::attr_htmlTextDefault, 
                                 nsIEntityConverter::html40Latin1);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  res = saveAsCharset->Convert(inString.get(), &outString);
  if (NS_ERROR_UENC_NOMAPPING != res && NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  if (!outString) {printf("\tFailed!! output null\n");}
  else {printf("%s\n", outString); nsMemory::Free(outString);}

  printf("ISO-8859-1 attr_FallbackHexNCR+attr_EntityAfterCharsetConv html40Latin1 \n");
  res = saveAsCharset->Init("ISO-8859-1", 
                                 nsISaveAsCharset::attr_FallbackHexNCR + 
                                 nsISaveAsCharset::attr_EntityAfterCharsetConv, 
                                 nsIEntityConverter::html40Latin1);
  if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  res = saveAsCharset->Convert(inString.get(), &outString);
  if (NS_ERROR_UENC_NOMAPPING != res && NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
  if (!outString) {printf("\tFailed!! output null\n");}
  else {printf("%s\n", outString); nsMemory::Free(outString);}


  printf("==============================\n");
  printf("Finish nsISaveAsCharset Test \n");
  printf("==============================\n\n");
}
Пример #17
0
nsresult nsMsgFilterList::LoadTextFilters(nsIInputStream *aStream)
{
  nsresult  err = NS_OK;
  uint64_t bytesAvailable;

  nsCOMPtr<nsIInputStream> bufStream;
  err = NS_NewBufferedInputStream(getter_AddRefs(bufStream), aStream, 10240);
  NS_ENSURE_SUCCESS(err, err);

  nsMsgFilterFileAttribValue attrib;
  nsCOMPtr<nsIMsgRuleAction> currentFilterAction;
  // We'd really like to move lot's of these into the objects that they refer to.
  do
  {
    nsAutoCString value;
    nsresult intToStringResult;

    char curChar;
    curChar = LoadAttrib(attrib, bufStream);
    if (curChar == (char) -1)  //reached eof
      break;
    err = LoadValue(value, bufStream);
    if (NS_FAILED(err))
      break;

    switch(attrib)
    {
    case nsIMsgFilterList::attribNone:
      if (m_curFilter)
        m_curFilter->SetUnparseable(true);
      break;
    case nsIMsgFilterList::attribVersion:
      m_fileVersion = value.ToInteger(&intToStringResult);
      if (NS_FAILED(intToStringResult))
      {
        attrib = nsIMsgFilterList::attribNone;
        NS_ASSERTION(false, "error parsing filter file version");
      }
      break;
    case nsIMsgFilterList::attribLogging:
      m_loggingEnabled = StrToBool(value);
      m_unparsedFilterBuffer.Truncate(); //we are going to buffer each filter as we read them, make sure no garbage is there
      m_startWritingToBuffer = true; //filters begin now
      break;
    case nsIMsgFilterList::attribName:  //every filter starts w/ a name
      {
        if (m_curFilter)
        {
          int32_t nextFilterStartPos = m_unparsedFilterBuffer.RFind("name");

          nsAutoCString nextFilterPart;
          nextFilterPart = Substring(m_unparsedFilterBuffer, nextFilterStartPos, m_unparsedFilterBuffer.Length());
          m_unparsedFilterBuffer.SetLength(nextFilterStartPos);

          bool unparseableFilter;
          m_curFilter->GetUnparseable(&unparseableFilter);
          if (unparseableFilter)
          {
            m_curFilter->SetUnparsedBuffer(m_unparsedFilterBuffer);
            m_curFilter->SetEnabled(false); //disable the filter because we don't know how to apply it
          }
          m_unparsedFilterBuffer = nextFilterPart;
        }
        nsMsgFilter *filter = new nsMsgFilter;
        if (filter == nullptr)
        {
          err = NS_ERROR_OUT_OF_MEMORY;
          break;
        }
        filter->SetFilterList(static_cast<nsIMsgFilterList*>(this));
        if (m_fileVersion == k45Version)
        {
          nsAutoString unicodeStr;
          err = nsMsgI18NConvertToUnicode(nsMsgI18NFileSystemCharset(),
                                          value, unicodeStr);
          if (NS_FAILED(err))
              break;

          filter->SetFilterName(unicodeStr);
        }
        else
        {
          // ### fix me - this is silly.
          PRUnichar *unicodeString =
            nsTextFormatter::smprintf(unicodeFormatter, value.get());
          filter->SetFilterName(nsDependentString(unicodeString));
          nsTextFormatter::smprintf_free(unicodeString);
        }
        m_curFilter = filter;
        m_filters.AppendElement(filter);
      }
      break;
    case nsIMsgFilterList::attribEnabled:
      if (m_curFilter)
        m_curFilter->SetEnabled(StrToBool(value));
      break;
    case nsIMsgFilterList::attribDescription:
      if (m_curFilter)
        m_curFilter->SetFilterDesc(value);
      break;
    case nsIMsgFilterList::attribType:
      if (m_curFilter)
      {
        // Older versions of filters didn't have the ability to turn on/off the
        // manual filter context, so default manual to be on in that case
        int32_t filterType = value.ToInteger(&intToStringResult);
        if (m_fileVersion < kManualContextVersion)
          filterType |= nsMsgFilterType::Manual;
        m_curFilter->SetType((nsMsgFilterTypeType) filterType);
      }
      break;
    case nsIMsgFilterList::attribScriptFile:
      if (m_curFilter)
        m_curFilter->SetFilterScript(&value);
      break;
    case nsIMsgFilterList::attribAction:
      if (m_curFilter)
      {
        nsMsgRuleActionType actionType = nsMsgFilter::GetActionForFilingStr(value);
        if (actionType == nsMsgFilterAction::None)
          m_curFilter->SetUnparseable(true);
        else
        {
          err = m_curFilter->CreateAction(getter_AddRefs(currentFilterAction));
          NS_ENSURE_SUCCESS(err, err);
          currentFilterAction->SetType(actionType);
          m_curFilter->AppendAction(currentFilterAction);
        }
      }
      break;
    case nsIMsgFilterList::attribActionValue:
      if (m_curFilter && currentFilterAction)
      {
        nsMsgRuleActionType type;
        currentFilterAction->GetType(&type);
        if (type == nsMsgFilterAction::MoveToFolder ||
              type == nsMsgFilterAction::CopyToFolder)
          err = m_curFilter->ConvertMoveOrCopyToFolderValue(currentFilterAction, value);
        else if (type == nsMsgFilterAction::ChangePriority)
        {
          nsMsgPriorityValue outPriority;
          nsresult res = NS_MsgGetPriorityFromString(value.get(), outPriority);
          if (NS_SUCCEEDED(res))
            currentFilterAction->SetPriority(outPriority);
          else
            NS_ASSERTION(false, "invalid priority in filter file");
        }
        else if (type == nsMsgFilterAction::Label)
        {
          // upgrade label to corresponding tag/keyword
          nsresult res;
          int32_t labelInt = value.ToInteger(&res);
          if (NS_SUCCEEDED(res))
          {
            nsAutoCString keyword("$label");
            keyword.Append('0' + labelInt);
            currentFilterAction->SetType(nsMsgFilterAction::AddTag);
            currentFilterAction->SetStrValue(keyword);
          }
        }
        else if (type == nsMsgFilterAction::JunkScore)
        {
          nsresult res;
          int32_t junkScore = value.ToInteger(&res);
          if (NS_SUCCEEDED(res))
            currentFilterAction->SetJunkScore(junkScore);
        }
        else if (type == nsMsgFilterAction::Forward ||
                 type == nsMsgFilterAction::Reply ||
                 type == nsMsgFilterAction::AddTag ||
                 type == nsMsgFilterAction::Custom)
        {
          currentFilterAction->SetStrValue(value);
        }
      }
      break;
    case nsIMsgFilterList::attribCondition:
      if (m_curFilter)
      {
        if (m_fileVersion == k45Version)
        {
          nsAutoString unicodeStr;
          err = nsMsgI18NConvertToUnicode(nsMsgI18NFileSystemCharset(),
                                          value, unicodeStr);
          if (NS_FAILED(err))
              break;

          char *utf8 = ToNewUTF8String(unicodeStr);
          value.Assign(utf8);
          nsMemory::Free(utf8);
        }
        err = ParseCondition(m_curFilter, value.get());
        if (err == NS_ERROR_INVALID_ARG)
          err = m_curFilter->SetUnparseable(true);
        NS_ENSURE_SUCCESS(err, err);
      }
      break;
    case nsIMsgFilterList::attribCustomId:
      if (m_curFilter && currentFilterAction)
      {
        err = currentFilterAction->SetCustomId(value);
        NS_ENSURE_SUCCESS(err, err);
      }
      break;

    }
  } while (NS_SUCCEEDED(bufStream->Available(&bytesAvailable)));

  if (m_curFilter)
  {
    bool unparseableFilter;
    m_curFilter->GetUnparseable(&unparseableFilter);
    if (unparseableFilter)
    {
      m_curFilter->SetUnparsedBuffer(m_unparsedFilterBuffer);
      m_curFilter->SetEnabled(false);  //disable the filter because we don't know how to apply it
    }
  }

  return err;
}
Пример #18
0
void
uGlobalMenuItem::SyncAccelFromContent()
{
  if (!mKeyContent) {
    dbusmenu_menuitem_property_remove(mDbusMenuItem,
                                      DBUSMENU_MENUITEM_PROP_SHORTCUT);
    return;
  }

  nsAutoString modStr;
  mKeyContent->GetAttr(kNameSpaceID_None, uWidgetAtoms::modifiers, modStr);

  PRUint32 modifier = 0;

  if (!modStr.IsEmpty()) {
    char* str = ToNewUTF8String(modStr);
    char *token = strtok(str, ", \t");
    while(token) {
      if (strcmp(token, "shift") == 0) {
        modifier |= GDK_SHIFT_MASK;
      } else if (strcmp(token, "alt") == 0) {
        modifier |= GDK_MOD1_MASK;
      } else if (strcmp(token, "meta") == 0) {
        modifier |= GDK_META_MASK;
      } else if (strcmp(token, "control") == 0) {
        modifier |= GDK_CONTROL_MASK;
      } else if (strcmp(token, "accel") == 0) {
        nsIPrefBranch *prefs = uGlobalMenuService::GetPrefService();
        PRInt32 accel;
        prefs->GetIntPref("ui.key.accelKey", &accel);
        if (accel == nsIDOMKeyEvent::DOM_VK_META) {
          modifier |= GDK_META_MASK;
        } else if (accel == nsIDOMKeyEvent::DOM_VK_ALT) {
          modifier |= GDK_MOD1_MASK;
        } else {
          modifier |= GDK_CONTROL_MASK;
        }
      }

      token = strtok(nullptr, ", \t");
    }

    nsMemory::Free(str);
  }

  nsAutoString keyStr;
  guint key = 0;
  mKeyContent->GetAttr(kNameSpaceID_None, uWidgetAtoms::key, keyStr);

  nsAutoCString cKeyStr;
  CopyUTF16toUTF8(keyStr, cKeyStr);

  if (!cKeyStr.IsEmpty()) {
    key = gdk_keyval_from_name(cKeyStr.get());
  }

  if (key == 0 && !keyStr.IsEmpty()) {
    key = gdk_unicode_to_keyval(*keyStr.BeginReading());
  }

  if (key == 0) {
    mKeyContent->GetAttr(kNameSpaceID_None, uWidgetAtoms::keycode, keyStr);
    if (!keyStr.IsEmpty())
      key = MozKeyCodeToGdkKeyCode(GetKeyCode(keyStr));
  }

  if (key == 0) {
    key = GDK_VoidSymbol;
  }

  if (key != GDK_VoidSymbol) {
    dbusmenu_menuitem_property_set_shortcut(mDbusMenuItem, key,
                                       static_cast<GdkModifierType>(modifier));
  } else {
    dbusmenu_menuitem_property_remove(mDbusMenuItem,
                                      DBUSMENU_MENUITEM_PROP_SHORTCUT);
  }
}
Пример #19
0
NS_IMETHODIMP
EmbedWindow::OnShowTooltip(PRInt32 aXCoords, PRInt32 aYCoords,
			   const PRUnichar *aTipText)
{
  nsAutoString tipText ( aTipText );

  const char* tipString = ToNewUTF8String(tipText);

  if (sTipWindow)
    gtk_widget_destroy(sTipWindow);
  
  // get the root origin for this content window
  nsCOMPtr<nsIWidget> mainWidget;
  mBaseWindow->GetMainWidget(getter_AddRefs(mainWidget));
  GdkWindow *window;
  window = static_cast<GdkWindow *>(mainWidget->GetNativeData(NS_NATIVE_WINDOW));
  gint root_x, root_y;
  gdk_window_get_origin(window, &root_x, &root_y);

  // XXX work around until I can get pink to figure out why
  // tooltips vanish if they show up right at the origin of the
  // cursor.
  root_y += 10;
  
  sTipWindow = gtk_window_new(GTK_WINDOW_POPUP);
  gtk_widget_set_app_paintable(sTipWindow, TRUE);
  gtk_window_set_resizable(GTK_WINDOW(sTipWindow), TRUE);
  // needed to get colors + fonts etc correctly
  gtk_widget_set_name(sTipWindow, "gtk-tooltips");
  gtk_window_set_type_hint(GTK_WINDOW(sTipWindow), GDK_WINDOW_TYPE_HINT_TOOLTIP);
  
  // set up the popup window as a transient of the widget.
  GtkWidget *toplevel_window;
  toplevel_window = gtk_widget_get_toplevel(GTK_WIDGET(mOwner->mOwningWidget));
  if (!GTK_WINDOW(toplevel_window)) {
    NS_ERROR("no gtk window in hierarchy!\n");
    return NS_ERROR_FAILURE;
  }
  gtk_window_set_transient_for(GTK_WINDOW(sTipWindow),
			       GTK_WINDOW(toplevel_window));
  
  // realize the widget
  gtk_widget_realize(sTipWindow);

  g_signal_connect(G_OBJECT(sTipWindow), "expose_event",
                   G_CALLBACK(tooltips_paint_window), NULL);

  // set up the label for the tooltip
  GtkWidget *label = gtk_label_new(tipString);
  // wrap automatically
  gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
  gtk_container_add(GTK_CONTAINER(sTipWindow), label);
  gtk_container_set_border_width(GTK_CONTAINER(sTipWindow), 4);
  // set the coords for the widget
  gtk_widget_set_uposition(sTipWindow, aXCoords + root_x,
			   aYCoords + root_y);

  // and show it.
  gtk_widget_show_all(sTipWindow);

  NS_Free( (void*)tipString );

  return NS_OK;
}
Пример #20
0
static int
MimeMessage_close_headers (MimeObject *obj)
{
  MimeMessage *msg = (MimeMessage *) obj;
  int status = 0;
  char *ct = 0;      /* Content-Type header */
  MimeObject *body;

  // Do a proper decoding of the munged subject.
  if (obj->headers && msg->hdrs && msg->grabSubject && obj->headers->munged_subject) {
    // nsMsgI18NConvertToUnicode wants nsAStrings...
    nsDependentCString orig(obj->headers->munged_subject);
    nsAutoString dest;
    // First, get the Content-Type, then extract the charset="whatever" part of
    // it.
    nsCString charset;
    nsCString contentType;
    contentType.Adopt(MimeHeaders_get(msg->hdrs, HEADER_CONTENT_TYPE, false, false));
    if (!contentType.IsEmpty())
      charset.Adopt(MimeHeaders_get_parameter(contentType.get(), "charset", nullptr, nullptr));

    // If we've got a charset, use nsMsgI18NConvertToUnicode to magically decode
    // the munged subject.
    if (!charset.IsEmpty()) {
      nsresult rv = nsMsgI18NConvertToUnicode(charset.get(), orig, dest);
      // If we managed to convert the string, replace munged_subject with the
      // UTF8 version of it, otherwise, just forget about it (maybe there was an
      // improperly encoded string in there).
      PR_Free(obj->headers->munged_subject);
      if (NS_SUCCEEDED(rv))
        obj->headers->munged_subject = ToNewUTF8String(dest);
      else
        obj->headers->munged_subject = nullptr;
    } else {
      PR_Free(obj->headers->munged_subject);
      obj->headers->munged_subject = nullptr;
    }
  }

  if (msg->hdrs)
  {
    bool outer_p = !obj->headers; /* is this the outermost message? */


#ifdef MIME_DRAFTS
    if (outer_p &&
      obj->options &&
          (obj->options->decompose_file_p || obj->options->caller_need_root_headers) &&
      obj->options->decompose_headers_info_fn)
    {
#ifdef ENABLE_SMIME
      if (obj->options->decrypt_p && !mime_crypto_object_p (msg->hdrs, false))
        obj->options->decrypt_p = false;
#endif /* ENABLE_SMIME */
      if (!obj->options->caller_need_root_headers || (obj == obj->options->state->root))
        status = obj->options->decompose_headers_info_fn (
                         obj->options->stream_closure,
                               msg->hdrs );
    }
#endif /* MIME_DRAFTS */


    /* If this is the outermost message, we need to run the
     `generate_header' callback.  This happens here instead of
     in `parse_begin', because it's only now that we've parsed
     our headers.  However, since this is the outermost message,
     we have yet to write any HTML, so that's fine.
     */
    if (outer_p &&
      obj->output_p &&
      obj->options &&
      obj->options->write_html_p &&
      obj->options->generate_header_html_fn)
    {
      int lstatus = 0;
      char *html = 0;

      /* The generate_header_html_fn might return HTML, so it's important
       that the output stream be set up with the proper type before we
       make the MimeObject_write() call below. */
      if (!obj->options->state->first_data_written_p)
      {
        lstatus = MimeObject_output_init (obj, TEXT_HTML);
        if (lstatus < 0) return lstatus;
        PR_ASSERT(obj->options->state->first_data_written_p);
      }

      html = obj->options->generate_header_html_fn(NULL,
                           obj->options->html_closure,
                             msg->hdrs);
      if (html)
      {
        lstatus = MimeObject_write(obj, html, strlen(html), false);
        PR_Free(html);
        if (lstatus < 0) return lstatus;
      }
    }


    /* Find the content-type of the body of this message.
     */
    {
    bool ok = true;
    char *mv = MimeHeaders_get (msg->hdrs, HEADER_MIME_VERSION,
                  true, false);

#ifdef REQUIRE_MIME_VERSION_HEADER
    /* If this is the outermost message, it must have a MIME-Version
       header with the value 1.0 for us to believe what might be in
       the Content-Type header.  If the MIME-Version header is not
       present, we must treat this message as untyped.
     */
    ok = (mv && !strcmp(mv, "1.0"));
#else
    /* #### actually, we didn't check this in Mozilla 2.0, and checking
       it now could cause some compatibility nonsense, so for now, let's
       just believe any Content-Type header we see.
     */
    ok = true;
#endif

    if (ok)
      {
      ct = MimeHeaders_get (msg->hdrs, HEADER_CONTENT_TYPE, true, false);

      /* If there is no Content-Type header, but there is a MIME-Version
         header, then assume that this *is* in fact a MIME message.
         (I've seen messages with

          MIME-Version: 1.0
          Content-Transfer-Encoding: quoted-printable

         and no Content-Type, and we should treat those as being of type
         MimeInlineTextPlain rather than MimeUntypedText.)
       */
      if (mv && !ct)
        ct = strdup(TEXT_PLAIN);
      }

    PR_FREEIF(mv);  /* done with this now. */
    }

    /* If this message has a body which is encrypted and we're going to
       decrypt it (whithout converting it to HTML, since decrypt_p and
       write_html_p are never true at the same time)
    */
    if (obj->output_p &&
        obj->options &&
        obj->options->decrypt_p
#ifdef ENABLE_SMIME
        && !mime_crypto_object_p (msg->hdrs, false)
#endif /* ENABLE_SMIME */
        )
    {
      /* The body of this message is not an encrypted object, so we need
         to turn off the decrypt_p flag (to prevent us from s#$%ing the
         body of the internal object up into one.) In this case,
         our output will end up being identical to our input.
      */
      obj->options->decrypt_p = false;
    }

    /* Emit the HTML for this message's headers.  Do this before
     creating the object representing the body.
     */
    if (obj->output_p &&
      obj->options &&
      obj->options->write_html_p)
    {
      /* If citation headers are on, and this is not the outermost message,
       turn them off. */
      if (obj->options->headers == MimeHeadersCitation && !outer_p)
      obj->options->headers = MimeHeadersSome;

      /* Emit a normal header block. */
      status = MimeMessage_write_headers_html(obj);
      if (status < 0) return status;
    }
    else if (obj->output_p)
    {
      /* Dump the headers, raw. */
      status = MimeObject_write(obj, "", 0, false);  /* initialize */
      if (status < 0) return status;
      status = MimeHeaders_write_raw_headers(msg->hdrs, obj->options,
                         obj->options->decrypt_p);
      if (status < 0) return status;
    }

#ifdef XP_UNIX
    if (outer_p && obj->output_p)
    /* Kludge from mimehdrs.c */
    MimeHeaders_do_unix_display_hook_hack(msg->hdrs);
#endif /* XP_UNIX */
  }

  /* Never put out a separator after a message header block. */
  if (obj->options && obj->options->state)
  obj->options->state->separator_suppressed_p = true;

#ifdef MIME_DRAFTS
  if ( !obj->headers &&    /* outer most message header */
     obj->options &&
     obj->options->decompose_file_p &&
     ct )
  obj->options->is_multipart_msg = PL_strcasestr(ct, "multipart/") != NULL;
#endif /* MIME_DRAFTS */


  body = mime_create(ct, msg->hdrs, obj->options);

  PR_FREEIF(ct);
  if (!body) return MIME_OUT_OF_MEMORY;
  status = ((MimeContainerClass *) obj->clazz)->add_child (obj, body);
  if (status < 0)
  {
    mime_free(body);
    return status;
  }

  // Only do this if this is a Text Object!
  if ( mime_typep(body, (MimeObjectClass *) &mimeInlineTextClass) )
  {
    ((MimeInlineText *) body)->needUpdateMsgWinCharset = true;
  }

  /* Now that we've added this new object to our list of children,
   start its parser going. */
  status = body->clazz->parse_begin(body);
  if (status < 0) return status;

  // Now notify the emitter if this is the outer most message, unless
  // it is a part that is not the head of the message. If it's a part,
  // we need to figure out the content type/charset of the part
  //
  bool outer_p = !obj->headers;  /* is this the outermost message? */

  if ( (outer_p || obj->options->notify_nested_bodies) &&
       (!obj->options->part_to_load || obj->options->format_out == nsMimeOutput::nsMimeMessageBodyDisplay))
  {
    // call SetMailCharacterSetToMsgWindow() to set a menu charset
    if (mime_typep(body, (MimeObjectClass *) &mimeInlineTextClass))
    {
      MimeInlineText  *text = (MimeInlineText *) body;
      if (text && text->charset && *text->charset)
        SetMailCharacterSetToMsgWindow(body, text->charset);
    }

    char  *msgID = MimeHeaders_get (msg->hdrs, HEADER_MESSAGE_ID,
                                    false, false);

    const char  *outCharset = NULL;
    if (!obj->options->force_user_charset)  /* Only convert if the user prefs is false */
      outCharset = "UTF-8";

    mimeEmitterStartBody(obj->options, (obj->options->headers == MimeHeadersNone), msgID, outCharset);
    PR_FREEIF(msgID);

  // setting up truncated message html fotter function
  char *xmoz = MimeHeaders_get(msg->hdrs, HEADER_X_MOZILLA_STATUS, false,
                 false);
  if (xmoz)
  {
    uint32_t flags = 0;
    char dummy = 0;
    if (sscanf(xmoz, " %x %c", &flags, &dummy) == 1 &&
      flags & nsMsgMessageFlags::Partial)
    {
      obj->options->html_closure = obj;
      obj->options->generate_footer_html_fn =
        MimeMessage_partial_message_html;
    }
    PR_FREEIF(xmoz);
  }
  }

  return 0;
}
Пример #21
0
NS_IMETHODIMP nsImportFieldMap::SetFieldValue(nsIAddrDatabase *database, nsIMdbRow *row, PRInt32 fieldNum, const PRUnichar *value)
{
  NS_PRECONDITION(database != nsnull, "null ptr");
  NS_PRECONDITION(row != nsnull, "null ptr");
  NS_PRECONDITION(value != nsnull, "null ptr");
  if (!database || !row || !value)
    return NS_ERROR_NULL_POINTER;

  // Allow the special value for a null field
  if (fieldNum == -1)
    return( NS_OK);

  if ((fieldNum < 0) || (fieldNum >= m_mozFieldCount))
    return( NS_ERROR_FAILURE);

  // UGGG!!!!! lot's of typing here!
  nsresult rv;

  nsString str(value);
  char *pVal = ToNewUTF8String(str);

  switch( fieldNum) {
  case 0:
    rv = database->AddFirstName( row, pVal);
    break;
  case 1:
    rv = database->AddLastName( row, pVal);
    break;
  case 2:
    rv = database->AddDisplayName( row, pVal);
    break;
  case 3:
    rv = database->AddNickName( row, pVal);
    break;
  case 4:
    rv = database->AddPrimaryEmail( row, pVal);
    break;
  case 5:
    rv = database->Add2ndEmail( row, pVal);
    break;
  case 6:
    rv = database->AddWorkPhone( row, pVal);
    break;
  case 7:
    rv = database->AddHomePhone( row, pVal);
    break;
  case 8:
    rv = database->AddFaxNumber( row, pVal);
    break;
  case 9:
    rv = database->AddPagerNumber( row, pVal);
    break;
  case 10:
    rv = database->AddCellularNumber( row, pVal);
    break;
  case 11:
    rv = database->AddHomeAddress( row, pVal);
    break;
  case 12:
    rv = database->AddHomeAddress2( row, pVal);
    break;
  case 13:
    rv = database->AddHomeCity( row, pVal);
    break;
  case 14:
    rv = database->AddHomeState( row, pVal);
    break;
  case 15:
    rv = database->AddHomeZipCode( row, pVal);
    break;
  case 16:
    rv = database->AddHomeCountry( row, pVal);
    break;
  case 17:
    rv = database->AddWorkAddress( row, pVal);
    break;
  case 18:
    rv = database->AddWorkAddress2( row, pVal);
    break;
  case 19:
    rv = database->AddWorkCity( row, pVal);
    break;
  case 20:
    rv = database->AddWorkState( row, pVal);
    break;
  case 21:
    rv = database->AddWorkZipCode( row, pVal);
    break;
  case 22:
    rv = database->AddWorkCountry( row, pVal);
    break;
  case 23:
    rv = database->AddJobTitle(row, pVal);
    break;
  case 24:
    rv = database->AddDepartment(row, pVal);
    break;
  case 25:
    rv = database->AddCompany(row, pVal);
    break;
  case 26:
    rv = database->AddWebPage1(row, pVal);
    break;
  case 27:
    rv = database->AddWebPage2(row, pVal);
    break;
  case 28:
    rv = database->AddBirthYear(row, pVal);
    break;
  case 29:
    rv = database->AddBirthMonth(row, pVal);
    break;
  case 30:
    rv = database->AddBirthDay(row, pVal);
    break;
  case 31:
    rv = database->AddCustom1(row, pVal);
    break;
  case 32:
    rv = database->AddCustom2(row, pVal);
    break;
  case 33:
    rv = database->AddCustom3(row, pVal);
    break;
  case 34:
    rv = database->AddCustom4(row, pVal);
    break;
  case 35:
    rv = database->AddNotes(row, pVal);
    break;
  case 36:
    rv = database->AddAimScreenName(row, pVal);
    break;
  default:
    /* Get the field description, and add it as an anonymous attr? */
    /* OR WHAT???? */
    {
      rv = NS_ERROR_FAILURE;
    }
  }

  NS_Free( pVal);

  return( rv);
}
Пример #22
0
void
nsAbAutoCompleteSession::AddToResult(const PRUnichar* pNickNameStr,
                                     const PRUnichar* pDisplayNameStr,
                                     const PRUnichar* pFirstNameStr,
                                     const PRUnichar* pLastNameStr,
                                     const PRUnichar* pEmailStr,
                                     const PRUnichar* pNotesStr,
                                     const PRUnichar* pDirName,
                                     PRUint32 aPopularityIndex,
                                     PRBool bIsMailList, PRBool pDefaultMatch,
                                     nsIAutoCompleteResults* results)
{
    nsresult rv;
    PRUnichar* fullAddrStr = nsnull;

    if (pDefaultMatch)
    {
        if (mDefaultDomain[0] == 0)
            return;

        nsAutoString aStr(pDisplayNameStr);
        if (aStr.FindChar('@') == kNotFound)
        {
            aStr.Append(PRUnichar('@'));
            aStr += mDefaultDomain;
        }
        fullAddrStr = ToNewUnicode(aStr);
    }
    else
    {
        if (mParser)
        {
            nsXPIDLCString fullAddress;
            nsXPIDLCString utf8Email;
            if (bIsMailList)
            {
                if (pNotesStr && pNotesStr[0] != 0)
                    utf8Email.Adopt(ToNewUTF8String(nsDependentString(pNotesStr)));
                else
                    utf8Email.Adopt(ToNewUTF8String(nsDependentString(pDisplayNameStr)));
            }
            else
                utf8Email.Adopt(ToNewUTF8String(nsDependentString(pEmailStr)));

            mParser->MakeFullAddress(nsnull, NS_ConvertUCS2toUTF8(pDisplayNameStr).get(),
                                     utf8Email, getter_Copies(fullAddress));
            if (!fullAddress.IsEmpty())
            {
                /* We need to convert back the result from UTF-8 to Unicode */
                fullAddrStr = nsCRT::strdup(NS_ConvertUTF8toUCS2(fullAddress.get()).get());
            }
        }

        if (!fullAddrStr)
        {
            //oops, parser problem! I will try to do my best...
            const PRUnichar * pStr = nsnull;
            if (bIsMailList)
            {
                if (pNotesStr && pNotesStr[0] != 0)
                    pStr = pNotesStr;
                else
                    pStr = pDisplayNameStr;
            }
            else
                pStr = pEmailStr;
            // check this so we do not get a bogus entry "someName <>"
            if (pStr && pStr[0] != 0) {
                nsAutoString aStr(pDisplayNameStr);
                aStr.AppendLiteral(" <");
                aStr += pStr;
                aStr.AppendLiteral(">");
                fullAddrStr = ToNewUnicode(aStr);
            }
            else
                fullAddrStr = nsnull;
        }
    }

    if (fullAddrStr && ! ItsADuplicate(fullAddrStr, aPopularityIndex, results))
    {
        nsCOMPtr<nsIAutoCompleteItem> newItem = do_CreateInstance(NS_AUTOCOMPLETEITEM_CONTRACTID, &rv);
        if (NS_SUCCEEDED(rv))
        {
            nsAbAutoCompleteParam *param = new nsAbAutoCompleteParam(pNickNameStr, pDisplayNameStr, pFirstNameStr, pLastNameStr, pEmailStr, pNotesStr, pDirName, aPopularityIndex, bIsMailList);
            NS_IF_ADDREF(param);
            newItem->SetParam(param);
            NS_IF_RELEASE(param);

            // how to process the comment column, if at all.  this value
            // comes from "mail.autoComplete.commentColumn", or, if that
            // doesn't exist, defaults to 0
            //
            // 0 = none
            // 1 = name of addressbook this card came from
            // 2 = other per-addressbook format (currrently unused here)
            //
            if (mAutoCompleteCommentColumn == 1) {
                rv = newItem->SetComment(pDirName);
                if (NS_FAILED(rv)) {
                    NS_WARNING("nsAbAutoCompleteSession::AddToResult():"
                               " newItem->SetComment() failed\n");
                }
            }

            // if this isn't a default match, set the class name so we can style
            // this cell with the local addressbook icon (or whatever)
            //
            rv = newItem->SetClassName(pDefaultMatch ? "default-match" :
                                       "local-abook");
            if (NS_FAILED(rv)) {
                NS_WARNING("nsAbAutoCompleteSession::AddToResult():"
                           " newItem->SetClassName() failed\n");
            }

            newItem->SetValue(nsDependentString(fullAddrStr));
            nsCOMPtr<nsISupportsArray> array;
            rv = results->GetItems(getter_AddRefs(array));
            if (NS_SUCCEEDED(rv))
            {
                PRUint32 nbrOfItems;
                rv = array->Count(&nbrOfItems);

                PRInt32 insertPosition = 0;

                for (; insertPosition < nbrOfItems && !pDefaultMatch; insertPosition++)
                {
                    nsCOMPtr<nsISupports> currentItemParams;
                    nsCOMPtr<nsIAutoCompleteItem> resultItem;
                    nsresult rv = array->QueryElementAt(insertPosition, NS_GET_IID(nsIAutoCompleteItem),
                                                        getter_AddRefs(resultItem));
                    if (NS_FAILED(rv))
                        continue;
                    rv = resultItem->GetParam(getter_AddRefs(currentItemParams));
                    if (NS_FAILED(rv))
                        continue;

                    param = (nsAbAutoCompleteParam *)(void *)currentItemParams;
                    if (aPopularityIndex > param->mPopularityIndex) // sort the search results by popularity index
                        break;
                }

                rv = array->InsertElementAt(newItem, insertPosition);
            }
        }
    }
    PR_Free(fullAddrStr);
}
Пример #23
0
/* dpoIKernel compileKernel (in AString source, in AString kernelName, [optional] in AString options); */
NS_IMETHODIMP dpoCContext::CompileKernel(const nsAString & source, const nsAString & kernelName, const nsAString & options, dpoIKernel **_retval)
{
	cl_program program;
	cl_kernel kernel;
	cl_int err_code, err_code2;
	cl_uint numDevices;
	cl_device_id *devices = NULL;
	size_t actual;
	char *sourceStr, *optionsStr, *kernelNameStr;
	nsCOMPtr<dpoCKernel> ret;
	nsresult result;

	sourceStr = ToNewUTF8String(source);
	DEBUG_LOG_STATUS("CompileKernel", "Source: " << sourceStr);
	program = clCreateProgramWithSource(context, 1, (const char**)&sourceStr, NULL, &err_code);
	nsMemory::Free(sourceStr);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code);
		return NS_ERROR_ILLEGAL_VALUE;
	}

	optionsStr = ToNewUTF8String(options);
	err_code = clBuildProgram(program, 0, NULL, optionsStr, NULL, NULL);
	nsMemory::Free(optionsStr);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code);
	}
		
	err_code2 = clGetProgramInfo(program, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &numDevices, NULL);
	if (err_code2 != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code2);
		goto FAIL;
	} 

	devices = (cl_device_id *) nsMemory::Alloc(numDevices * sizeof(cl_device_id));
	err_code2 = clGetProgramInfo(program, CL_PROGRAM_DEVICES, numDevices * sizeof(cl_device_id), devices, NULL);
	if (err_code2 != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code);
		goto FAIL;
	} 
	err_code2 = clGetProgramBuildInfo(program, devices[0], CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, &actual);
	if (actual > buildLogSize) {
		if (buildLog != NULL) {
			nsMemory::Free(buildLog);
		}
		buildLog = (char *) nsMemory::Alloc(actual * sizeof(char));
		if (buildLog == NULL) {
			DEBUG_LOG_STATUS("CompileKernel", "Cannot allocate buildLog");
			buildLogSize = 0;
			goto DONE;
		}
		buildLogSize = actual;
		err_code2 = clGetProgramBuildInfo(program, devices[0], CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, &actual);
	}
			
	if (err_code2 != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code);
		goto FAIL;
	}

	DEBUG_LOG_STATUS("CompileKernel", "buildLog: " << buildLog);
	goto DONE;

FAIL:
	if (buildLog != NULL) {
		nsMemory::Free(buildLog);
		buildLog = NULL;
		buildLogSize = 0;
	}

DONE:
	if (devices != NULL) {
		nsMemory::Free(devices);
	}
	
	kernelNameStr = ToNewUTF8String(kernelName);
	kernel = clCreateKernel(program, kernelNameStr, &err_code);
	nsMemory::Free( kernelNameStr);
	clReleaseProgram(program);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("CompileKernel", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	ret = new dpoCKernel(this);
	if (ret == NULL) {
		clReleaseKernel(kernel);
		DEBUG_LOG_STATUS("CompileKernel", "Cannot create new dpoCKernel object");
		return NS_ERROR_OUT_OF_MEMORY;
	}

	/* all kernels share the single buffer for the failure code */
	result = ret->InitKernel(cmdQueue, kernel, kernelFailureMem);
	if (NS_FAILED(result)) {
		clReleaseKernel(kernel);
		return result;
	}

	ret.forget((dpoCKernel **)_retval);
	
	return NS_OK;
}
Пример #24
0
NS_IMETHODIMP
nsFilePicker::Show(PRInt16 *aReturn)
{
  NS_ENSURE_ARG_POINTER(aReturn);

  nsXPIDLCString title;
  title.Adopt(ToNewUTF8String(mTitle));

  GtkWindow *parent_widget = get_gtk_window_for_nsiwidget(mParentWidget);

  GtkFileChooserAction action = GetGtkFileChooserAction(mMode);
  const gchar *accept_button = (action == GTK_FILE_CHOOSER_ACTION_SAVE)
                               ? GTK_STOCK_SAVE : GTK_STOCK_OPEN;
#if (MOZ_PLATFORM_MAEMO == 5)
  GtkWidget *file_chooser =
    hildon_file_chooser_dialog_new_with_properties(parent_widget,
                                                   "action", action,
                                                   "open-button-text", accept_button,
                                                   NULL);
  gtk_window_set_title(GTK_WINDOW(file_chooser), title);
#else
  GtkWidget *file_chooser =
      gtk_file_chooser_dialog_new(title, parent_widget, action,
                                  GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                  accept_button, GTK_RESPONSE_ACCEPT,
                                  NULL);
  gtk_dialog_set_alternative_button_order(GTK_DIALOG(file_chooser),
                                          GTK_RESPONSE_ACCEPT,
                                          GTK_RESPONSE_CANCEL,
                                          -1);
  if (mAllowURLs) {
    gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(file_chooser), FALSE);
  }
#endif

  if (action == GTK_FILE_CHOOSER_ACTION_OPEN || action == GTK_FILE_CHOOSER_ACTION_SAVE) {
    GtkWidget *img_preview = gtk_image_new();
    gtk_file_chooser_set_preview_widget(GTK_FILE_CHOOSER(file_chooser), img_preview);
    g_signal_connect(file_chooser, "update-preview", G_CALLBACK(UpdateFilePreviewWidget), img_preview);
  }

  if (parent_widget && parent_widget->group) {
    gtk_window_group_add_window(parent_widget->group, GTK_WINDOW(file_chooser));
  }

  NS_ConvertUTF16toUTF8 defaultName(mDefault);
  switch (mMode) {
    case nsIFilePicker::modeOpenMultiple:
      gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(file_chooser), TRUE);
      break;
    case nsIFilePicker::modeSave:
      gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser),
                                        defaultName.get());
      break;
  }

  nsCOMPtr<nsIFile> defaultPath;
  if (mDisplayDirectory) {
    mDisplayDirectory->Clone(getter_AddRefs(defaultPath));
  } else if (mPrevDisplayDirectory) {
    mPrevDisplayDirectory->Clone(getter_AddRefs(defaultPath));
  }

  if (defaultPath) {
    if (!defaultName.IsEmpty() && mMode != nsIFilePicker::modeSave) {
      // Try to select the intended file. Even if it doesn't exist, GTK still switches
      // directories.
      defaultPath->AppendNative(defaultName);
      nsCAutoString path;
      defaultPath->GetNativePath(path);
      gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(file_chooser), path.get());
    } else {
      nsCAutoString directory;
      defaultPath->GetNativePath(directory);
      gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(file_chooser),
                                          directory.get());
    }
  }

  gtk_dialog_set_default_response(GTK_DIALOG(file_chooser), GTK_RESPONSE_ACCEPT);

  PRInt32 count = mFilters.Length();
  for (PRInt32 i = 0; i < count; ++i) {
    // This is fun... the GTK file picker does not accept a list of filters
    // so we need to split out each string, and add it manually.

    char **patterns = g_strsplit(mFilters[i].get(), ";", -1);
    if (!patterns) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    GtkFileFilter *filter = gtk_file_filter_new();
    for (int j = 0; patterns[j] != NULL; ++j) {
      nsCAutoString caseInsensitiveFilter = MakeCaseInsensitiveShellGlob(g_strstrip(patterns[j]));
      gtk_file_filter_add_pattern(filter, caseInsensitiveFilter.get());
    }

    g_strfreev(patterns);

    if (!mFilterNames[i].IsEmpty()) {
      // If we have a name for our filter, let's use that.
      const char *filter_name = mFilterNames[i].get();
      gtk_file_filter_set_name(filter, filter_name);
    } else {
      // If we don't have a name, let's just use the filter pattern.
      const char *filter_pattern = mFilters[i].get();
      gtk_file_filter_set_name(filter, filter_pattern);
    }

    gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(file_chooser), filter);

    // Set the initially selected filter
    if (mSelectedType == i) {
      gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(file_chooser), filter);
    }
  }

  gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(file_chooser), PR_TRUE);
  gint response = RunDialog(GTK_DIALOG(file_chooser));

  switch (response) {
    case GTK_RESPONSE_OK:
    case GTK_RESPONSE_ACCEPT:
    ReadValuesFromFileChooser(file_chooser);
    *aReturn = nsIFilePicker::returnOK;
    if (mMode == nsIFilePicker::modeSave) {
      nsCOMPtr<nsILocalFile> file;
      GetFile(getter_AddRefs(file));
      if (file) {
        PRBool exists = PR_FALSE;
        file->Exists(&exists);
        if (exists)
          *aReturn = nsIFilePicker::returnReplace;
      }
    }
    break;

    case GTK_RESPONSE_CANCEL:
    case GTK_RESPONSE_CLOSE:
    case GTK_RESPONSE_DELETE_EVENT:
    *aReturn = nsIFilePicker::returnCancel;
    break;

    default:
    NS_WARNING("Unexpected response");
    *aReturn = nsIFilePicker::returnCancel;
    break;
  }

  gtk_widget_destroy(file_chooser);

  return NS_OK;
}