/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef XP_WIN # include "mozilla/StaticPrefs_clipboard.h" # include "nsCExternalHandlerService.h" # include "nsEscape.h" # include "nsIMIMEInfo.h" # include "nsIMIMEService.h" # include "nsIURIMutator.h" # include "nsIURL.h" # include "nsReadableUtils.h" # include "nsXULAppAPI.h" #endif
// copy string data onto the transferable static nsresult AppendString(nsITransferable* aTransferable, const nsAString& aString, constchar* aFlavor);
// copy HTML node data static nsresult AppendDOMNode(nsITransferable* aTransferable,
nsINode* aDOMNode);
#ifdef XP_WIN // copy image as file promise onto the transferable static nsresult AppendImagePromise(nsITransferable* aTransferable,
imgIRequest* aImgRequest,
nsINode* aImageNode); #endif
static nsresult EncodeForTextUnicode(nsIDocumentEncoder& aEncoder,
Document& aDocument, Selection* aSelection,
uint32_t aAdditionalEncoderFlags, bool& aEncodedAsTextHTMLResult,
nsAutoString& aSerializationResult) { // note that we assign text/unicode as mime type, but in fact // nsHTMLCopyEncoder ignore it and use text/html or text/plain depending where // the selection is. if it is a selection into input/textarea element or in a // html content with pre-wrap style : text/plain. Otherwise text/html. see // nsHTMLCopyEncoder::SetSelection
nsAutoString mimeType;
mimeType.AssignLiteral("text/unicode");
// Do the first and potentially trial encoding as preformatted and raw.
uint32_t flags = aAdditionalEncoderFlags |
nsIDocumentEncoder::OutputPreformatted |
nsIDocumentEncoder::OutputRaw |
nsIDocumentEncoder::OutputForPlainTextClipboardCopy |
nsIDocumentEncoder::OutputPersistNBSP;
// SetSelection set the mime type to text/plain if the selection is inside a // text widget.
rv = aEncoder.GetMimeType(mimeType);
NS_ENSURE_SUCCESS(rv, rv); bool selForcedTextPlain = mimeType.EqualsLiteral(kTextMime);
// The mime type is ultimately text/html if the encoder successfully encoded // the selection as text/html.
aEncodedAsTextHTMLResult = mimeType.EqualsLiteral(kHTMLMime);
if (selForcedTextPlain) { // Nothing to do. buf contains the final, preformatted, raw text/plain.
aSerializationResult.Assign(buf);
} else { // Redo the encoding, but this time use pretty printing.
flags = nsIDocumentEncoder::OutputSelectionOnly |
nsIDocumentEncoder::OutputAbsoluteLinks |
nsIDocumentEncoder::SkipInvisibleContent |
nsIDocumentEncoder::OutputDropInvisibleBreak |
(aAdditionalEncoderFlags &
(nsIDocumentEncoder::OutputNoScriptContent |
nsIDocumentEncoder::OutputRubyAnnotation |
nsIDocumentEncoder::AllowCrossShadowBoundary));
struct EncodedDocumentWithContext { // When determining `mSerializationForTextUnicode`, `text/unicode` is passed // as mime type to the encoder. It uses this as a switch to decide whether to // encode the document as `text/html` or `text/plain`. It is `true` iff // `text/html` was used. bool mUnicodeEncodingIsTextHTML = false;
// The serialized document when encoding the document with `text/unicode`. See // comment of `mUnicodeEncodingIsTextHTML`.
nsAutoString mSerializationForTextUnicode;
// When `mUnicodeEncodingIsTextHTML` is true, this is the serialized document // using `text/html`. Its value may differ from `mSerializationForTextHTML`, // because different flags were passed to the encoder.
nsAutoString mSerializationForTextHTML;
// When `mUnicodeEncodingIsTextHTML` is true, this contains the serialized // ancestor elements.
nsAutoString mHTMLContextBuffer;
// When `mUnicodeEncodingIsTextHTML` is true, this contains numbers // identifying where in the context the serialization came from.
nsAutoString mHTMLInfoBuffer;
};
aTransferable->Init(aDocument.GetLoadContext());
aTransferable->SetDataPrincipal(aDocument.NodePrincipal()); if (aEncodedDocumentWithContext.mUnicodeEncodingIsTextHTML) { // Set up a format converter so that clipboard flavor queries work. // This converter isn't really used for conversions.
nsCOMPtr<nsIFormatConverter> htmlConverter =
do_CreateInstance(kHTMLConverterCID);
aTransferable->SetConverter(htmlConverter);
if (!aEncodedDocumentWithContext.mSerializationForTextHTML.IsEmpty()) { // Add the html DataFlavor to the transferable
rv = AppendString(aTransferable,
aEncodedDocumentWithContext.mSerializationForTextHTML,
kHTMLMime);
NS_ENSURE_SUCCESS(rv, rv);
}
// Add the htmlcontext DataFlavor to the transferable. Even if the context // buffer is empty, this flavor should be attached to the transferable.
rv = AppendString(aTransferable,
aEncodedDocumentWithContext.mHTMLContextBuffer,
kHTMLContext);
NS_ENSURE_SUCCESS(rv, rv);
if (!aEncodedDocumentWithContext.mHTMLInfoBuffer.IsEmpty()) { // Add the htmlinfo DataFlavor to the transferable
rv = AppendString(aTransferable,
aEncodedDocumentWithContext.mHTMLInfoBuffer, kHTMLInfo);
NS_ENSURE_SUCCESS(rv, rv);
}
if (!aEncodedDocumentWithContext.mSerializationForTextUnicode.IsEmpty()) { // unicode text // Add the plain text DataFlavor to the transferable // If we didn't have this, then nsDataObj::GetData matches // text/plain against the kURLMime flavour which is not desirable // (eg. when pasting into Notepad)
rv = AppendString(
aTransferable,
aEncodedDocumentWithContext.mSerializationForTextUnicode, kTextMime);
NS_ENSURE_SUCCESS(rv, rv);
}
// Try and get source URI of the items that are being dragged
nsIURI* uri = aDocument.GetDocumentURI(); if (uri) {
nsAutoCString spec;
nsresult rv = uri->GetSpec(spec);
NS_ENSURE_SUCCESS(rv, rv); if (!spec.IsEmpty()) {
nsAutoString shortcut;
AppendUTF8toUTF16(spec, shortcut);
// Add the URL DataFlavor to the transferable. Don't use kURLMime, // as it will cause an unnecessary UniformResourceLocator to be // added which confuses some apps eg. Outlook 2000 - (See Bug // 315370). Don't use kURLDataMime, as it will cause a bogus 'url ' // flavor to show up on the Mac clipboard, confusing other apps, // like Terminal (see bug 336012).
rv = AppendString(aTransferable, shortcut, kURLPrivateMime);
NS_ENSURE_SUCCESS(rv, rv);
}
}
} else { if (!aEncodedDocumentWithContext.mSerializationForTextUnicode.IsEmpty()) { // Add the unicode DataFlavor to the transferable
rv = AppendString(
aTransferable,
aEncodedDocumentWithContext.mSerializationForTextUnicode, kTextMime);
NS_ENSURE_SUCCESS(rv, rv);
}
}
// Make a temporary selection with aNode in a single range. // XXX We should try to get rid of the Selection object here. // XXX bug 1245883
RefPtr<Selection> selection = new Selection(SelectionType::eNormal, nullptr);
RefPtr<nsRange> range = nsRange::Create(aNode);
ErrorResult result;
range->SelectNode(*aNode, result); if (NS_WARN_IF(result.Failed())) { return result.StealNSResult();
}
selection->AddRangeAndSelectFramesAndNotifyListenersInternal(*range, aDoc,
result); if (NS_WARN_IF(result.Failed())) { return result.StealNSResult();
} // It's not the primary selection - so don't skip invisible content.
uint32_t additionalFlags = 0; return EncodeDocumentWithContextAndCreateTransferable(
*aDoc, selection, additionalFlags, aTransferable);
}
// create a transferable for putting data on the Clipboard
nsCOMPtr<nsITransferable> trans(do_CreateInstance(kCTransferableCID, &rv));
NS_ENSURE_SUCCESS(rv, rv);
trans->Init(aLoadContext);
trans->SetDataPrincipal(imageNode->NodePrincipal());
if (aCopyFlags & nsIDocumentViewerEdit::COPY_IMAGE_TEXT) { // get the location from the element
nsCOMPtr<nsIURI> uri;
rv = aImageElement->GetCurrentURI(getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
// append the string to the transferable
rv = AppendString(trans, NS_ConvertUTF8toUTF16(location), kTextMime);
NS_ENSURE_SUCCESS(rv, rv);
}
if (aCopyFlags & nsIDocumentViewerEdit::COPY_IMAGE_HTML) { // append HTML data to the transferable
nsCOMPtr<nsINode> node(do_QueryInterface(aImageElement, &rv));
NS_ENSURE_SUCCESS(rv, rv);
if (aCopyFlags & nsIDocumentViewerEdit::COPY_IMAGE_DATA) { // get the image data and its request from the element
nsCOMPtr<imgIRequest> imgRequest;
nsCOMPtr<imgIContainer> image = nsContentUtils::GetImageFromContent(
aImageElement, getter_AddRefs(imgRequest));
NS_ENSURE_TRUE(image, NS_ERROR_FAILURE);
if (imgRequest) { // Remember the referrer used for this image request.
nsCOMPtr<nsIReferrerInfo> referrerInfo;
imgRequest->GetReferrerInfo(getter_AddRefs(referrerInfo));
trans->SetReferrerInfo(referrerInfo);
}
// copy the image data onto the transferable
rv = trans->SetTransferData(kNativeImageMime, image);
NS_ENSURE_SUCCESS(rv, rv);
}
// get clipboard
nsCOMPtr<nsIClipboard> clipboard(do_GetService(kCClipboardCID, &rv));
NS_ENSURE_SUCCESS(rv, rv);
// check whether the system supports the selection clipboard or not. if (clipboard->IsClipboardTypeSupported(nsIClipboard::kSelectionClipboard)) { // put the transferable on the clipboard
rv = clipboard->SetData(trans, nullptr, nsIClipboard::kSelectionClipboard,
aSettingWindowContext);
NS_ENSURE_SUCCESS(rv, rv);
}
// get document for the encoder
nsCOMPtr<Document> document = aDOMNode->OwnerDoc();
// Note that XHTML is not counted as HTML here, because we can't copy it // properly (all the copy code for non-plaintext assumes using HTML // serializers and parsers is OK, and those mess up XHTML).
NS_ENSURE_TRUE(document->IsHTMLDocument(), NS_OK);
// init encoder with document and node
rv = docEncoder->NativeInit(
document, NS_LITERAL_STRING_FROM_CSTRING(kHTMLMime),
nsIDocumentEncoder::OutputAbsoluteLinks |
nsIDocumentEncoder::OutputEncodeBasicEntities);
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<PresShell> presShell = aPresShell; if (!presShell) { returnfalse;
}
nsCOMPtr<Document> doc = presShell->GetDocument(); if (!doc) returnfalse;
nsCOMPtr<nsPIDOMWindowOuter> piWindow = doc->GetWindow(); if (!piWindow) returnfalse;
// Event target of clipboard events should be an element node which // contains selection start container.
RefPtr<Element> targetElement;
// If a selection was not supplied, try to find it.
RefPtr<Selection> sel = aSelection; if (!sel) {
sel = GetSelectionForCopy(doc);
}
// Retrieve the event target node from the start of the selection. if (sel) { const nsRange* range = sel->GetRangeAt(0); if (range) {
targetElement = GetElementOrNearestFlattenedTreeParentElement(
range->GetStartContainer());
}
}
// If there is no selection ranges, use the <body> or <frameset> element. if (!targetElement) {
targetElement = doc->GetBody(); if (!targetElement) { returnfalse;
}
}
// It seems to be unsafe to fire an event handler during reflow (bug 393696) if (!nsContentUtils::IsSafeToRunScript()) {
nsContentUtils::WarnScriptWasIgnored(doc); returnfalse;
}
BrowsingContext* bc = piWindow->GetBrowsingContext(); constbool chromeShell = bc && bc->IsChrome();
// If the event was cancelled, don't do the clipboard operation
doDefault = (status != nsEventStatus_eConsumeNoDefault);
}
// When this function exits, the event dispatch is over. We want to disconnect // our DataTransfer, which means setting its mode to `Protected` and clearing // all stored data, before we return. auto clearAfter = MakeScopeExit([&] { if (clipboardData && !aDataTransfer) {
clipboardData->Disconnect();
// NOTE: Disconnect may not actually clear the DataTransfer if the // dom.events.dataTransfer.protected.enabled pref is not on, so we make // sure we clear here, as not clearing could provide the DataTransfer // access to information from the system clipboard at an arbitrary point // in the future. if (originalEventMessage == ePaste) {
clipboardData->ClearAll();
}
}
});
// No need to do anything special during a paste. Either an event listener // took care of it and cancelled the event, or the caller will handle it. // Return true to indicate that the event wasn't cancelled. if (originalEventMessage == ePaste) { if (aActionTaken) {
*aActionTaken = true;
} return doDefault;
}
// Update the presentation in case the event handler modified the selection, // see bug 602231.
presShell->FlushPendingNotifications(FlushType::Frames); if (presShell->IsDestroying()) { returnfalse;
}
// if the event was not cancelled, do the default copy. If the event was // cancelled, use the data added to the data transfer and copy that instead.
uint32_t count = 0; if (doDefault) { // find the focused node
nsIContent* sourceContent = targetElement.get(); if (targetElement->IsInNativeAnonymousSubtree()) {
sourceContent = targetElement->FindFirstNonChromeOnlyAccessContent();
}
// If it's <input type="password"> and there is no unmasked range or // there is unmasked range but it's collapsed or it'll be masked // automatically, the selected password shouldn't be copied into the // clipboard. if (RefPtr<HTMLInputElement> inputElement =
HTMLInputElement::FromNodeOrNull(sourceContent)) { if (TextEditor* textEditor = inputElement->GetTextEditor()) { if (textEditor->IsPasswordEditor() &&
!textEditor->IsCopyToClipboardAllowed()) { returnfalse;
}
}
}
// when cutting non-editable content, do nothing // XXX this is probably the wrong editable flag to check if (originalEventMessage != eCut || targetElement->IsEditable()) { // get the data from the selection if any if (sel->AreNormalAndCrossShadowBoundaryRangesCollapsed()) { if (aActionTaken) {
*aActionTaken = true;
} returnfalse;
} // XXX Code which decides whether we should copy text with ruby // annotation is currenct depending on whether each range of the // selection is inside a same ruby container. But we really should // expose the full functionality in browser. See bug 1130891. bool withRubyAnnotation = IsSelectionInsideRuby(sel);
nsresult rv = EncodeDocumentWithContextAndPutToClipboard(
sel, doc, *aClipboardType, withRubyAnnotation); if (NS_FAILED(rv)) { returnfalse;
}
} else { returnfalse;
}
} elseif (clipboardData) { // check to see if any data was put on the data transfer.
count = clipboardData->MozItemCount(); if (count) {
nsCOMPtr<nsIClipboard> clipboard(
do_GetService("@mozilla.org/widget/clipboard;1"));
NS_ENSURE_TRUE(clipboard, false);
// put the transferable on the clipboard
WindowContext* settingWindowContext = nullptr; if (aPresShell && aPresShell->GetDocument()) {
settingWindowContext = aPresShell->GetDocument()->GetWindowContext();
}
nsresult rv = clipboard->SetData(transferable, nullptr, *aClipboardType,
settingWindowContext); if (NS_FAILED(rv)) { returnfalse;
}
}
}
// Now that we have copied, update the clipboard commands. This should have // the effect of updating the enabled state of the paste menu item. if (doDefault || count) {
piWindow->UpdateCommands(u"clipboard"_ns); if (aPresShell && aPresShell->GetDocument()) { // Record that a copy to the clipboard was triggered by JS code
aPresShell->GetDocument()->SetClipboardCopyTriggered();
}
}
if (aActionTaken) {
*aActionTaken = true;
} return doDefault;
}
¤ Dauer der Verarbeitung: 0.20 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.