Ejemplo n.º 1
1
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
{
    ASSERT(src);

    if (!src->view() || !src->contentRenderer())
        return false;

    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
    if (!state.m_dragSrc->contains(hitTestResult.innerNode()))
        // The original node being dragged isn't under the drag origin anymore... maybe it was
        // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
        // something that's not actually under the drag origin.
        return false;
    KURL linkURL = hitTestResult.absoluteLinkURL();
    KURL imageURL = hitTestResult.absoluteImageURL();

    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.position());

    m_draggingImageURL = KURL();
    m_sourceDragOperation = srcOp;

    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);

    Clipboard* clipboard = state.m_dragClipboard.get();
    if (state.m_dragType == DragSourceActionDHTML)
        dragImage = clipboard->createDragImage(dragImageOffset);
    if (state.m_dragType == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty())
        // Selection, image, and link drags receive a default set of allowed drag operations that
        // follows from:
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);

    // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
    // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
    if (dragImage) {
        dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
        m_dragOffset = dragImageOffset;
    }

    bool startedDrag = true; // optimism - we almost always manage to start the drag

    Node* node = state.m_dragSrc.get();

    Image* image = getImage(static_cast<Element*>(node));
    if (state.m_dragType == DragSourceActionSelection) {
        if (!clipboard->hasData()) {
            if (enclosingTextFormControl(src->selection()->start()))
                clipboard->writePlainText(src->editor()->selectedText());
            else {
                RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
                ASSERT(selectionRange);

                clipboard->writeRange(selectionRange.get(), src);
            }
        }
        m_client->willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
        if (!dragImage) {
            dragImage = createDragImageForSelection(src);
            dragLoc = dragLocForSelectionDrag(src);
            m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
        }
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
               && (m_dragSourceAction & DragSourceActionImage)) {
        // We shouldn't be starting a drag for an image that can't provide an extension.
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
            m_draggingImageURL = imageURL;
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
        }

        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);

        if (!dragImage) {
            IntRect imageRect = hitTestResult.imageRect();
            imageRect.setLocation(m_page->mainFrame()->view()->rootViewToContents(src->view()->contentsToRootView(imageRect.location())));
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
        } else
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
        if (!clipboard->hasData())
            // Simplify whitespace so the title put on the clipboard resembles what the user sees
            // on the web page. This includes replacing newlines with spaces.
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);

        if (src->selection()->isCaret() && src->selection()->isContentEditable()) {
            // a user can initiate a drag on a link without having any text
            // selected.  In this case, we should expand the selection to
            // the enclosing anchor element
            Position pos = src->selection()->base();
            Node* node = enclosingAnchorElement(pos);
            if (node)
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
        }

        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
        }
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
    } else if (state.m_dragType == DragSourceActionDHTML) {
        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
        m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
    } else {
        // draggableNode() determined an image or link node was draggable, but it turns out the
        // image or link had no URL, so there is nothing to drag.
        startedDrag = false;
    }

    if (dragImage)
        deleteDragImage(dragImage);
    return startedDrag;
}
Ejemplo n.º 2
0
void PakProtocol::listDir(const KURL &url) {
	kdDebug(PAK_DEBUG_ID) << "Entering listDir()" << endl;
	QString path;

	KIO::Error errorNum;
	if ( !checkNewFile( url, path, errorNum ) )
	{
		if ( errorNum == KIO::ERR_CANNOT_OPEN_FOR_READING )
		{
			// If we cannot open, it might be a problem with the archive header (e.g. unsupported format)
			// Therefore give a more specific error message
			error( KIO::ERR_SLAVE_DEFINED,
					i18n( "Could not open the file, probably due to an unsupported file format.\n%1")
					.arg( url.prettyURL() ) );
			return;
		}
		else if ( errorNum != KIO::ERR_IS_DIRECTORY )
		{
			// We have any other error
			error( errorNum, url.prettyURL() );
			return;
		}
		// It's a real dir -> redirect
		KURL redir;
		redir.setPath( url.path() );
		kdDebug( PAK_DEBUG_ID ) << "Ok, redirection to " << redir.url() << endl;
		redirection( redir );
		finished();
		// And let go of the tar file - for people who want to unmount a cdrom after that
		delete _pakFile;
		_pakFile = 0L;
		return;
	}

	if ( path.isEmpty() )
	{
		KURL redir( url.protocol() + QString::fromLatin1( ":/") );
		kdDebug( PAK_DEBUG_ID ) << "url.path()==" << url.path() << endl;
		redir.setPath( url.path() + QString::fromLatin1("/") );
		kdDebug( PAK_DEBUG_ID ) << "ArchiveProtocol::listDir: redirection " << redir.url() << endl;
		redirection( redir );
		finished();
		return;
	}

	path = QString::fromLocal8Bit(remoteEncoding()->encode(path));

	kdDebug( PAK_DEBUG_ID ) << "checkNewFile done" << endl;
	const KArchiveDirectory* root = _pakFile->directory();
	const KArchiveDirectory* dir;
	if (!path.isEmpty() && path != "/")
	{
		kdDebug(PAK_DEBUG_ID) << QString("Looking for entry %1").arg(path) << endl;
		const KArchiveEntry* e = root->entry( path );
		if ( !e )
		{
			error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
			return;
		}
		if ( ! e->isDirectory() )
		{
			error( KIO::ERR_IS_FILE, url.prettyURL() );
			return;
		}
		dir = (KArchiveDirectory*)e;
	} else {
		dir = root;
	}

	QStringList l = dir->entries();
	totalSize( l.count() );

	KIO::UDSEntry entry;
	QStringList::Iterator it = l.begin();
	for( ; it != l.end(); ++it )
	{
		kdDebug(PAK_DEBUG_ID) << (*it) << endl;
		const KArchiveEntry* archiveEntry = dir->entry( (*it) );

		createUDSEntry( archiveEntry, entry );

		listEntry( entry, false );
	}

	listEntry( entry, true ); // ready

	finished();

	kdDebug( PAK_DEBUG_ID ) << "ArchiveProtocol::listDir done" << endl;

	/*kdDebug(PAK_DEBUG_ID) << "Entering listDir()" << endl;
	totalSize(1);		// ONE file (Magic!!)
	KIO::UDSEntry entry;
	createUDSEntry(NULL, entry);
	kdDebug(PAK_DEBUG_ID) << "Giving file away" << endl;
	listEntry(entry, false);
	listEntry(entry, true);		// End
	finished();
	kdDebug(PAK_DEBUG_ID) << "-<> Exiting listDir()" << endl;*/
}
Ejemplo n.º 3
0
JSValue jsStringOrUndefined(ExecState* exec, const KURL& url)
{
    if (url.isNull())
        return jsUndefined();
    return jsString(exec, url.string());
}
Ejemplo n.º 4
0
void WebFrameLoaderClient::dispatchWillPerformClientRedirect(const KURL& url, double delay, double fireDate)
{
    WebFrameLoadDelegate* frameLoadDelegate = m_webFrame->webView()->webFrameLoadDelegate();
    if (frameLoadDelegate)
        frameLoadDelegate->willPerformClientRedirectToURL(m_webFrame, url.string().utf8().data(), delay, fireDate);
}
Ejemplo n.º 5
0
static HGLOBAL createGlobalHDropContent(const KURL& url, String& fileName, SharedBuffer* data)
{
    if (fileName.isEmpty() || !data )
        return 0;

    WCHAR filePath[MAX_PATH];

    if (url.isLocalFile()) {
        String localPath = url.path();
        // windows does not enjoy a leading slash on paths
        if (localPath[0] == '/')
            localPath = localPath.substring(1);
        LPCTSTR localPathStr = localPath.charactersWithNullTermination();
        if (wcslen(localPathStr) + 1 < MAX_PATH)
            wcscpy_s(filePath, MAX_PATH, localPathStr);
        else
            return 0;
    } else {
        WCHAR tempPath[MAX_PATH];
        WCHAR extension[MAX_PATH];
        if (!::GetTempPath(ARRAYSIZE(tempPath), tempPath))
            return 0;
        if (!::PathAppend(tempPath, fileName.charactersWithNullTermination()))
            return 0;
        LPCWSTR foundExtension = ::PathFindExtension(tempPath);
        if (foundExtension) {
            if (wcscpy_s(extension, MAX_PATH, foundExtension))
                return 0;
        } else
            *extension = 0;
        ::PathRemoveExtension(tempPath);
        for (int i = 1; i < 10000; i++) {
            if (swprintf_s(filePath, MAX_PATH, TEXT("%s-%d%s"), tempPath, i, extension) == -1)
                return 0;
            if (!::PathFileExists(filePath))
                break;
        }
        HANDLE tempFileHandle = CreateFile(filePath, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
        if (tempFileHandle == INVALID_HANDLE_VALUE)
            return 0;

        // Write the data to this temp file.
        DWORD written;
        BOOL tempWriteSucceeded = WriteFile(tempFileHandle, data->data(), data->size(), &written, 0);
        CloseHandle(tempFileHandle);
        if (!tempWriteSucceeded)
            return 0;
    }

    SIZE_T dropFilesSize = sizeof(DROPFILES) + (sizeof(WCHAR) * (wcslen(filePath) + 2));
    HGLOBAL memObj = GlobalAlloc(GHND | GMEM_SHARE, dropFilesSize);
    if (!memObj) 
        return 0;

    DROPFILES* dropFiles = (DROPFILES*) GlobalLock(memObj);
    dropFiles->pFiles = sizeof(DROPFILES);
    dropFiles->fWide = TRUE;
    wcscpy((LPWSTR)(dropFiles + 1), filePath);    
    GlobalUnlock(memObj);
    
    return memObj;
}
Ejemplo n.º 6
0
void TrashProtocol::copyOrMove(const KURL &src, const KURL &dest, bool overwrite, CopyOrMove action)
{
    if(src.protocol() == "trash" && dest.isLocalFile())
    {
        // Extracting (e.g. via dnd). Ignore original location stored in info file.
        int trashId;
        QString fileId, relativePath;
        bool ok = TrashImpl::parseURL(src, trashId, fileId, relativePath);
        if(!ok)
        {
            error(KIO::ERR_SLAVE_DEFINED, i18n("Malformed URL %1").arg(src.prettyURL()));
            return;
        }
        const QString destPath = dest.path();
        if(QFile::exists(destPath))
        {
            if(overwrite)
            {
                ok = QFile::remove(destPath);
                Q_ASSERT(ok); // ### TODO
            }
            else
            {
                error(KIO::ERR_FILE_ALREADY_EXIST, destPath);
                return;
            }
        }

        if(action == Move)
        {
            kdDebug() << "calling moveFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
            ok = impl.moveFromTrash(destPath, trashId, fileId, relativePath);
        }
        else
        { // Copy
            kdDebug() << "calling copyFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
            ok = impl.copyFromTrash(destPath, trashId, fileId, relativePath);
        }
        if(!ok)
        {
            error(impl.lastErrorCode(), impl.lastErrorMessage());
        }
        else
        {
            if(action == Move && relativePath.isEmpty())
                (void)impl.deleteInfo(trashId, fileId);
            finished();
        }
        return;
    }
    else if(src.isLocalFile() && dest.protocol() == "trash")
    {
        QString dir = dest.directory();
        // kdDebug() << "trashing a file to " << dir << endl;
        // Trashing a file
        // We detect the case where this isn't normal trashing, but
        // e.g. if kwrite tries to save (moving tempfile over destination)
        if(dir.length() <= 1 && src.fileName() == dest.fileName()) // new toplevel entry
        {
            const QString srcPath = src.path();
            // In theory we should use TrashImpl::parseURL to give the right filename to createInfo,
            // in case the trash URL didn't contain the same filename as srcPath.
            // But this can only happen with copyAs/moveAs, not available in the GUI
            // for the trash (New/... or Rename from iconview/listview).
            int trashId;
            QString fileId;
            if(!impl.createInfo(srcPath, trashId, fileId))
            {
                error(impl.lastErrorCode(), impl.lastErrorMessage());
            }
            else
            {
                bool ok;
                if(action == Move)
                {
                    kdDebug() << "calling moveToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
                    ok = impl.moveToTrash(srcPath, trashId, fileId);
                }
                else
                { // Copy
                    kdDebug() << "calling copyToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
                    ok = impl.copyToTrash(srcPath, trashId, fileId);
                }
                if(!ok)
                {
                    (void)impl.deleteInfo(trashId, fileId);
                    error(impl.lastErrorCode(), impl.lastErrorMessage());
                }
                else
                {
                    // Inform caller of the final URL. Used by konq_undo.
                    const KURL url = impl.makeURL(trashId, fileId, QString::null);
                    setMetaData("trashURL-" + srcPath, url.url());
                    finished();
                }
            }
            return;
        }
        else
        {
            kdDebug() << "returning KIO::ERR_ACCESS_DENIED, it's not allowed to add a file to an existing trash directory" << endl;
            // It's not allowed to add a file to an existing trash directory.
            error(KIO::ERR_ACCESS_DENIED, dest.prettyURL());
            return;
        }
    }
    else
        error(KIO::ERR_UNSUPPORTED_ACTION, "should never happen");
}
Ejemplo n.º 7
0
void HistoryDialog::slotOpenURLRequest(const KURL &url, const KParts::URLArgs &/*args*/)
{
	kdDebug(14310) << k_funcinfo << "url=" << url.url() << endl;
	new KRun(url, 0, false); // false = non-local files
}
Ejemplo n.º 8
0
void AnnotationOutput::readAnnotations()
{
  if (!Project::ref()->hasProject())
  {
    m_allAnnotations->clear();
    m_yourAnnotations->clear();
    m_yourAnnotationsNum = 0;
    setTabLabel(m_yourAnnotations, i18n("For You"));
    return;
  }

  KURL baseURL = Project::ref()->projectBaseURL();
  QStringList openedItems;
  QListViewItem *item = m_allAnnotations->firstChild();
  while (item)
  {
    if (item->isOpen())
        openedItems += item->text(0);
    item = item->nextSibling();
  }
  m_allAnnotations->clear();
  m_annotatedFileItems.clear();
  m_fileNames.clear();
  m_lines.clear();

  QStringList yourOpenedItems;
  item = m_yourAnnotations->firstChild();
  while (item)
  {
    if (item->isOpen())
        yourOpenedItems += item->text(0);
    item = item->nextSibling();
  }

  m_yourAnnotations->clear();
  m_yourFileItems.clear();
  m_yourFileNames.clear();
  m_yourLines.clear();
  m_yourAnnotationsNum = 0;

  QDomElement annotationElement = Project::ref()->dom()->firstChild().firstChild().namedItem("annotations").toElement();
  if (annotationElement.isNull())
    return;
  QString yourself = Project::ref()->yourself().lower();
  QStringList roles = Project::ref()->yourRoles();
  QDomNodeList nodes = annotationElement.childNodes();
  int count = nodes.count();
  for (int i = 0; i < count; i++)
  {
    QDomElement el = nodes.item(i).toElement();
    QString fileName = el.attribute("url");
    KURL u = baseURL;
    QuantaCommon::setUrl(u, fileName);
    u = QExtFileInfo::toAbsolute(u, baseURL);
    if (Project::ref()->contains(u))
    {
      bool ok;
      int line = el.attribute("line").toInt(&ok, 10);
      QString text = el.attribute("text");
      QString receiver = el.attribute("receiver");
      text.replace('\n',' ');
      QString lineText = QString("%1").arg(line);
      if (lineText.length() < 20)
      {
        QString s;
        s.fill('0', 20 - lineText.length());
        lineText.prepend(s);
      }
      KListViewItem *fileIt = m_annotatedFileItems[fileName];
      if (!fileIt)
      {
        fileIt = new KListViewItem(m_allAnnotations, fileName);
        m_annotatedFileItems.insert(fileName, fileIt);
        m_fileNames[fileIt] = u.url();
      }
      KListViewItem *it = new KListViewItem(fileIt, fileIt, text, lineText);
      if (openedItems.contains(fileName))
        fileIt->setOpen(true);
      m_fileNames[it] = u.url();
      m_lines[it] = line;
   
      if (!yourself.isEmpty() && (receiver == yourself || roles.contains(receiver)))
      {
        m_yourAnnotationsNum++;
        KListViewItem *fileIt = m_yourFileItems[fileName];
        if (!fileIt)
        {
          fileIt = new KListViewItem(m_yourAnnotations, fileName);
          m_yourFileItems.insert(fileName, fileIt);
          m_yourFileNames[fileIt] = u.url();
        }
        KListViewItem *it = new KListViewItem(fileIt, fileIt, text, lineText);
        if (yourOpenedItems.contains(fileName))
          fileIt->setOpen(true);
        m_yourFileNames[it] = u.url();
        m_yourLines[it] = line;
      }
    } else
    {
      annotationElement.removeChild(el);
    }
  }
  if (m_yourAnnotationsNum > 0)
  {
    setTabLabel(m_yourAnnotations, i18n("For You: %1").arg(m_yourAnnotationsNum));
  } else
  {
    setTabLabel(m_yourAnnotations, i18n("For You"));
  }
}
Ejemplo n.º 9
0
ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, FetchRequest& request)
{
    ASSERT(request.options().synchronousPolicy == RequestAsynchronously || type == Resource::Raw);

    TRACE_EVENT0("blink", "ResourceFetcher::requestResource");

    KURL url = request.resourceRequest().url();

    WTF_LOG(ResourceLoading, "ResourceFetcher::requestResource '%s', charset '%s', priority=%d, type=%s", url.elidedString().latin1().data(), request.charset().latin1().data(), request.priority(), ResourceTypeName(type));

    // If only the fragment identifiers differ, it is the same resource.
    url = MemoryCache::removeFragmentIdentifierIfNeeded(url);

    if (!url.isValid())
        return 0;

    if (!canRequest(type, url, request.options(), request.originRestriction()))
        return 0;

    if (LocalFrame* f = frame())
        f->loaderClient()->dispatchWillRequestResource(&request);

    // See if we can use an existing resource from the cache.
    ResourcePtr<Resource> resource = memoryCache()->resourceForURL(url);

    const RevalidationPolicy policy = determineRevalidationPolicy(type, request, resource.get());
    switch (policy) {
    case Reload:
        memoryCache()->remove(resource.get());
        // Fall through
    case Load:
        resource = createResourceForLoading(type, request, request.charset());
        break;
    case Revalidate:
        resource = createResourceForRevalidation(request, resource.get());
        break;
    case Use:
        memoryCache()->updateForAccess(resource.get());
        break;
    }

    if (!resource)
        return 0;

    if (!resource->hasClients())
        m_deadStatsRecorder.update(policy);

    if (policy != Use)
        resource->setIdentifier(createUniqueIdentifier());

    ResourceLoadPriority priority = loadPriority(type, request);
    if (priority != resource->resourceRequest().priority()) {
        resource->mutableResourceRequest().setPriority(priority);
        resource->didChangePriority(priority, 0);
    }

    if (resourceNeedsLoad(resource.get(), request, policy)) {
        if (!shouldLoadNewResource(type)) {
            if (memoryCache()->contains(resource.get()))
                memoryCache()->remove(resource.get());
            return 0;
        }

        resource->load(this, request.options());

        // For asynchronous loads that immediately fail, it's sufficient to return a
        // null Resource, as it indicates that something prevented the load from starting.
        // If there's a network error, that failure will happen asynchronously. However, if
        // a sync load receives a network error, it will have already happened by this point.
        // In that case, the requester should have access to the relevant ResourceError, so
        // we need to return a non-null Resource.
        if (resource->errorOccurred()) {
            if (memoryCache()->contains(resource.get()))
                memoryCache()->remove(resource.get());
            return 0;
        }
    }

    requestLoadStarted(resource.get(), request, policy == Use ? ResourceLoadingFromCache : ResourceLoadingFromNetwork);

    ASSERT(resource->url() == url.string());
    m_documentResources.set(resource->url(), resource);
    return resource;
}
Ejemplo n.º 10
0
KURL InspectorAgent::inspectedURLWithoutFragment() const
{
    KURL url = inspectedURL();
    url.removeFragmentIdentifier();
    return url;
}
Ejemplo n.º 11
0
void HistoryItem::setURL(const KURL& url)
{
    setURLString(url.string());
    clearDocumentState();
}
Ejemplo n.º 12
0
IconURL IconController::defaultURL(IconType iconType)
{
    // Don't return a favicon iconURL unless we're http or https
    KURL documentURL = m_frame->document()->url();
    if (!documentURL.protocolIsInHTTPFamily())
        return IconURL();

    KURL url;
    bool couldSetProtocol = url.setProtocol(documentURL.protocol());
    ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
    url.setHost(documentURL.host());
    if (documentURL.hasPort())
        url.setPort(documentURL.port());

    if (iconType == Favicon) {
        url.setPath("/favicon.ico");
        return IconURL::defaultIconURL(url, Favicon);
    }
#if ENABLE(TOUCH_ICON_LOADING)
    if (iconType == TouchPrecomposedIcon) {
        url.setPath("/apple-touch-icon-precomposed.png");
        return IconURL::defaultIconURL(url, TouchPrecomposedIcon);
    }
    if (iconType == TouchIcon) {
        url.setPath("/apple-touch-icon.png");
        return IconURL::defaultIconURL(url, TouchIcon);
    }
#endif
    return IconURL();
}
Ejemplo n.º 13
0
void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r)
{
    KURL url = request().url();
    const String& mimeType = r.mimeType();
    
    switch (contentPolicy) {
    case PolicyUse: {
        // Prevent remote web archives from loading because they can claim to be from any domain and thus avoid cross-domain security checks (4120255).
        bool isRemote = !url.isLocalFile();
        isRemote = isRemote && !m_substituteData.isValid();
        bool isRemoteWebArchive = isRemote && equalIgnoringCase("application/x-webarchive", mimeType);
        if (!frameLoader()->canShowMIMEType(mimeType) || isRemoteWebArchive) {
            frameLoader()->cannotShowMIMEType(r);
            // Check reachedTerminalState since the load may have already been cancelled inside of _handleUnimplementablePolicyWithErrorCode::.
            if (!reachedTerminalState())
                stopLoadingForPolicyChange();
            return;
        }
        break;
    }

    case PolicyDownload:
        frameLoader()->client()->download(m_handle.get(), request(), r);
        receivedError(interruptionForPolicyChangeError());
        return;

    case PolicyIgnore:
        stopLoadingForPolicyChange();
        return;
    
    default:
        ASSERT_NOT_REACHED();
    }

    RefPtr<MainResourceLoader> protect(this);

    if (r.isHTTP()) {
        int status = r.httpStatusCode();
        if (status < 200 || status >= 300) {
            bool hostedByObject = frameLoader()->isHostedByObjectElement();

            frameLoader()->handleFallbackContent();
            // object elements are no longer rendered after we fallback, so don't
            // keep trying to process data from their load

            if (hostedByObject)
                cancel();
        }
    }

    // we may have cancelled this load as part of switching to fallback content
    if (!reachedTerminalState())
        ResourceLoader::didReceiveResponse(r);

    if (frameLoader() && !frameLoader()->isStopping())
        if (m_substituteData.isValid()) {
            if (m_substituteData.content()->size())
                didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true);
            if (frameLoader() && !frameLoader()->isStopping()) 
                didFinishLoading();
        } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->representationExistsForURLScheme(url.protocol()))
            didFinishLoading();
}
Ejemplo n.º 14
0
static bool shouldLoadAsEmptyDocument(const KURL& URL)
{
    return URL.isEmpty() || equalIgnoringCase(String(URL.protocol()), "about");
}
Ejemplo n.º 15
0
void HTMLAppletElement::updateWidget(PluginCreationOption)
{
    setNeedsWidgetUpdate(false);
    // FIXME: This should ASSERT isFinishedParsingChildren() instead.
    if (!isFinishedParsingChildren())
        return;

    RenderEmbeddedObject* renderer = renderEmbeddedObject();

    Frame* frame = document().frame();
    ASSERT(frame);

    LayoutUnit contentWidth = renderer->style()->width().isFixed() ? LayoutUnit(renderer->style()->width().value()) :
        renderer->width() - renderer->borderAndPaddingWidth();
    LayoutUnit contentHeight = renderer->style()->height().isFixed() ? LayoutUnit(renderer->style()->height().value()) :
        renderer->height() - renderer->borderAndPaddingHeight();

    Vector<String> paramNames;
    Vector<String> paramValues;

    paramNames.append("code");
    paramValues.append(getAttribute(codeAttr).string());

    const AtomicString& codeBase = getAttribute(codebaseAttr);
    if (!codeBase.isNull()) {
        KURL codeBaseURL = document().completeURL(codeBase);
        if (!document().securityOrigin()->canDisplay(codeBaseURL)) {
            FrameLoader::reportLocalLoadFailed(frame, codeBaseURL.string());
            return;
        }
        const char javaAppletMimeType[] = "application/x-java-applet";
        if (!document().contentSecurityPolicy()->allowObjectFromSource(codeBaseURL)
            || !document().contentSecurityPolicy()->allowPluginType(javaAppletMimeType, javaAppletMimeType, codeBaseURL))
            return;
        paramNames.append("codeBase");
        paramValues.append(codeBase.string());
    }

    const AtomicString& name = document().isHTMLDocument() ? getNameAttribute() : getIdAttribute();
    if (!name.isNull()) {
        paramNames.append("name");
        paramValues.append(name.string());
    }

    const AtomicString& archive = getAttribute(archiveAttr);
    if (!archive.isNull()) {
        paramNames.append("archive");
        paramValues.append(archive.string());
    }

    paramNames.append("baseURL");
    KURL baseURL = document().baseURL();
    paramValues.append(baseURL.string());

    const AtomicString& mayScript = getAttribute(mayscriptAttr);
    if (!mayScript.isNull()) {
        paramNames.append("mayScript");
        paramValues.append(mayScript.string());
    }

    for (Node* child = firstChild(); child; child = child->nextSibling()) {
        if (!child->hasTagName(paramTag))
            continue;

        HTMLParamElement* param = toHTMLParamElement(child);
        if (param->name().isEmpty())
            continue;

        paramNames.append(param->name());
        paramValues.append(param->value());
    }

    RefPtr<Widget> widget;
    if (frame->loader()->allowPlugins(AboutToInstantiatePlugin))
        widget = frame->loader()->client()->createJavaAppletWidget(roundedIntSize(LayoutSize(contentWidth, contentHeight)), this, baseURL, paramNames, paramValues);

    if (!widget) {
        if (!renderer->showsUnavailablePluginIndicator())
            renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
        return;
    }
    frame->loader()->setContainsPlugins();
    renderer->setWidget(widget);
}
Ejemplo n.º 16
0
// static
bool MixedContentChecker::shouldBlockFetch(LocalFrame* frame, WebURLRequest::RequestContext requestContext, WebURLRequest::FrameType frameType, const KURL& url, MixedContentChecker::ReportingStatus reportingStatus)
{
    Frame* effectiveFrame = effectiveFrameForFrameType(frame, frameType);
    Frame* mixedFrame = inWhichFrameIsContentMixed(effectiveFrame, frameType, url);
    if (!mixedFrame)
        return false;

    MixedContentChecker::count(mixedFrame, requestContext);

    Settings* settings = mixedFrame->settings();
    // Use the current local frame's client; the embedder doesn't
    // distinguish mixed content signals from different frames on the
    // same page.
    FrameLoaderClient* client = frame->loader().client();
    SecurityOrigin* securityOrigin = mixedFrame->securityContext()->securityOrigin();
    bool allowed = false;

    // If we're in strict mode, we'll automagically fail everything, and intentionally skip
    // the client checks in order to prevent degrading the site's security UI.
    bool strictMode = mixedFrame->securityContext()->shouldEnforceStrictMixedContentChecking() || settings->strictMixedContentChecking();

    ContextType contextType = contextTypeFromContext(requestContext, mixedFrame);

    // If we're loading the main resource of a subframe, we need to take a close look at the loaded URL.
    // If we're dealing with a CORS-enabled scheme, then block mixed frames as active content. Otherwise,
    // treat frames as passive content.
    //
    // FIXME: Remove this temporary hack once we have a reasonable API for launching external applications
    // via URLs. http://crbug.com/318788 and https://crbug.com/393481
    if (frameType == WebURLRequest::FrameTypeNested && !SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(url.protocol()))
        contextType = ContextTypeOptionallyBlockable;

    switch (contextType) {
    case ContextTypeOptionallyBlockable:
        allowed = !strictMode && client->allowDisplayingInsecureContent(settings && settings->allowDisplayOfInsecureContent(), url);
        if (allowed)
            client->didDisplayInsecureContent();
        break;

    case ContextTypeBlockable: {
        // Strictly block subresources in subframes, unless all insecure
        // content is allowed.
        if (!settings->allowRunningOfInsecureContent() && requestIsSubframeSubresource(effectiveFrame, frameType)) {
            UseCounter::count(mixedFrame, UseCounter::BlockableMixedContentInSubframeBlocked);
            allowed = false;
            break;
        }

        bool shouldAskEmbedder = !strictMode && settings && (!settings->strictlyBlockBlockableMixedContent() || settings->allowRunningOfInsecureContent());
        allowed = shouldAskEmbedder && client->allowRunningInsecureContent(settings && settings->allowRunningOfInsecureContent(), securityOrigin, url);
        if (allowed) {
            client->didRunInsecureContent(securityOrigin, url);
            UseCounter::count(mixedFrame, UseCounter::MixedContentBlockableAllowed);
        }
        break;
    }

    case ContextTypeShouldBeBlockable:
        allowed = !strictMode;
        if (allowed)
            client->didDisplayInsecureContent();
        break;
    case ContextTypeNotMixedContent:
        ASSERT_NOT_REACHED();
        break;
    };

    if (reportingStatus == SendReport)
        logToConsoleAboutFetch(frame, mainResourceUrlForFrame(mixedFrame), url, requestContext, allowed);
    return !allowed;
}
Ejemplo n.º 17
0
PassRefPtr<LegacyWebArchive> LegacyWebArchive::create(const String& markupString, Frame* frame, Vector<Node*>& nodes)
{
    ASSERT(frame);
    
    const ResourceResponse& response = frame->loader()->documentLoader()->response();
    KURL responseURL = response.url();
    
    // it's possible to have a response without a URL here
    // <rdar://problem/5454935>
    if (responseURL.isNull())
        responseURL = KURL("");
        
    PassRefPtr<ArchiveResource> mainResource = ArchiveResource::create(utf8Buffer(markupString), responseURL, response.mimeType(), "UTF-8", frame->tree()->name());

    Vector<PassRefPtr<LegacyWebArchive> > subframeArchives;
    Vector<PassRefPtr<ArchiveResource> > subresources;
    HashSet<KURL> uniqueSubresources;
    
    Vector<Node*>::iterator it = nodes.begin();
    Vector<Node*>::iterator end = nodes.end();
    
    for (; it != end; ++it) {
        Frame* childFrame;
        if (((*it)->hasTagName(HTMLNames::frameTag) || (*it)->hasTagName(HTMLNames::iframeTag) || (*it)->hasTagName(HTMLNames::objectTag)) &&
             (childFrame = static_cast<HTMLFrameOwnerElement*>(*it)->contentFrame())) {
            RefPtr<LegacyWebArchive> subframeArchive;
            if (Document* document = childFrame->document())
                subframeArchive = LegacyWebArchive::create(document);
            else
                subframeArchive = create(childFrame);
            
            if (subframeArchive)
                subframeArchives.append(subframeArchive);
            else
                LOG_ERROR("Unabled to archive subframe %s", childFrame->tree()->name().string().utf8().data());
        } else {
            ListHashSet<KURL> subresourceURLs;
            (*it)->getSubresourceURLs(subresourceURLs);
            
            DocumentLoader* documentLoader = frame->loader()->documentLoader();
            ListHashSet<KURL>::iterator iterEnd = subresourceURLs.end();
            for (ListHashSet<KURL>::iterator iter = subresourceURLs.begin(); iter != iterEnd; ++iter) {
                const KURL& subresourceURL = *iter;
                if (uniqueSubresources.contains(subresourceURL))
                    continue;

                uniqueSubresources.add(subresourceURL);

                RefPtr<ArchiveResource> resource = documentLoader->subresource(subresourceURL);
                if (resource) {
                    subresources.append(resource.release());
                    continue;
                }

                CachedResource *cachedResource = cache()->resourceForURL(subresourceURL);
                if (cachedResource) {
                    resource = ArchiveResource::create(cachedResource->data(), subresourceURL, cachedResource->response());
                    if (resource) {
                        subresources.append(resource.release());
                        continue;
                    }
                }

                // FIXME: should do something better than spew to console here
                LOG_ERROR("Failed to archive subresource for %s", subresourceURL.string().utf8().data());
            }
        }
    }
    
    return create(mainResource, subresources, subframeArchives);
}
Ejemplo n.º 18
0
void ArgumentCoder<KURL>::encode(ArgumentEncoder& encoder, const KURL& result)
{
    encoder << result.string();
}
Ejemplo n.º 19
0
void TrashProtocol::listDir(const KURL &url)
{
    INIT_IMPL;
    kdDebug() << "listdir: " << url << endl;
    if(url.path().length() <= 1)
    {
        listRoot();
        return;
    }
    int trashId;
    QString fileId;
    QString relativePath;
    bool ok = TrashImpl::parseURL(url, trashId, fileId, relativePath);
    if(!ok)
    {
        error(KIO::ERR_SLAVE_DEFINED, i18n("Malformed URL %1").arg(url.prettyURL()));
        return;
    }
    // was: const QString physicalPath = impl.physicalPath( trashId, fileId, relativePath );

    // Get info for deleted directory - the date of deletion and orig path will be used
    // for all the items in it, and we need the physicalPath.
    TrashedFileInfo info;
    ok = impl.infoForFile(trashId, fileId, info);
    if(!ok || info.physicalPath.isEmpty())
    {
        error(impl.lastErrorCode(), impl.lastErrorMessage());
        return;
    }
    if(!relativePath.isEmpty())
    {
        info.physicalPath += "/";
        info.physicalPath += relativePath;
    }

    // List subdir. Can't use kio_file here since we provide our own info...
    kdDebug() << k_funcinfo << "listing " << info.physicalPath << endl;
    QStrList entryNames = impl.listDir(info.physicalPath);
    totalSize(entryNames.count());
    KIO::UDSEntry entry;
    QStrListIterator entryIt(entryNames);
    for(; entryIt.current(); ++entryIt)
    {
        QString fileName = QFile::decodeName(entryIt.current());
        if(fileName == "..")
            continue;
        const QString filePath = info.physicalPath + "/" + fileName;
        // shouldn't be necessary
        // const QString url = TrashImpl::makeURL( trashId, fileId, relativePath + "/" + fileName );
        entry.clear();
        TrashedFileInfo infoForItem(info);
        infoForItem.origPath += '/';
        infoForItem.origPath += fileName;
        if(ok && createUDSEntry(filePath, fileName, QString::null /*url*/, entry, infoForItem))
        {
            listEntry(entry, false);
        }
    }
    entry.clear();
    listEntry(entry, true);
    finished();
}
Ejemplo n.º 20
0
void HTMLLinkElement::process()
{
    if (!inDocument() || m_isInShadowTree) {
        ASSERT(!m_sheet);
        return;
    }

    String type = m_type.lower();
    KURL url = getNonEmptyURLAttribute(hrefAttr);

    if (!m_linkLoader.loadLink(m_relAttribute, type, m_sizes->toString(), url, document()))
        return;

    if ((m_disabledState != Disabled) && m_relAttribute.isStyleSheet()
        && document()->frame() && url.isValid()) {
        
        String charset = getAttribute(charsetAttr);
        if (charset.isEmpty() && document()->frame())
            charset = document()->charset();
        
        if (m_cachedSheet) {
            removePendingSheet();
            m_cachedSheet->removeClient(this);
            m_cachedSheet = 0;
        }

        if (!shouldLoadLink())
            return;

        m_loading = true;

        bool mediaQueryMatches = true;
        if (!m_media.isEmpty()) {
            RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(document());
            RefPtr<MediaQuerySet> media = MediaQuerySet::createAllowingDescriptionSyntax(m_media);
            MediaQueryEvaluator evaluator(document()->frame()->view()->mediaType(), document()->frame(), documentStyle.get());
            mediaQueryMatches = evaluator.eval(media.get());
        }

        // Don't hold up render tree construction and script execution on stylesheets
        // that are not needed for the rendering at the moment.
        bool blocking = mediaQueryMatches && !isAlternate();
        addPendingSheet(blocking ? Blocking : NonBlocking);

        // Load stylesheets that are not needed for the rendering immediately with low priority.
        ResourceLoadPriority priority = blocking ? ResourceLoadPriorityUnresolved : ResourceLoadPriorityVeryLow;
        CachedResourceRequest request(ResourceRequest(document()->completeURL(url)), charset, priority);
        request.setInitiator(this);
        m_cachedSheet = document()->cachedResourceLoader()->requestCSSStyleSheet(request);
        
        if (m_cachedSheet)
            m_cachedSheet->addClient(this);
        else {
            // The request may have been denied if (for example) the stylesheet is local and the document is remote.
            m_loading = false;
            removePendingSheet();
        }
    } else if (m_sheet) {
        // we no longer contain a stylesheet, e.g. perhaps rel or type was changed
        clearSheet();
        document()->styleResolverChanged(DeferRecalcStyle);
    }
}
void WebSocketHandshake::setURL(const KURL& url)
{
    m_url = url.copy();
}
Ejemplo n.º 22
0
// static
bool MixedContentChecker::shouldBlockFetch(
    LocalFrame* frame,
    WebURLRequest::RequestContext requestContext,
    WebURLRequest::FrameType frameType,
    ResourceRequest::RedirectStatus redirectStatus,
    const KURL& url,
    MixedContentChecker::ReportingStatus reportingStatus) {
  Frame* effectiveFrame = effectiveFrameForFrameType(frame, frameType);
  Frame* mixedFrame =
      inWhichFrameIsContentMixed(effectiveFrame, frameType, url);
  if (!mixedFrame)
    return false;

  MixedContentChecker::count(mixedFrame, requestContext);
  if (ContentSecurityPolicy* policy =
          frame->securityContext()->contentSecurityPolicy())
    policy->reportMixedContent(url, redirectStatus);

  Settings* settings = mixedFrame->settings();
  // Use the current local frame's client; the embedder doesn't distinguish
  // mixed content signals from different frames on the same page.
  FrameLoaderClient* client = frame->loader().client();
  SecurityOrigin* securityOrigin =
      mixedFrame->securityContext()->getSecurityOrigin();
  bool allowed = false;

  // If we're in strict mode, we'll automagically fail everything, and
  // intentionally skip the client checks in order to prevent degrading the
  // site's security UI.
  bool strictMode = mixedFrame->securityContext()->getInsecureRequestPolicy() &
                        kBlockAllMixedContent ||
                    settings->strictMixedContentChecking();

  WebMixedContent::ContextType contextType =
      WebMixedContent::contextTypeFromRequestContext(
          requestContext, settings->strictMixedContentCheckingForPlugin());

  // If we're loading the main resource of a subframe, we need to take a close
  // look at the loaded URL. If we're dealing with a CORS-enabled scheme, then
  // block mixed frames as active content. Otherwise, treat frames as passive
  // content.
  //
  // FIXME: Remove this temporary hack once we have a reasonable API for
  // launching external applications via URLs. http://crbug.com/318788 and
  // https://crbug.com/393481
  if (frameType == WebURLRequest::FrameTypeNested &&
      !SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(url.protocol()))
    contextType = WebMixedContent::ContextType::OptionallyBlockable;

  switch (contextType) {
    case WebMixedContent::ContextType::OptionallyBlockable:
      client->passiveInsecureContentFound(url);
      allowed = !strictMode;
      if (allowed)
        client->didDisplayInsecureContent();
      break;

    case WebMixedContent::ContextType::Blockable: {
      // Strictly block subresources that are mixed with respect to their
      // subframes, unless all insecure content is allowed. This is to avoid the
      // following situation: https://a.com embeds https://b.com, which loads a
      // script over insecure HTTP. The user opts to allow the insecure content,
      // thinking that they are allowing an insecure script to run on
      // https://a.com and not realizing that they are in fact allowing an
      // insecure script on https://b.com.
      if (!settings->allowRunningOfInsecureContent() &&
          requestIsSubframeSubresource(effectiveFrame, frameType) &&
          isMixedContent(frame->securityContext()->getSecurityOrigin(), url)) {
        UseCounter::count(mixedFrame,
                          UseCounter::BlockableMixedContentInSubframeBlocked);
        allowed = false;
        break;
      }

      bool shouldAskEmbedder =
          !strictMode && settings &&
          (!settings->strictlyBlockBlockableMixedContent() ||
           settings->allowRunningOfInsecureContent());
      allowed = shouldAskEmbedder &&
                client->allowRunningInsecureContent(
                    settings && settings->allowRunningOfInsecureContent(),
                    securityOrigin, url);
      if (allowed) {
        client->didRunInsecureContent(securityOrigin, url);
        UseCounter::count(mixedFrame, UseCounter::MixedContentBlockableAllowed);
      }
      break;
    }

    case WebMixedContent::ContextType::ShouldBeBlockable:
      allowed = !strictMode;
      if (allowed)
        client->didDisplayInsecureContent();
      break;
    case WebMixedContent::ContextType::NotMixedContent:
      NOTREACHED();
      break;
  };

  if (reportingStatus == SendReport) {
    logToConsoleAboutFetch(frame, mainResourceUrlForFrame(mixedFrame), url,
                           requestContext, allowed);
  }
  return !allowed;
}
Ejemplo n.º 23
0
String WebFrameLoaderClient::userAgent(const KURL& url)
{
    return m_webFrame->webView()->userAgentForKURL(url.string().utf8().data());
}
Ejemplo n.º 24
0
DragImageRef WebDragClient::createDragImageForLink(KURL& url, const String& inLabel, Frame* frame)
{
    // This is more or less an exact match for the Mac OS X code.

    const Font* labelFont;
    const Font* urlFont;

    if (frame->settings() && frame->settings()->fontRenderingMode() == AlternateRenderingMode) {
        static const Font alternateRenderingModeLabelFont = dragLabelFont(DRAG_LINK_LABEL_FONT_SIZE, true, AlternateRenderingMode);
        static const Font alternateRenderingModeURLFont = dragLabelFont(DRAG_LINK_URL_FONT_SIZE, false, AlternateRenderingMode);
        labelFont = &alternateRenderingModeLabelFont;
        urlFont = &alternateRenderingModeURLFont;
    } else {
        static const Font normalRenderingModeLabelFont = dragLabelFont(DRAG_LINK_LABEL_FONT_SIZE, true, NormalRenderingMode);
        static const Font normalRenderingModeURLFont = dragLabelFont(DRAG_LINK_URL_FONT_SIZE, false, NormalRenderingMode);
        labelFont = &normalRenderingModeLabelFont;
        urlFont = &normalRenderingModeURLFont;
    }

    bool drawURLString = true;
    bool clipURLString = false;
    bool clipLabelString = false;

    String urlString = url.string(); 
    String label = inLabel;
    if (label.isEmpty()) {
        drawURLString = false;
        label = urlString;
    }

    //First step in drawing the link drag image width
    TextRun labelRun(label.impl());
    TextRun urlRun(urlString.impl());
    IntSize labelSize(labelFont->width(labelRun), labelFont->ascent() + labelFont->descent());

    if (labelSize.width() > MAX_DRAG_LABEL_STRING_WIDTH){
        labelSize.setWidth(MAX_DRAG_LABEL_STRING_WIDTH);
        clipLabelString = true;
    }
    
    IntSize urlStringSize;
    IntSize imageSize(labelSize.width() + DRAG_LABEL_BORDER_X * 2, 
                      labelSize.height() + DRAG_LABEL_BORDER_Y * 2);

    if (drawURLString) {
        urlStringSize.setWidth(urlFont->width(urlRun));
        urlStringSize.setHeight(urlFont->ascent() + urlFont->descent()); 
        imageSize.setHeight(imageSize.height() + urlStringSize.height());
        if (urlStringSize.width() > MAX_DRAG_LABEL_STRING_WIDTH) {
            imageSize.setWidth(MAX_DRAG_LABEL_WIDTH);
            clipURLString = true;
        } else {
            imageSize.setWidth(std::max(labelSize.width(), urlStringSize.width()) + DRAG_LABEL_BORDER_X * 2);
        }
    }

    // We now know how big the image needs to be, so we create and
    // fill the background
    HBITMAP image = 0;
    HDC dc = GetDC(0);
    HDC workingDC = CreateCompatibleDC(dc);
    if (!workingDC) {
        ReleaseDC(0, dc);
        return 0;
    }

    PlatformGraphicsContext* contextRef;
    image = allocImage(workingDC, imageSize, &contextRef);
    if (!image) {
        DeleteDC(workingDC);
        ReleaseDC(0, dc);
        return 0;
    }
        
    ::SelectObject(workingDC, image);
    GraphicsContext context(contextRef);
    // On Mac alpha is {0.7, 0.7, 0.7, 0.8}, however we can't control alpha
    // for drag images on win, so we use 1
    static const Color backgroundColor(140, 140, 140);
    static const IntSize radii(DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS);
    IntRect rect(0, 0, imageSize.width(), imageSize.height());
    context.fillRoundedRect(rect, radii, radii, radii, radii, backgroundColor, DeviceColorSpace);
 
    // Draw the text
    static const Color topColor(0, 0, 0, 255); //original alpha = 0.75
    static const Color bottomColor(255, 255, 255, 127); //original alpha = 0.5
    if (drawURLString) {
        if (clipURLString)
            urlString = StringTruncator::rightTruncate(urlString, imageSize.width() - (DRAG_LABEL_BORDER_X * 2.0f), *urlFont, false);
        IntPoint textPos(DRAG_LABEL_BORDER_X, imageSize.height() - (DRAG_LABEL_BORDER_Y_OFFSET + urlFont->descent()));
        WebCoreDrawDoubledTextAtPoint(context, urlString, textPos, *urlFont, topColor, bottomColor);
    }
    
    if (clipLabelString)
        label = StringTruncator::rightTruncate(label, imageSize.width() - (DRAG_LABEL_BORDER_X * 2.0f), *labelFont, false);

    IntPoint textPos(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y + labelFont->pixelSize());
    WebCoreDrawDoubledTextAtPoint(context, label, textPos, *labelFont, topColor, bottomColor);

    deallocContext(contextRef);
    DeleteDC(workingDC);
    ReleaseDC(0, dc);
    return image;
}
WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode)
    : m_scriptURL(scriptURL.copy())
    , m_userAgent(userAgent.copy())
    , m_sourceCode(sourceCode.copy())
{
}
Ejemplo n.º 26
0
//-----GetLocalFileName---------------------------------------------------------
// Sets the local filename and opens the file
// returns false if the user hits cancel
bool CFileDlg::GetLocalFileName()
{
  QString f;
  bool bValid = false;

  QTextCodec *codec = UserCodec::codecForProtoUser(m_szId, m_nPPID);
  
  // Get the local filename and open it, loop until valid or cancel
  while(!bValid)
  {
#ifdef USE_KDE
    KURL u = KFileDialog::getSaveURL(
          QString(QDir::homeDirPath() + "/" + codec->toUnicode(m_sFileInfo.szName)),
          QString::null, this);
    f = u.path();
#else
    f = QFileDialog::getSaveFileName(
          QString(QDir::homeDirPath() + "/" + codec->toUnicode(m_sFileInfo.szName)),
          QString::null, this);
#endif
    if (f.isNull()) return (false);
    struct stat buf;
    int nFlags = O_WRONLY;
    m_nFilePos = 0;
    if (stat(QFile::encodeName(f), &buf) == 0)  // file already exists
    {
      if ((unsigned long)buf.st_size >= m_sFileInfo.nSize)
      {
        if(QueryUser(this, tr("File already exists and is at least as big as the incoming file."), tr("Overwrite"), tr("Cancel")))
          nFlags |= O_TRUNC;
        else
          return (false);
      }
      else
      {
        if (QueryUser(this, tr("File already exists and appears incomplete."), tr("Overwrite"), tr("Resume")))
          nFlags |= O_TRUNC;
        else
        {
          nFlags |= O_APPEND;
          m_nFilePos = buf.st_size;
        }
      }
    }
    else
    {
      nFlags |= O_CREAT;
    }

    m_nFileDesc = open (QFile::encodeName(f), nFlags, 00664);
    if (m_nFileDesc < 0)
    {
      if (!QueryUser(this, tr("Open error - unable to open file for writing."), tr("Retry"), tr("Cancel")))
        return (false);
    }
    else
      bValid = true;
  }

  nfoLocalFileName->setText(f);
  m_nBytesTransfered = 0;
  barTransfer->setTotalSteps(m_sFileInfo.nSize / 1024);
  barTransfer->setProgress(0);
  return(true);
}
Ejemplo n.º 27
0
JSValue jsString(ExecState* exec, const KURL& url)
{
    return jsString(exec, url.string());
}
Ejemplo n.º 28
0
void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r)
{
    KURL url = request().url();
    const String& mimeType = r.mimeType();
    
    switch (contentPolicy) {
    case PolicyUse: {
        // Prevent remote web archives from loading because they can claim to be from any domain and thus avoid cross-domain security checks (4120255).
        bool isRemoteWebArchive = (equalIgnoringCase("application/x-webarchive", mimeType) || equalIgnoringCase("multipart/related", mimeType))
            && !m_substituteData.isValid() && !url.isLocalFile();
        if (!frameLoader()->client()->canShowMIMEType(mimeType) || isRemoteWebArchive) {
            frameLoader()->policyChecker()->cannotShowMIMEType(r);
            // Check reachedTerminalState since the load may have already been cancelled inside of _handleUnimplementablePolicyWithErrorCode::.
            if (!reachedTerminalState())
                stopLoadingForPolicyChange();
            return;
        }
        break;
    }

    case PolicyDownload: {
        // m_handle can be null, e.g. when loading a substitute resource from application cache.
        if (!m_handle) {
            receivedError(cannotShowURLError());
            return;
        }
        InspectorInstrumentation::continueWithPolicyDownload(m_frame.get(), documentLoader(), identifier(), r);

        // When starting the request, we didn't know that it would result in download and not navigation. Now we know that main document URL didn't change.
        // Download may use this knowledge for purposes unrelated to cookies, notably for setting file quarantine data.
        ResourceRequest request = this->request();
        frameLoader()->setOriginalURLForDownloadRequest(request);

        frameLoader()->client()->download(m_handle.get(), request, r);

        // It might have gone missing
        if (frameLoader())
            receivedError(interruptedForPolicyChangeError());
        return;
    }
    case PolicyIgnore:
        InspectorInstrumentation::continueWithPolicyIgnore(m_frame.get(), documentLoader(), identifier(), r);
        stopLoadingForPolicyChange();
        return;
    
    default:
        ASSERT_NOT_REACHED();
    }

    RefPtr<MainResourceLoader> protect(this);

    if (r.isHTTP()) {
        int status = r.httpStatusCode();
        if (status < 200 || status >= 300) {
            bool hostedByObject = frameLoader()->isHostedByObjectElement();

            frameLoader()->handleFallbackContent();
            // object elements are no longer rendered after we fallback, so don't
            // keep trying to process data from their load

            if (hostedByObject)
                cancel();
        }
    }

    // we may have cancelled this load as part of switching to fallback content
    if (!reachedTerminalState())
        ResourceLoader::didReceiveResponse(r);

    if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) {
        if (m_substituteData.isValid()) {
            if (m_substituteData.content()->size())
                didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true);
            if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) 
                didFinishLoading(0);
        } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->client()->representationExistsForURLScheme(url.protocol()))
            didFinishLoading(0);
    }
}
Ejemplo n.º 29
0
JSValue jsStringOrFalse(ExecState* exec, const KURL& url)
{
    if (url.isNull())
        return jsBoolean(false);
    return jsString(exec, url.string());
}
Ejemplo n.º 30
0
bool PakProtocol::checkNewFile(const KURL &url, QString &path, KIO::Error &errorNum) {
	QString fullPath = url.path();

	kdDebug(PAK_DEBUG_ID) << "Entering checkNewFile() - " << fullPath << endl;

	// Are we already looking at that file ?
	if ( _pakFile && _pakFileName == fullPath.left(_pakFileName.length()) )
	{
		// Has it changed ?
		KDE_struct_stat statbuf;
		if ( KDE_stat( QFile::encodeName( _pakFileName ), &statbuf ) == 0 )
		{
			if ( _pakFileTime == statbuf.st_mtime )
			{
				// It hasn't changed, so just return
				path = fullPath.mid( _pakFileName.length() );
				kdDebug(PAK_DEBUG_ID) << "checkNewFile() returning " << path << endl;
				return true;
			}
		}
	}
	kdDebug(PAK_DEBUG_ID) << "Need to open a new file or check if dir" << endl;

	// Close previous file
	if ( _pakFile )
	{
		_pakFile->close();
		delete _pakFile;
		_pakFile = NULL;
	}

	kdDebug(PAK_DEBUG_ID) << "Going to find full path" << endl;

	// Find where the tar file is in the full path
	int pos = 0;
	QString archiveFile;
	path = QString::null;

	int len = fullPath.length();
	if ( len != 0 && fullPath[ len - 1 ] != '/' )
		fullPath += '/';

	kdDebug(PAK_DEBUG_ID) << "the full path is " << fullPath << endl;
	KDE_struct_stat statbuf;
	statbuf.st_mode = 0; // be sure to clear the directory bit
	while ( (pos=fullPath.find( '/', pos+1 )) != -1 )
	{
		QString tryPath = fullPath.left( pos );
		kdDebug(PAK_DEBUG_ID) << fullPath << "  trying " << tryPath << endl;
		if ( KDE_stat( QFile::encodeName(tryPath), &statbuf ) == -1 )
		{
			// We are not in the file system anymore, either we have already enough data or we will never get any useful data anymore
			break;
		}
		if ( !S_ISDIR(statbuf.st_mode) )
		{
			archiveFile = tryPath;
			_pakFileTime = statbuf.st_mtime;
			path = fullPath.mid( pos + 1 );
			kdDebug(PAK_DEBUG_ID) << "fullPath=" << fullPath << " path=" << path << endl;
			len = path.length();
			if ( len > 1 )
			{
				if ( path[ len - 1 ] == '/' )
					path.truncate( len - 1 );
			}
			else
				path = QString::fromLatin1("/");
			kdDebug(PAK_DEBUG_ID) << "Found. archiveFile=" << archiveFile << " path=" << path << endl;
			break;
		}
	}
	if ( archiveFile.isEmpty() )
	{
		kdDebug(PAK_DEBUG_ID) << "checkNewFile(): not found" << endl;
		if ( S_ISDIR(statbuf.st_mode) ) // Was the last stat about a directory?
		{
			// Too bad, it is a directory, not an archive.
			kdDebug(PAK_DEBUG_ID) << "Path is a directory, not an archive." << endl;
			errorNum = KIO::ERR_IS_DIRECTORY;
		}
		else
			errorNum = KIO::ERR_DOES_NOT_EXIST;
		return false;
	}

	if (url.protocol() == "pak") {
		kdDebug(PAK_DEBUG_ID) << "Creating a KPak object on " << archiveFile << endl;
		_pakFile = new KPak(archiveFile);
	} else {
		kdWarning(PAK_DEBUG_ID) << "Protocol " << url.protocol() << " not supported by this IOSlave" << endl;
		errorNum = KIO::ERR_UNSUPPORTED_PROTOCOL;
		return false;
	}

	if ( !_pakFile->open(IO_ReadOnly) )
	{
		kdDebug(PAK_DEBUG_ID) << "Opening " << archiveFile << "failed." << endl;
		delete _pakFile;
		_pakFile = NULL;
		errorNum = KIO::ERR_CANNOT_OPEN_FOR_READING;
		return false;
	}

	_pakFileName = archiveFile;
	return true;
}