/* This is cvg_qt_util.h
* This defines some utility functions that use QT structures
*/
#include <limits.h>
#include <stdlib.h>
#include "cvg_qt_util.h"
QString makeAbsolutePath(const QString &Cwd, const QString &Path)
{
QString retval;
char resolved[PATH_MAX + 1];
if (Path.startsWith("/"))
retval = Path;
else
retval = Cwd + Path.right(Path.length() - 2);
// fix /../ and /./ in the path
retval = realpath(retval, resolved);
return retval;
}
QString computeRelativePath(const QString &Base, const QString &Target)
{
//qWarning("cRP(\"" + Base + "\", \"" + Target + "\")");
// This code kindly supplied by Isaac Richards
// And then fixed to actually work by me (Matthew Gabeler-Lee)
if ((Base.isEmpty()) || (Target.isEmpty()))
return Target;
const char *a = Base.latin1();
const char *b = Target.latin1();
int match_count = 0;
if ((*a != *b) || (*a != '/'))
return QString::null;
a++; b++;
while (*a == *b)
{
if (*a == '/')
match_count++;
a++; b++;
}
//qWarning("cRP: match_count = " + QString::number(match_count));
// ok, they share the first match_count parent dirs
// count # of dirs in Base
int dir_count = 0;
b = Base.latin1();
b++;
while (b)
{
b = strchr(b, '/');
if (b)
{
b++;
dir_count++;
}
}
//qWarning("cRP: dir_count = " + QString::number(dir_count));
// seek to the unshared part of target
b = Target.latin1();
b++;
for (int i = 0; i < match_count; i++)
{
b = strchr(b, '/');
if (!b)
// BIG FUCKING ERROR
return QString::null;
b++;
}
// b now points at the non-shared parts of the second path
QString retval = "";
for (int j = 0; j < (dir_count - match_count); j++)
retval += "../";
retval = "./" + retval + b;
retval = cleanPath(retval);
return retval;
}
void splitPath(QString &Path, QString &File, const QString &Source)
{
int slashpos = Source.findRev('/');
if (slashpos >= 0)
{
Path = Source.left(slashpos);
File = Source.right(Source.length() - slashpos - 1);
}
else
{
Path = "";
File = Source;
}
}
QString cleanPath(QString Path)
{
// this translates /./ -> / and // -> /
// works with a local copy of path, so passed by value
// this is a somewhat inefficient implementation for now, but it
// works ...
QString retval;
while (! Path.isEmpty())
{
if (Path.startsWith("//"))
{
retval += '/';
Path.remove(0, 2);
}
else if (Path.startsWith("/./"))
{
retval += '/';
Path.remove(0, 3);
}
else
{
retval += Path[0];
Path.remove(0, 1);
}
}
return retval;
}