Example #1
1
GP<DataPool>
DjVuErrorList::request_data(const DjVuPort * source, const GURL & url)
{
   GP<DataPool> retval;
   G_TRY
   {
     if (pool && url.protocol().downcase() == "data")
     {
       if(url == pool_url)
       {
         retval=pool;
       }else if(url.base() == pool_url)
       {
         GUTF8String name=url.fname();
         GP<DjVmDoc> doc=DjVmDoc::create();
         GP<ByteStream> bs=pool->get_stream();
         doc->read(*bs);
         retval=doc->get_data(name);
       }
     }else if (url.is_local_file_url())
     {
//       GUTF8String fname=GOS::url_to_filename(url);
//       if (GOS::basename(fname)=="-") fname="-";
       retval=DataPool::create(url);
     }
   }
   G_CATCH_ALL
   {
     retval=0;
   } G_ENDCATCH;
   return retval;
}
void WebContentsDelegateQt::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url)
{
    Q_ASSERT(validated_url.is_valid());
    if (validated_url.spec() == content::kUnreachableWebDataURL) {
        m_loadingErrorFrameList.removeOne(render_frame_host->GetRoutingID());
        m_viewClient->iconChanged(QUrl());

        // Trigger LoadFinished signal for main frame's error page only.
        if (!render_frame_host->GetParent())
            m_viewClient->loadFinished(true /* success */, toQt(validated_url), true /* isErrorPage */);

        return;
    }

    if (render_frame_host->GetParent())
        return;

    m_viewClient->loadFinished(true, toQt(validated_url));

    content::NavigationEntry *entry = web_contents()->GetController().GetActiveEntry();
    if (!entry)
        return;
    content::FaviconStatus &favicon = entry->GetFavicon();
    if (favicon.valid)
        m_viewClient->iconChanged(toQt(favicon.url));
    else
        m_viewClient->iconChanged(QUrl());
}
GURL 
getDjViewDataFile(const char *fname)
{
  GList<GURL> paths = DjVuMessage::GetProfilePaths();
  GUTF8String file = fname;

  // end hack alert
  static const char *osi = "/osi/";
  static const char *djview3 = "/djview3/";
  for (GPosition pos=paths; pos; ++pos)
    {
      GURL url = GURL(file, paths[pos]);
      GUTF8String urls = (const char*)url;
      int pos = urls.search(osi);
      if (pos >= 0)
        {
          GUTF8String urlx;
          urlx += urls.substr(0, pos);
          urlx += djview3;
          urlx += urls.substr(pos+strlen(osi), -1);
          GURL url = GURL::UTF8(urlx);
          if (url.is_file())
            return url;
        }
    }
  // end hack alert
  for (GPosition pos=paths; pos; ++pos)
    {
      GURL url = GURL(file, paths[pos]);
      if(url.is_file())
        return url;
    }
  return GURL();
}
Example #4
0
/** 
 * Returns all Links found in an URL
 * @return a vector of strings of the links we got
 */
vector < GURL > Page::getLinks()
{	
    vector< GURL > answer;
    HTML::ParserDom parser;
    GURL curr( url );

    if (getContent() == "")
        return answer;

    tree<HTML::Node> dom = parser.parseTree(content);

    tree<HTML::Node>::iterator it = dom.begin();
    tree<HTML::Node>::iterator end = dom.end();
    for (; it != end; ++it)
    {
        if (it->tagName() == "a")
        {
            it->parseAttributes();
            string relative = it->attribute("href").second;

            GURL resolved = curr.Resolve(relative);
            if (resolved.host() == curr.host() )
                answer.push_back( resolved );
        }
    }

    return answer;
}
Example #5
0
bool WebViewHost::canHandleRequest(WebFrame*, const WebURLRequest& request)
{
    GURL url = request.url();
    // Just reject the scheme used in
    // LayoutTests/http/tests/misc/redirect-to-external-url.html
    return !url.SchemeIs("spaceballs");
}
Example #6
0
static void
appendPath(const GURL &url, 
           GMap<GUTF8String,void *> &map,
           GList<GURL> &list)
{
  if( !url.is_empty() && !map.contains(url.get_string()) )
    {
      map[url.get_string()]=0;
      list.append(url);
    }
}
Example #7
0
void WebViewHost::willSendRequest(WebFrame*, unsigned identifier, WebURLRequest& request, const WebURLResponse& redirectResponse)
{
    // Need to use GURL for host() and SchemeIs()
    GURL url = request.url();
    string requestURL = url.possibly_invalid_spec();

    if (layoutTestController()->shouldDumpResourceLoadCallbacks()) {
        GURL mainDocumentURL = request.firstPartyForCookies();
        printResourceDescription(identifier);
        printf(" - willSendRequest <NSURLRequest URL %s, main document URL %s,"
               " http method %s> redirectResponse ",
               descriptionSuitableForTestResult(requestURL).c_str(),
               URLDescription(mainDocumentURL).c_str(),
               request.httpMethod().utf8().data());
        printResponseDescription(redirectResponse);
        fputs("\n", stdout);
    }

    if (!redirectResponse.isNull() && m_blocksRedirects) {
        fputs("Returning null for this redirect\n", stdout);
        // To block the request, we set its URL to an empty one.
        request.setURL(WebURL());
        return;
    }

    if (m_requestReturnNull) {
        // To block the request, we set its URL to an empty one.
        request.setURL(WebURL());
        return;
    }

    string host = url.host();
    // 255.255.255.255 is used in some tests that expect to get back an error.
    if (!host.empty() && (url.SchemeIs("http") || url.SchemeIs("https"))
        && host != "127.0.0.1"
        && host != "255.255.255.255"
        && host != "localhost"
        && !m_shell->allowExternalPages()) {
        printf("Blocked access to external URL %s\n", requestURL.c_str());

        // To block the request, we set its URL to an empty one.
        request.setURL(WebURL());
        return;
    }

    HashSet<String>::const_iterator end = m_clearHeaders.end();
    for (HashSet<String>::const_iterator header = m_clearHeaders.begin(); header != end; ++header)
        request.clearHTTPHeaderField(WebString(header->characters(), header->length()));

    // Set the new substituted URL.
    request.setURL(webkit_support::RewriteLayoutTestsURL(request.url().spec()));
}
Example #8
0
GURL
DjVuPortcaster::id_to_url(const DjVuPort * source, const GUTF8String &id)
{
   GPList<DjVuPort> list;
   compute_closure(source, list, true);
   GURL url;
   for(GPosition pos=list;pos;++pos)
   {
      url=list[pos]->id_to_url(source, id);
      if (!url.is_empty()) break;
   }
   return url;
}
Example #9
0
void WebViewHost::willSendRequest(WebFrame* frame, unsigned identifier, WebURLRequest& request, const WebURLResponse& redirectResponse)
{
    if (request.url().isEmpty())
        return;

    // Need to use GURL for host() and SchemeIs()
    GURL url = request.url();
    string requestURL = url.possibly_invalid_spec();

    GURL mainDocumentURL = request.firstPartyForCookies();

    request.setExtraData(webkit_support::CreateWebURLRequestExtraData(frame->document().referrerPolicy()));

    string host = url.host();
    if (!host.empty() && (url.SchemeIs("http") || url.SchemeIs("https"))) {
        if (!isLocalhost(host) && !hostIsUsedBySomeTestsToGenerateError(host)
                && ((!mainDocumentURL.SchemeIs("http") && !mainDocumentURL.SchemeIs("https")) || isLocalhost(mainDocumentURL.host()))
                && !m_shell->allowExternalPages()) {
            printf("Blocked access to external URL %s\n", requestURL.c_str());
            blockRequest(request);
            return;
        }
    }

    // Set the new substituted URL.
    request.setURL(webkit_support::RewriteLayoutTestsURL(request.url().spec()));
}
void LayoutTestController::queueLoad(const CppArgumentList& arguments, CppVariant* result)
{
    if (arguments.size() > 0 && arguments[0].isString()) {
        // FIXME: Implement WebURL::resolve() and avoid GURL.
        GURL currentURL = m_shell->webView()->mainFrame()->url();
        GURL fullURL = currentURL.Resolve(arguments[0].toString());

        string target = "";
        if (arguments.size() > 1 && arguments[1].isString())
            target = arguments[1].toString();

        m_workQueue.addWork(new WorkItemLoad(fullURL, WebString::fromUTF8(target)));
    }
    result->setNull();
}
Example #11
0
void SfDelegate::OnReceivedRedirect(
            net::URLRequest *request, const GURL &new_url, bool *defer_redirect) {

#ifndef ANDROID_DEFAULT_CODE
     const char *uri =NULL;   
      uri = new_url.spec().c_str();
      MY_LOGI(StringPrintf("OnReceivedRedirect,original_url=%s ",request->original_url().spec().c_str()).c_str());
      MY_LOGI(StringPrintf("OnReceivedRedirect, new_url=%s", new_url.spec().c_str()).c_str());
      MY_LOGI(StringPrintf("OnReceivedRedirect,defer_redirect=%d",*defer_redirect).c_str());
    
      mOwner->OnReceivedRedirect( uri);
#else
    MY_LOGV("OnReceivedRedirect");
#endif
}
Example #12
0
void WebRequest::handleDataURL(GURL url)
{
    OwnPtr<std::string> data(new std::string);
    std::string mimeType;
    std::string charset;

    if (net::DataURL::Parse(url, &mimeType, &charset, data.get())) {
        // PopulateURLResponse from chrome implementation
        // weburlloader_impl.cc
        m_loadState = Response;
        OwnPtr<WebResponse> webResponse(new WebResponse(url.spec(), mimeType, data->size(), charset, 200));
        m_urlLoader->maybeCallOnMainThread(NewRunnableMethod(
                m_urlLoader.get(), &WebUrlLoaderClient::didReceiveResponse, webResponse.release()));

        if (!data->empty()) {
            m_loadState = GotData;
            m_urlLoader->maybeCallOnMainThread(NewRunnableMethod(
                    m_urlLoader.get(), &WebUrlLoaderClient::didReceiveDataUrl, data.release()));
        }
    } else {
        // handle the failed case
    }

    finish(true);
}
Example #13
0
void WebViewHost::didReceiveResponse(WebFrame*, unsigned identifier, const WebURLResponse& response)
{
    if (m_shell->shouldDumpResourceLoadCallbacks()) {
        printResourceDescription(identifier);
        fputs(" - didReceiveResponse ", stdout);
        printResponseDescription(response);
        fputs("\n", stdout);
    }
    if (m_shell->shouldDumpResourceResponseMIMETypes()) {
        GURL url = response.url();
        WebString mimeType = response.mimeType();
        printf("%s has MIME type %s\n",
            url.ExtractFileName().c_str(),
            // Simulate NSURLResponse's mapping of empty/unknown MIME types to application/octet-stream
            mimeType.isEmpty() ? "application/octet-stream" : mimeType.utf8().data());
    }
}
Example #14
0
int
main(int argc,char *argv[],char *[])
{
    setlocale(LC_ALL,"");
    djvu_programname(argv[0]);
    G_TRY
    {
        int i;
        if (argc < 2)
            usage(argv[0]);
        for (i=1; i<argc; i++)
        {
            GURL djvufile;
            GURL *pdjvufile = 0;
            if (! strcmp(argv[i], "-o"))
            {
                if (++i >= argc)
                    usage(argv[0]);
                djvufile = GURL::Filename::Native(argv[i]);
                pdjvufile = &djvufile;
                if (! djvufile.is_file())
                    nofile(argv[i]);
                if (++i >= argc)
                    usage(argv[0]);
            }
            GURL xmlfile = GURL::Filename::Native(argv[i]);
            if (! xmlfile.is_file())
                nofile(argv[i]);
            GP<lt_XMLParser> parser(lt_XMLParser::create());
            GP<lt_XMLTags> tag(lt_XMLTags::create(xmlfile));
            parser->parse(*tag, pdjvufile);
            parser->save();
        }
    }
    G_CATCH(ex)
    {
        ex.perror();
        exit(1);
    }
    G_ENDCATCH;
    exit(0);
#ifdef WIN32
    return 0;
#endif
}
Example #15
0
// Called upon a server-initiated redirect.  The delegate may call the
// request's Cancel method to prevent the redirect from being followed.
// Since there may be multiple chained redirects, there may also be more
// than one redirect call.
//
// When this function is called, the request will still contain the
// original URL, the destination of the redirect is provided in 'new_url'.
// If the delegate does not cancel the request and |*defer_redirect| is
// false, then the redirect will be followed, and the request's URL will be
// changed to the new URL.  Otherwise if the delegate does not cancel the
// request and |*defer_redirect| is true, then the redirect will be
// followed once FollowDeferredRedirect is called on the URLRequest.
//
// The caller must set |*defer_redirect| to false, so that delegates do not
// need to set it if they are happy with the default behavior of not
// deferring redirect.
void WebRequest::OnReceivedRedirect(net::URLRequest* newRequest, const GURL& newUrl, bool* deferRedirect)
{
    ASSERT(m_loadState < Response, "Redirect after receiving response");
    ASSERT(newRequest && newRequest->status().is_success(), "Invalid redirect");

    // SAMSUNG CHANGE : read timer stop
    timer_.Stop();
    // SAMSUNG CHANGE

//Android KITKAT Merge  - START
	    m_url = newUrl.spec();
//Android KITKAT Merge  - END

    OwnPtr<WebResponse> webResponse(new WebResponse(newRequest));
    webResponse->setUrl(newUrl.spec());
    m_urlLoader->maybeCallOnMainThread(NewRunnableMethod(
            m_urlLoader.get(), &WebUrlLoaderClient::willSendRequest, webResponse.release()));

    // Defer the redirect until followDeferredRedirect() is called.
    *deferRedirect = true;
}
Example #16
0
void WebRequest::handleBrowserURL(GURL url)
{
    std::string data("data:text/html;charset=utf-8,");
    if (url.spec() == "browser:incognito") {
        AssetManager* assetManager = globalAssetManager();
        Asset* asset = assetManager->open("webkit/incognito_mode_start_page.html", Asset::ACCESS_BUFFER);
        if (asset) {
            data.append((const char*)asset->getBuffer(false), asset->getLength());
            delete asset;
        }
    }
    GURL dataURL(data.c_str());
    handleDataURL(dataURL);
}
void WebContentsDelegateQt::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code, const base::string16& error_description, bool was_ignored_by_handler)
{
    Q_UNUSED(was_ignored_by_handler);
    if (validated_url.spec() == content::kUnreachableWebDataURL) {
        m_loadingErrorFrameList.removeOne(render_frame_host->GetRoutingID());
        qCritical("Loading error-page failed. This shouldn't happen.");
        if (!render_frame_host->GetParent())
            m_viewClient->loadFinished(false /* success */, toQt(validated_url), true /* isErrorPage */);
        return;
    }

    if (render_frame_host->GetParent())
        return;

    m_viewClient->loadFinished(false /* success */ , toQt(validated_url), false /* isErrorPage */, error_code, toQt(error_description));
    m_viewClient->loadProgressChanged(0);
}
GURL 
getExecDir(void)
{
  // This is the same as GetModulePath in DjVuMessage.cpp
 GURL retval;
 GUTF8String &xprogramname=DjVuMessage::programname();
 if(xprogramname.length())
 {
   if(xprogramname[1]=='/'
     ||!xprogramname.cmp("../",3)
     ||!xprogramname.cmp("./",2))
   {
     retval=GURL::Filename::UTF8(xprogramname);
   }
   if(retval.is_empty() || !retval.is_file())
   {
     GList<GURL> paths(parsePATH());
     GMap<GUTF8String,void *> pathMAP;
     for(GPosition pos=paths;pos;++pos)
     {
       retval=GURL::UTF8(xprogramname,paths[pos]);
       const GUTF8String path(retval.get_string());
       if(!pathMAP.contains(path))
       {
         if(retval.is_file())
           break;
         pathMAP[path]=0;
       }
     }
   }
   if (! retval.is_empty() )
     retval = retval.follow_symlinks();
   if (! retval.is_empty() )
     retval = retval.base();
 }
 return retval;
}
Example #19
0
GP<DjVuFile>
lt_XMLParser::Impl::get_file(const GURL &url,GUTF8String id)
{
  GP<DjVuFile> dfile;
  GP<DjVuDocument> doc;
  GCriticalSectionLock lock(&xmlparser_lock);
  {
    GPosition pos=m_docs.contains(url.get_string());
    if(pos)
    {
      doc=m_docs[pos];
    }else
    {
      doc=DjVuDocument::create_wait(url);
      if(! doc->wait_for_complete_init())
      {
        G_THROW(( ERR_MSG("XMLAnno.fail_init") "\t")+url.get_string() );
      }
      m_docs[url.get_string()]=doc;
    }
    if(id.is_int())
    {
      const int xpage=id.toInt(); //atoi((char const *)page); 
      if(xpage>0)
        id=doc->page_to_id(xpage-1);
    }else if(!id.length())
    { 
      id=doc->page_to_id(0);
    }
  }
  const GURL fileurl(doc->id_to_url(id));
  GPosition dpos(m_files.contains(fileurl.get_string()));
  if(!dpos)
  {
    if(!doc->get_id_list().contains(id))
    {
      G_THROW( ERR_MSG("XMLAnno.bad_page") );
    }
    dfile=doc->get_djvu_file(id,false);
    if(!dfile)
    {
      G_THROW( ERR_MSG("XMLAnno.bad_page") );
    }
    m_files[fileurl.get_string()]=dfile;
  }else
  {
    dfile=m_files[dpos];
  }
  return dfile;
}
Example #20
0
int 
main(int argc, const char **argv)
{
  setlocale(LC_ALL,"");
  setlocale(LC_NUMERIC,"C");
  djvu_programname(argv[0]);
  GArray<GUTF8String> dargv(0,argc-1);
  for(int i=0;i<argc;++i)
    dargv[i]=GNativeString(argv[i]);
  G_TRY
    {
      GURL inputpbmurl;
      GURL outputdjvuurl;
      cjb2opts opts;
      // Defaults
      opts.forcedpi = 0;
      opts.dpi = 300;
      opts.losslevel = 0;
      opts.verbose = false;
      // Parse options
      for (int i=1; i<argc; i++)
        {
          GUTF8String arg = dargv[i];
          if (arg == "-dpi" && i+1<argc)
            {
              char *end;
              opts.dpi = opts.forcedpi = strtol(dargv[++i], &end, 10);
              if (*end || opts.dpi<25 || opts.dpi>1200)
                usage();
            }
          else if (arg == "-losslevel")
            {
              char *end;
              opts.losslevel = strtol(dargv[++i], &end, 10);
              if (*end || opts.losslevel<0 || opts.losslevel>200)
                usage();
            }
          else if (arg == "-lossless")
            opts.losslevel = 0;
          else if (arg == "-lossy")
            opts.losslevel = 100;
          else if (arg == "-clean") // almost deprecated
            opts.losslevel = 1;
          else if (arg == "-verbose" || arg == "-v")
            opts.verbose = true;
          else if (arg[0] == '-' && arg[1])
            usage();
          else if (inputpbmurl.is_empty())
            inputpbmurl = GURL::Filename::UTF8(arg);
          else if (outputdjvuurl.is_empty())
            outputdjvuurl = GURL::Filename::UTF8(arg);
          else
            usage();
        }
      if (inputpbmurl.is_empty() || outputdjvuurl.is_empty())
        usage();
      // Execute
      cjb2(inputpbmurl, outputdjvuurl, opts);
    }
  G_CATCH(ex)
    {
      ex.perror();
      exit(1);
    }
  G_ENDCATCH;
  return 0;
}
void setStringField(JNIEnv* env, jobject obj, jfieldID field, const GURL& url)
{
    jstring jstr = stdStringToJstring(env, url.spec(), false);
    env->SetObjectField(obj, field, jstr);
    env->DeleteLocalRef(jstr);
}
Example #22
0
/**
 * Implementation of getQueryable
 */
string Crawler::getQueryable(GURL url) {
    return url.path() + "?" + url.query();
}
Example #23
0
void print_uri(GURL &url) {
    std::cout << "scheme:\t\t" << url.scheme() << "\nusername:\t" << url.username() << "\npassword:\t" << url.password()
        << "\nhost:\t\t" << url.host() << "\nport:\t\t" << url.port() << "\npath:\t\t" << url.path() << "\nquery:\t\t"
        << url.query() << "\nfragment:\t" << url.ref() << "\n\n";
}
QUrl WebContentsAdapter::activeUrl() const
{
    GURL gurl = webContents()->GetVisibleURL();
    return QUrl(QString::fromStdString(gurl.spec()));
}
Example #25
0
string URLDescription(const GURL& url)
{
    if (url.SchemeIs("file"))
        return url.ExtractFileName();
    return url.possibly_invalid_spec();
}
Example #26
0
TUrlParseResult gurl::gParseRel( GURL& baseUrl, const std::string& relativeUrl )
{
    GURL   relativeGurl(baseUrl.Resolve(relativeUrl));
    return TUrlParseResult(relativeGurl.host(), relativeGurl.PathForRequest());
}
Example #27
0
int 
main(int argc, const char **argv)
{
  setlocale(LC_ALL,"");
  setlocale(LC_NUMERIC,"C");
  djvu_programname(argv[0]);
  GArray<GUTF8String> dargv(0,argc-1);
  for(int i=0;i<argc;++i)
    dargv[i]=GNativeString(argv[i]);
  G_TRY
    {
      GURL inputppmurl;
      GURL outputdjvuurl;
      // Defaults
      cpaldjvuopts opts;
      opts.dpi = 100;
      opts.ncolors = 256;
      opts.verbose = false;
      opts.bgwhite = false;
      // Parse options
      for (int i=1; i<argc; i++)
        {
          GUTF8String arg = dargv[i];
          if (arg == "-colors" && i+1<argc)
            {
              char *end;
              opts.ncolors = strtol(dargv[++i], &end, 10);
              if (*end || opts.ncolors<2 || opts.ncolors>4096)
                usage();
            }
          else if (arg == "-dpi" && i+1<argc)
            {
              char *end;
              opts.dpi = strtol(dargv[++i], &end, 10);
              if (*end || opts.dpi<25 || opts.dpi>6000)
                usage();
            }
          else if (arg == "-verbose" || arg == "-v")
            opts.verbose = true;
          else if (arg == "-bgwhite")
            opts.bgwhite = true;
          else if (arg[0] == '-' && arg[1])
            usage();
          else if (inputppmurl.is_empty())
            inputppmurl = GURL::Filename::UTF8(arg);
          else if (outputdjvuurl.is_empty())
            outputdjvuurl = GURL::Filename::UTF8(arg);
          else
            usage();
        }
      if (inputppmurl.is_empty() || outputdjvuurl.is_empty())
        usage();
      // Load and run
      GP<ByteStream> ibs=ByteStream::create(inputppmurl,"rb");
      cpaldjvu(ibs, outputdjvuurl, opts);
    }
  G_CATCH(ex)
    {
      ex.perror();
      exit(1);
    }
  G_ENDCATCH;
  return 0;
}
Example #28
0
GList<GURL>
DjVuMessage::GetProfilePaths(void)
{
  static bool first=true;
  static GList<GURL> realpaths;
  if(first)
  {
    first=false;
    GMap<GUTF8String,void *> pathsmap;
    GList<GURL> paths;
    GURL path;
    const GUTF8String envp(GOS::getenv(DjVuEnv));
    if(envp.length())
      appendPath(GURL::Filename::UTF8(envp),pathsmap,paths);
#if defined(WIN32) || defined(UNIX)
    GURL mpath(GetModulePath());
    if(!mpath.is_empty() && mpath.is_dir())
    {
#if defined(UNIX) && !defined(AUTOCONF) && !defined(NDEBUG)
      appendPath(GURL::UTF8(DebugModuleDjVuDir,mpath),pathsmap,paths);
#endif
      appendPath(mpath,pathsmap,paths);
      mpath=mpath.base();
      appendPath(GURL::UTF8(ModuleDjVuDir,mpath),pathsmap,paths);
      mpath=mpath.base();
      appendPath(GURL::UTF8(ModuleDjVuDir,mpath),pathsmap,paths);
    }
#endif
#if defined(AUTOCONF)
    GURL dpath = GURL::Filename::UTF8(DjVuDataDir);
    appendPath(dpath,pathsmap,paths);
#endif
#ifdef WIN32
    appendPath(RegOpenReadConfig(HKEY_CURRENT_USER),pathsmap,paths);
    appendPath(RegOpenReadConfig(HKEY_LOCAL_MACHINE),pathsmap,paths);
#else
    GUTF8String home=GOS::getenv("HOME");
# if HAVE_GETPWUID
    if (! home.length()) {
      struct passwd *pw=0;
      if ((pw = getpwuid(getuid())))
        home=GNativeString(pw->pw_dir);
    }
# endif
    if (home.length()) {
      GURL hpath = GURL::UTF8(LocalDjVuDir,GURL::Filename::UTF8(home));
      appendPath(hpath,pathsmap,paths);
    }
#endif
#ifdef LT_DEFAULT_PREFIX
    appendPath(GURL::Filename::UTF8(DjVuPrefixDir),pathsmap,paths);
#endif
    appendPath(GURL::Filename::UTF8(RootDjVuDir),pathsmap,paths);
    pathsmap.empty();

    GPosition pos;
    GList< GMap<GUTF8String,GP<lt_XMLTags> > > localemaps;
    for(pos=paths;pos;++pos)
    {
      path=GURL::UTF8(LanguageFile,paths[pos]);
      if(path.is_file())
      {
        const GP<lt_XMLTags> xml(lt_XMLTags::create(ByteStream::create(path,"rb")));
        const GPList<lt_XMLTags> Body(xml->get_Tags(bodystring));
        GPosition pos=Body;
        if(!pos || (pos != Body.lastpos()))
        {
          G_THROW( ERR_MSG("XMLAnno.extra_body") );
        }
        const GP<lt_XMLTags> GBody(Body[pos]);
        if(!GBody)
        {
          G_THROW( ERR_MSG("XMLAnno.no_body") );
        }
        GMap<GUTF8String,GP<lt_XMLTags> > localemap;
        lt_XMLTags::get_Maps(languagestring,localestring,Body,localemap);
        localemaps.append(localemap);
      }
    } 
    GList<GURL> localepaths;
    GList<GURL> osilocalepaths;

    // Need to do it the right way!
    GUTF8String defaultlocale = getenv("LANGUAGE");
    if (! defaultlocale) 
      {
        const GUTF8String oldlocale(setlocale(LC_MESSAGES,0));
        defaultlocale = setlocale(LC_MESSAGES,"");
        setlocale(LC_MESSAGES,(const char *)oldlocale);
      }
    // Unfathomable search.
    for(int loop=0; loop<2; loop++)
    {
      static const char sepchars[]=" _.@";
      const char *p=sepchars+sizeof(sepchars)-1;
      do
      {
        int sepcharpos=p[0]?defaultlocale.search(p[0]):defaultlocale.length();
        if(sepcharpos > 0)
        {
          const GUTF8String sublocale(defaultlocale,sepcharpos);
          const GUTF8String downcasesublocale("downcase^"+sublocale.downcase());
          for(pos=localemaps;pos;++pos) 
          {
            const GMap<GUTF8String,GP<lt_XMLTags> > &localemap=localemaps[pos];
            GPosition pos=localemap.contains(sublocale);
            if(!pos)
              pos=localemap.contains(downcasesublocale);
            if(pos)
            {
              const GMap<GUTF8String,GUTF8String>&args
                = localemap[pos]->get_args();
              pos = args.contains(srcstring);
              if (pos)
              {
                const GUTF8String src(args[pos]);
                for(pos=paths;pos;++pos)
                {
                  path=GURL::UTF8(src,paths[pos]);
                  if(path.is_dir())
                    localepaths.append(path);
                  path=GURL::UTF8(GUTF8String(opensourcedir)+"/"+src,paths[pos]);
                  if(path.is_dir())
                    osilocalepaths.append(path);
                }
              }
              // We don't need to check anymore language files.
              p=sepchars;
              break;
            }
          }
          if(!pos)
          {
            for(pos=paths;pos;++pos)
            {
              path=GURL::UTF8(sublocale,paths[pos]);
              if(path.is_dir())
              {
                localepaths.append(path);
              }
              path=GURL::UTF8(GUTF8String(opensourcedir)+"/"+sublocale,paths[pos]);
              if(path.is_dir())
              {
                osilocalepaths.append(path);
              }
            }
          }
        }
      } while(p-- != sepchars);
      if((GPosition) localepaths)
        break;
      defaultlocale="C";
    }
    for(pos=localepaths;pos;++pos)
      appendPath(localepaths[pos],pathsmap,realpaths);
    for(pos=paths;pos;++pos)
      appendPath(paths[pos],pathsmap,realpaths);
    for(pos=osilocalepaths;pos;++pos)
      appendPath(osilocalepaths[pos],pathsmap,realpaths);
    for(pos=paths;pos;++pos)
      {
        path=GURL::UTF8(opensourcedir,paths[pos]);
        appendPath(path,pathsmap,realpaths);
      }
  }
  return realpaths;
}
Example #29
0
DjVuNavDir::DjVuNavDir(const GURL &dirURL)
{
   if (!dirURL) G_THROW( ERR_MSG("DjVuNavDir.zero_dir") );
   baseURL=dirURL.base();
}
Example #30
0
void
lt_XMLParser::Impl::parse(const lt_XMLTags &tags, GURL *pdjvufile)
{
  const GPList<lt_XMLTags> Body(tags.get_Tags(bodytag));
  GPosition pos=Body;
 
  if(!pos || (pos != Body.lastpos()))
  {
    G_THROW( ERR_MSG("XMLAnno.extra_body") );
  }
  const GP<lt_XMLTags> GBody(Body[pos]);
  if(!GBody)
  {
    G_THROW( ERR_MSG("XMLAnno.no_body") );
  }

  GMap<GUTF8String,GP<lt_XMLTags> > Maps;
  lt_XMLTags::get_Maps(maptag,"name",Body,Maps);

  const GPList<lt_XMLTags> Objects(GBody->get_Tags(objecttag));
  lt_XMLTags::get_Maps(maptag,"name",Objects,Maps);

  for(GPosition Objpos=Objects;Objpos;++Objpos)
  {
    lt_XMLTags &GObject=*Objects[Objpos];
    // Map of attributes to value (e.g. "width" --> "500")
    const GMap<GUTF8String,GUTF8String> &args=GObject.get_args();
    GURL codebase;
    {
      DEBUG_MSG("Setting up codebase... m_codebase = " << m_codebase << "\n");
      GPosition codebasePos=args.contains("codebase");
      // If user specified a codebase attribute, assume it is correct (absolute URL):
      //  the GURL constructor will throw an exception if it isn't
      if(codebasePos)
      {
        codebase=GURL::UTF8(args[codebasePos]);
      }else if (m_codebase.is_dir())
      {
        codebase=m_codebase;
      }else
      {
        codebase=GURL::Filename::UTF8(GOS::cwd());
      }
      DEBUG_MSG("codebase = " << codebase << "\n");
    }
    // the data attribute specifies the input file.  This can be
    //  either an absolute URL (starts with file:/) or a relative
    //  URL (for now, just a path and file name).  If it's absolute,
    //  our GURL will adequately wrap it.  If it's relative, we need
    //  to use the codebase attribute to form an absolute URL first.
    GPosition datapos=args.contains("data");
    if(datapos)
    {
      bool isDjVuType=false;
      GPosition typePos(args.contains("type"));
      if(typePos)
      {
        if(args[typePos] != mimetype)
        {
          // DjVuPrintErrorUTF8("Ignoring %s Object tag\n",mimetype);
          continue;
        }
        isDjVuType=true;
      }
      const GURL url = (pdjvufile) ? *pdjvufile 
        : GURL::UTF8(args[datapos], 
                     (args[datapos][0] == '/') ? codebase.base() : codebase);
      int width;
      {
        GPosition widthPos=args.contains("width");
        width=(widthPos)?args[widthPos].toInt():0;
      }
      int height;
      {
        GPosition heightPos=args.contains("height");
        height=(heightPos)?args[heightPos].toInt():0;
      }
      GUTF8String gamma;
      GUTF8String dpi;
      GUTF8String page;
      GUTF8String do_ocr;
      {
        GPosition paramPos(GObject.contains(paramtag));
        if(paramPos)
        {
          const GPList<lt_XMLTags> Params(GObject[paramPos]);
          for(GPosition loc=Params;loc;++loc)
          {
            const GMap<GUTF8String,GUTF8String> &pargs=Params[loc]->get_args();
            GPosition namepos=pargs.contains("name");
            if(namepos)
            {
              GPosition valuepos=pargs.contains("value");
              if(valuepos)
              {
                const GUTF8String name=pargs[namepos].downcase();
                const GUTF8String &value=pargs[valuepos];
                if(name == "flags")
                {
                  GMap<GUTF8String,GUTF8String> args;
                  lt_XMLTags::ParseValues(value,args,true);
                  if(args.contains("page"))
                  {
                    page=args["page"];
                  }
                  if(args.contains("dpi"))
                  {
                    dpi=args["dpi"];
                  }
                  if(args.contains("gamma"))
                  {
                    gamma=args["gamma"];
                  }
                  if(args.contains("ocr"))
                  {
                    do_ocr=args["ocr"];
                  }
                }else if(name == "page")
                {
                  page=value;
                }else if(name == "dpi")
                {
                  dpi=value;
                }else if(name == "gamma")
                {
                  gamma=value;
                }else if(name == "ocr")
                {
                  do_ocr=value;
                }
              }
            }
          }
        }
      }
      const GP<DjVuFile> dfile(get_file(url,page));
      if(dpi.is_int() || gamma.is_float())
      {
        int pos=0;
        ChangeInfo(*dfile,dpi.toInt(),gamma.toDouble(pos,pos));
      }
      parse_anno(width,height,GObject,Maps,*dfile);
      parse_meta(GObject,*dfile);
      parse_text(width,height,GObject,*dfile);
      ChangeTextOCR(do_ocr,width,height,dfile);
    }
  }
}