Page Menu
Home
Phabricator (Chris)
Search
Configure Global Search
Log In
Files
F132202
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Authored By
Unknown
Size
59 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/src/GitHubAPI.cpp b/src/GitHubAPI.cpp
index b03917d..5272ee7 100644
--- a/src/GitHubAPI.cpp
+++ b/src/GitHubAPI.cpp
@@ -1,99 +1,101 @@
+
#include "GitHubAPI.h"
#include "webclient.h"
#include "common/misc.h"
#include "charvec.h"
#include "urlencode.h"
#include "MemoryReader.h"
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <memory>
using WebClientPtr = GitHubAPI::WebClientPtr;
struct GitHubRequestThread::Private {
WebClientPtr web;
};
GitHubRequestThread::GitHubRequestThread()
: m(new Private)
{
}
GitHubRequestThread::~GitHubRequestThread()
{
delete m;
}
void GitHubRequestThread::start(WebContext *webcx)
{
- m->web = WebClientPtr(new WebClient(webcx));
+ m->web = std::make_shared<WebClient>(webcx);
QThread::start();
}
void GitHubRequestThread::run()
{
ok = false;
if (web()->get(WebClient::URL(url)) == 200) {
WebClient::Response const &r = web()->response();
if (!r.content.empty()) {
text = to_stdstr(r.content);
ok = true;
if (callback) {
ok = callback(text);
}
}
}
}
GitHubAPI::WebClientPtr GitHubRequestThread::web()
{
return m->web;
}
QList<GitHubAPI::SearchResultItem> GitHubAPI::searchRepository(std::string const &q)
{
QList<GitHubAPI::SearchResultItem> items;
GitHubRequestThread th;
{
OverrideWaitCursor;
th.url = "https://api.github.com/search/repositories?q=" + q;
th.start(webcx);
while (!th.wait(1)) {
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
if (th.ok) {
QByteArray ba(th.text.c_str(), th.text.size());
QJsonDocument doc = QJsonDocument::fromJson(ba);
QJsonArray a1 = doc.object().value("items").toArray();
for (QJsonValue const &v1 : a1) {
QJsonObject o1 = v1.toObject();
SearchResultItem item;
auto String = [&](QString const &key){
return o1.value(key).toString().toStdString();
};
item.full_name = String("full_name");
if (!item.full_name.empty()) {
item.description = String("description");
item.html_url = String("html_url");
item.ssh_url = String("ssh_url");
item.clone_url = String("clone_url");
item.score = o1.value("score").toDouble();
items.push_back(item);
}
}
}
std::sort(items.begin(), items.end(), [](SearchResultItem const &l, SearchResultItem const &r){
return l.score > r.score; // 降順
});
return items;
}
diff --git a/src/ImageViewWidget.cpp b/src/ImageViewWidget.cpp
index 1101f8d..47ff559 100644
--- a/src/ImageViewWidget.cpp
+++ b/src/ImageViewWidget.cpp
@@ -1,374 +1,376 @@
+#include <memory>
+
#include "ImageViewWidget.h"
#include "FileDiffSliderWidget.h"
#include "FileDiffWidget.h"
#include "MainWindow.h"
#include "common/misc.h"
#include "common/joinpath.h"
#include "Photoshop.h"
#include "MemoryReader.h"
#include "charvec.h"
#include <math.h>
#include <functional>
#include <QDebug>
#include <QFileDialog>
#include <QMenu>
#include <QPainter>
#include <QWheelEvent>
#include <QSvgRenderer>
#include <QBuffer>
using SvgRendererPtr = std::shared_ptr<QSvgRenderer>;
struct ImageViewWidget::Private {
MainWindow *mainwindow = nullptr;
FileDiffWidget *filediffwidget = nullptr;
FileDiffWidget::DrawData *draw_data = nullptr;
QScrollBar *v_scroll_bar = nullptr;
QScrollBar *h_scroll_bar = nullptr;
QString mime_type;
QPixmap pixmap;
SvgRendererPtr svg;
double image_scroll_x = 0;
double image_scroll_y = 0;
double image_scale = 1;
- int scroll_origin_x = 0;
- int scroll_origin_y = 0;
+ double scroll_origin_x = 0;
+ double scroll_origin_y = 0;
QPoint mouse_press_pos;
int wheel_delta = 0;
QPointF interest_pos;
int top_margin = 1;
int bottom_margin = 1;
bool draw_left_border = true;
#ifndef APP_GUITAR
QPixmap transparent_pixmap;
#endif
};
ImageViewWidget::ImageViewWidget(QWidget *parent)
: QWidget(parent)
, m(new Private)
{
#if defined(Q_OS_WIN32)
setFont(QFont("MS Gothic"));
#elif defined(Q_OS_LINUX)
setFont(QFont("Monospace"));
#elif defined(Q_OS_MAC)
setFont(QFont("Menlo"));
#endif
setContextMenuPolicy(Qt::DefaultContextMenu);
}
ImageViewWidget::~ImageViewWidget()
{
delete m;
}
void ImageViewWidget::bind(MainWindow *mainwindow, FileDiffWidget *filediffwidget, QScrollBar *vsb, QScrollBar *hsb)
{
m->mainwindow = mainwindow;
m->filediffwidget = filediffwidget;
m->v_scroll_bar = vsb;
m->h_scroll_bar = hsb;
}
bool ImageViewWidget::hasFocus() const
{
QWidget *w = qApp->focusWidget();
return w && w != m->filediffwidget && w->isAncestorOf(this);
}
void ImageViewWidget::setLeftBorderVisible(bool f)
{
m->draw_left_border = f;
}
void ImageViewWidget::internalScrollImage(double x, double y)
{
m->image_scroll_x = x;
m->image_scroll_y = y;
QSizeF sz = imageScrollRange();
if (m->image_scroll_x < 0) m->image_scroll_x = 0;
if (m->image_scroll_y < 0) m->image_scroll_y = 0;
if (m->image_scroll_x > sz.width()) m->image_scroll_x = sz.width();
if (m->image_scroll_y > sz.height()) m->image_scroll_y = sz.height();
update();
}
void ImageViewWidget::scrollImage(double x, double y)
{
internalScrollImage(x, y);
if (m->h_scroll_bar) {
m->h_scroll_bar->blockSignals(true);
- m->h_scroll_bar->setValue(m->image_scroll_x);
+ m->h_scroll_bar->setValue((int)m->image_scroll_x);
m->h_scroll_bar->blockSignals(false);
}
if (m->v_scroll_bar) {
m->v_scroll_bar->blockSignals(true);
- m->v_scroll_bar->setValue(m->image_scroll_y);
+ m->v_scroll_bar->setValue((int)m->image_scroll_y);
m->v_scroll_bar->blockSignals(false);
}
}
void ImageViewWidget::refrectScrollBar()
{
double e = 0.75;
double x = m->h_scroll_bar->value();
double y = m->v_scroll_bar->value();
if (fabs(x - m->image_scroll_x) < e) x = m->image_scroll_x; // 差が小さいときは値を維持する
if (fabs(y - m->image_scroll_y) < e) y = m->image_scroll_y;
internalScrollImage(x, y);
}
void ImageViewWidget::clear()
{
m->mime_type = QString();
m->pixmap = QPixmap();
setMouseTracking(false);
update();
}
QString ImageViewWidget::formatText(Document::Line const &line)
{
QByteArray const &ba = line.text;
if (ba.isEmpty()) return QString();
std::vector<char> vec;
vec.reserve(ba.size() + 100);
char const *begin = ba.data();
char const *end = begin + ba.size();
char const *ptr = begin;
int x = 0;
while (ptr < end) {
if (*ptr == '\t') {
do {
vec.push_back(' ');
x++;
} while ((x % 4) != 0);
ptr++;
} else {
vec.push_back(*ptr);
ptr++;
x++;
}
}
return QString::fromUtf8(&vec[0], vec.size());
}
QSizeF ImageViewWidget::imageScrollRange() const
{
QSize sz = imageSize();
- int w = sz.width() * m->image_scale;
- int h = sz.height() * m->image_scale;
+ int w = int(sz.width() * m->image_scale);
+ int h = int(sz.height() * m->image_scale);
return QSize(w, h);
}
void ImageViewWidget::setScrollBarRange(QScrollBar *h, QScrollBar *v)
{
h->blockSignals(true);
v->blockSignals(true);
QSizeF sz = imageScrollRange();
- h->setRange(0, sz.width());
- v->setRange(0, sz.height());
+ h->setRange(0, (int)sz.width());
+ v->setRange(0, (int)sz.height());
h->setPageStep(width());
v->setPageStep(height());
h->blockSignals(false);
v->blockSignals(false);
}
void ImageViewWidget::updateScrollBarRange()
{
setScrollBarRange(m->h_scroll_bar, m->v_scroll_bar);
}
MainWindow *ImageViewWidget::mainwindow()
{
return m->mainwindow;
}
QBrush ImageViewWidget::getTransparentBackgroundBrush()
{
#ifdef APP_GUITAR
return mainwindow()->getTransparentPixmap();
#else
if (m->transparent_pixmap.isNull()) {
m->transparent_pixmap = QPixmap(":/image/transparent.png");
}
return m->transparent_pixmap;
#endif
}
bool ImageViewWidget::isValidImage() const
{
return !m->pixmap.isNull() || (m->svg && m->svg->isValid());
}
QSize ImageViewWidget::imageSize() const
{
if (!m->pixmap.isNull()) return m->pixmap.size();
if (m->svg && m->svg->isValid()) return m->svg->defaultSize();
return QSize();
}
void ImageViewWidget::paintEvent(QPaintEvent *)
{
QPainter pr(this);
QSize imagesize = imageSize();
if (imagesize.width() > 0 && imagesize.height() > 0) {
pr.save();
if (!m->draw_left_border) {
pr.setClipRect(1, 0, width() - 1, height());
}
double cx = width() / 2.0;
double cy = height() / 2.0;
double x = cx - m->image_scroll_x;
double y = cy - m->image_scroll_y;
QSizeF sz = imageScrollRange();
if (sz.width() > 0 && sz.height() > 0) {
QBrush br = getTransparentBackgroundBrush();
- pr.setBrushOrigin(x, y);
- pr.fillRect(x, y, sz.width(), sz.height(), br);
+ pr.setBrushOrigin((int)x, (int)y);
+ pr.fillRect((int)x, (int)y, (int)sz.width(), (int)sz.height(), br);
if (!m->pixmap.isNull()) {
- pr.drawPixmap(x, y, sz.width(), sz.height(), m->pixmap, 0, 0, imagesize.width(), imagesize.height());
+ pr.drawPixmap((int)x, (int)y, (int)sz.width(), (int)sz.height(), m->pixmap, 0, 0, imagesize.width(), imagesize.height());
} else if (m->svg && m->svg->isValid()) {
m->svg->render(&pr, QRectF(x, y, sz.width(), sz.height()));
}
}
- misc::drawFrame(&pr, x - 1, y - 1, sz.width() + 2, sz.height() + 2, Qt::black);
+ misc::drawFrame(&pr, (int)x - 1, (int)y - 1, (int)sz.width() + 2, (int)sz.height() + 2, Qt::black);
pr.restore();
}
if (m->draw_left_border) {
pr.fillRect(0, 0, 1, height(), QColor(160, 160, 160));
}
if (hasFocus()) {
misc::drawFrame(&pr, 0, 0, width(), height(), QColor(0, 128, 255, 128));
misc::drawFrame(&pr, 1, 1, width() - 2, height() - 2, QColor(0, 128, 255, 64));
}
}
void ImageViewWidget::resizeEvent(QResizeEvent *)
{
updateScrollBarRange();
}
void ImageViewWidget::setImage(QString mimetype, QByteArray const &ba)
{
if (mimetype.isEmpty()) {
mimetype = "image/x-unknown";
}
setMouseTracking(true);
m->pixmap = QPixmap();
m->svg = SvgRendererPtr();
if (!ba.isEmpty()) {
if (misc::isSVG(mimetype)) {
- m->svg = SvgRendererPtr(new QSvgRenderer(ba));
+ m->svg = std::make_shared<QSvgRenderer>(ba);
} else if (misc::isPSD(mimetype)) {
if (!ba.isEmpty()) {
MemoryReader reader(ba.data(), ba.size());
if (reader.open(QIODevice::ReadOnly)) {
std::vector<char> jpeg;
photoshop::readThumbnail(&reader, &jpeg);
if (!jpeg.empty()) {
m->pixmap.loadFromData((uchar const *)&jpeg[0], jpeg.size());
}
}
}
} else {
m->pixmap.loadFromData(ba);
}
}
QSize sz = imageSize();
double sx = sz.width();
double sy = sz.height();
if (sx > 0 && sy > 0) {
sx = width() / sx;
sy = height() / sy;
m->image_scale = (sx < sy ? sx : sy) * 0.9;
}
updateScrollBarRange();
m->h_scroll_bar->blockSignals(true);
m->v_scroll_bar->blockSignals(true);
m->h_scroll_bar->setValue(m->h_scroll_bar->maximum() / 2);
m->v_scroll_bar->setValue(m->v_scroll_bar->maximum() / 2);
m->h_scroll_bar->blockSignals(false);
m->v_scroll_bar->blockSignals(false);
refrectScrollBar();
}
void ImageViewWidget::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
QPoint pos = mapFromGlobal(QCursor::pos());
m->mouse_press_pos = pos;
m->scroll_origin_x = m->image_scroll_x;
m->scroll_origin_y = m->image_scroll_y;
}
}
void ImageViewWidget::mouseMoveEvent(QMouseEvent *e)
{
if (isValidImage()) {
QPoint pos = mapFromGlobal(QCursor::pos());
if ((e->buttons() & Qt::LeftButton) && hasFocus()) {
int delta_x = pos.x() - m->mouse_press_pos.x();
int delta_y = pos.y() - m->mouse_press_pos.y();
scrollImage(m->scroll_origin_x - delta_x, m->scroll_origin_y - delta_y);
}
double cx = width() / 2.0;
double cy = height() / 2.0;
double x = (pos.x() + 0.5 - cx + m->image_scroll_x) / m->image_scale;
double y = (pos.y() + 0.5 - cy + m->image_scroll_y) / m->image_scale;
m->interest_pos = QPointF(x, y);
m->wheel_delta = 0;
}
}
void ImageViewWidget::setImageScale(double scale)
{
if (scale < 1 / 32.0) scale = 1 / 32.0;
if (scale > 32) scale = 32;
m->image_scale = scale;
}
void ImageViewWidget::wheelEvent(QWheelEvent *e)
{
if (isValidImage()) {
double scale = 1;
const double mul = 1.189207115; // sqrt(sqrt(2))
m->wheel_delta += e->delta();
while (m->wheel_delta >= 120) {
m->wheel_delta -= 120;
scale *= mul;
}
while (m->wheel_delta <= -120) {
m->wheel_delta += 120;
scale /= mul;
}
setImageScale(m->image_scale * scale);
updateScrollBarRange();
double cx = width() / 2.0;
double cy = height() / 2.0;
QPoint pos = mapFromGlobal(QCursor::pos());
double dx = m->interest_pos.x() * m->image_scale + cx - (pos.x() + 0.5);
double dy = m->interest_pos.y() * m->image_scale + cy - (pos.y() + 0.5);
scrollImage(dx, dy);
update();
}
}
diff --git a/src/LogTableWidget.cpp b/src/LogTableWidget.cpp
index a15e883..1de2feb 100644
--- a/src/LogTableWidget.cpp
+++ b/src/LogTableWidget.cpp
@@ -1,334 +1,334 @@
#include "LogTableWidget.h"
#include <QDebug>
#include <QEvent>
#include <QPainter>
#include <QProxyStyle>
#include <cmath>
#include "MainWindow.h"
#include <QApplication>
#include "MyTableWidgetDelegate.h"
#include "common/misc.h"
struct LogTableWidget::Private {
};
class LogTableWidgetDelegate : public MyTableWidgetDelegate {
private:
MainWindow *mainwindow() const
{
LogTableWidget *w = dynamic_cast<LogTableWidget *>(QStyledItemDelegate::parent());
Q_ASSERT(w);
return w->mainwindow();
}
static QColor labelColor(int kind)
{
switch (kind) {
case MainWindow::Label::Head: return QColor(255, 192, 224); // blue
case MainWindow::Label::LocalBranch: return QColor(192, 224, 255); // blue
case MainWindow::Label::RemoteBranch: return QColor(192, 240, 224); // green
case MainWindow::Label::Tag: return QColor(255, 224, 192); // orange
}
return QColor(224, 224, 224); // gray
}
static QColor hiliteColor(QColor const &color)
{
int r = color.red();
int g = color.green();
int b = color.blue();
r = 255 - (255 - r) / 2;
g = 255 - (255 - g) / 2;
b = 255 - (255 - b) / 2;
return QColor(r, g, b);
}
static QColor shadowColor(QColor const &color)
{
return QColor(color.red() / 2, color.green() / 2, color.blue() / 2);
}
void drawSignatureIcon(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const
{
if (!opt.widget->isEnabled()) return;
Git::CommitItem const *commit = mainwindow()->commitItem(index.row());
QIcon icon = mainwindow()->verifiedIcon(commit->signature);
if (!icon.isNull()) {
QRect r = opt.rect.adjusted(6, 3, 0, -3);
int h = r.height();
int w = h;
int x = r.x() + r.width() - w;
int y = r.y();
icon.paint(painter, x, y, w, h);
}
}
void drawAvatar(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const
{
if (!opt.widget->isEnabled()) return;
int row = index.row();
QIcon icon = mainwindow()->committerIcon(row);
if (!icon.isNull()) {
int h = opt.rect.height();
int w = h;
int x = opt.rect.x() + opt.rect.width() - w;
int y = opt.rect.y();
painter->save();
painter->setOpacity(0.5); // 半透明で描画
icon.paint(painter, x, y, w, h);
painter->restore();
}
}
void drawDescription(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const
{
int row = index.row();
QList<MainWindow::Label> const *labels = mainwindow()->label(row);
if (labels) {
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
QFontMetrics fm = painter->fontMetrics();
const int space = 8;
int x = opt.rect.x() + opt.rect.width() - 3;
int x1 = x;
int y0 = opt.rect.y();
int y1 = y0 + opt.rect.height() - 1;
int i = labels->size();
while (i > 0) {
i--;
MainWindow::Label const &label = labels->at(i);
QString text = misc::abbrevBranchName(label.text);
int w = fm.size(0, text).width() + space * 2;
int x0 = x1 - w;
QRect r(x0, y0, x1 - x0, y1 - y0);
painter->setPen(Qt::NoPen);
auto DrawRect = [&](int dx, int dy, QColor color){
painter->setBrush(color);
painter->drawRoundedRect(r.adjusted(lround(dx + 3), lround(dy + 3), lround(dx - 3), lround(dy - 3)), 3, 3);
};
QColor color = labelColor(label.kind);
QColor hilite = hiliteColor(color);
QColor shadow = shadowColor(color);
DrawRect(-1, -1, hilite);
DrawRect(1, 1, shadow);
DrawRect(0, 0, color);
painter->setPen(Qt::black);
painter->setBrush(Qt::NoBrush);
qApp->style()->drawItemText(painter, r.adjusted(space, 0, 0, 0), opt.displayAlignment, opt.palette, true, text);
x1 = x0;
}
painter->restore();
}
}
public:
explicit LogTableWidgetDelegate(QObject *parent = Q_NULLPTR)
: MyTableWidgetDelegate(parent)
{
}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
MyTableWidgetDelegate::paint(painter, option, index);
// signatureの描画
if (index.column() == 1) {
drawSignatureIcon(painter, option, index);
}
// avatarの描画
if (index.column() == 3) {
drawAvatar(painter, option, index);
}
// Descriptionの描画
if (index.column() == 4) {
drawDescription(painter, option, index);
}
}
};
LogTableWidget::LogTableWidget(QWidget *parent)
: QTableWidget(parent)
, m(new Private)
{
setItemDelegate(new LogTableWidgetDelegate(this));
}
LogTableWidget::~LogTableWidget()
{
delete m;
}
MainWindow *LogTableWidget::mainwindow()
{
MainWindow *mw = qobject_cast<MainWindow *>(window());
Q_ASSERT(mw);
return mw;
}
void drawBranch(QPainterPath *path, double x0, double y0, double x1, double y1, double r, bool bend_early)
{
const double k = 0.55228475;
if (x0 == x1) {
path->moveTo(x0, y0);
path->lineTo(x1, y1);
} else {
double ym = bend_early ? (y0 + r) : (y1 - r);
double h = fabs(y1 - y0);
double w = fabs(x1 - x0);
if (r > h / 2) r = h / 2;
if (r > w / 2) r = w / 2;
double s = r;
if (x0 > x1) r = -r;
if (y0 > y1) s = -s;
if (0) {
path->moveTo(x0, y0);
path->lineTo(x0, ym - s);
path->cubicTo(x0, ym - s + s * k, x0 + r - r * k, ym, x0 + r, ym);
path->lineTo(x1 - r, ym);
path->cubicTo(x1 - r + r * k, ym, x1, ym + s - s * k, x1, ym + s);
path->lineTo(x1, y1);
} else {
if (bend_early) {
path->moveTo(x0, y0);
path->cubicTo(x0, ym, x1, ym, x1, ym + ym - y0);
path->lineTo(x1, y1);
} else {
path->moveTo(x0, y0);
path->lineTo(x0, ym + ym - y1);
path->cubicTo(x0, ym, x1, ym, x1, y1);
}
}
}
}
void LogTableWidget::paintEvent(QPaintEvent *e)
{
if (rowCount() < 1) return;
QTableWidget::paintEvent(e);
QPainter pr(viewport());
pr.setRenderHint(QPainter::Antialiasing);
pr.setBrush(QBrush(QColor(255, 255, 255)));
Git::CommitItemList const *list = mainwindow()->logs();
int indent_span = 16;
auto ItemRect = [&](int row){
QRect r;
QTableWidgetItem *p = item(row, 0);
if (p) {
r = visualItemRect(p);
}
return r;
};
int line_width = 2;
auto ItemPoint = [&](int depth, QRect const &rect){
int h = rect.height();
double n = h / 2.0;
double x = floor(rect.x() + n + depth * indent_span);
double y = floor(rect.y() + n);
return QPointF(x, y);
};
auto SetPen = [&](QPainter *pr, int level, bool /*continued*/){
QColor c = mainwindow()->color(level + 1);
Qt::PenStyle s = Qt::SolidLine;
pr->setPen(QPen(c, line_width, s));
};
auto DrawLine = [&](size_t index, int itemrow){
QRect rc1;
if (index < list->size()) {
Git::CommitItem const &item1 = list->at(index);
rc1 = ItemRect(itemrow);
QPointF pt1 = ItemPoint(item1.marker_depth, rc1);
double halfheight = rc1.height() / 2.0;
for (TreeLine const &line : item1.parent_lines) {
if (line.depth >= 0) {
QPainterPath *path = nullptr;
Git::CommitItem const &item2 = list->at(line.index);
QRect rc2 = ItemRect(line.index);
if (index + 1 == (size_t)line.index || line.depth == item1.marker_depth || line.depth == item2.marker_depth) {
QPointF pt2 = ItemPoint(line.depth, rc2);
if (pt2.y() > 0) {
path = new QPainterPath();
drawBranch(path, pt1.x(), pt1.y(), pt2.x(), pt2.y(), halfheight, line.bend_early);
}
} else {
QPointF pt3 = ItemPoint(item2.marker_depth, rc2);
if (pt3.y() > 0) {
path = new QPainterPath();
QRect rc3 = ItemRect(itemrow + 1);
QPointF pt2 = ItemPoint(line.depth, rc3);
drawBranch(path, pt1.x(), pt1.y(), pt2.x(), pt2.y(), halfheight, true);
drawBranch(path, pt2.x(), pt2.y(), pt3.x(), pt3.y(), halfheight, false);
}
}
if (path) {
SetPen(&pr, line.color_number, false);
pr.drawPath(*path);
delete path;
}
}
}
}
return rc1.y();
};
auto DrawMark = [&](size_t index, int row){
double x, y;
y = 0;
if (index < list->size()) {
Git::CommitItem const &item = list->at(index);
QRect rc = ItemRect(row);
QPointF pt = ItemPoint(item.marker_depth, rc);
double r = 4;
x = pt.x() - r;
y = pt.y() - r;
SetPen(&pr, item.marker_depth, false);
if (item.resolved) {
// ◯
- pr.drawEllipse(x, y, r * 2, r * 2);
+ pr.drawEllipse((int)x, (int)y, int(r * 2), int(r * 2));
} else {
// ▽
QPainterPath path;
path.moveTo(pt.x(), pt.y() + r);
path.lineTo(pt.x() - r, pt.y() - r);
path.lineTo(pt.x() + r, pt.y() - r);
path.lineTo(pt.x(), pt.y() + r);
pr.drawPath(path);
}
}
return y;
};
// draw lines
pr.setOpacity(0.5);
pr.setBrush(Qt::NoBrush);
for (size_t i = 0; i < list->size(); i++) {
double y = DrawLine(i, i);
if (y >= height()) break;
}
// draw marks
pr.setOpacity(1);
pr.setBrush(mainwindow()->color(0));
for (size_t i = 0; i < list->size(); i++) {
double y = DrawMark(i, i);
if (y >= height()) break;
}
}
diff --git a/src/MyTableWidgetDelegate.cpp b/src/MyTableWidgetDelegate.cpp
index 8306341..9e4617a 100644
--- a/src/MyTableWidgetDelegate.cpp
+++ b/src/MyTableWidgetDelegate.cpp
@@ -1,36 +1,36 @@
#include "MyTableWidgetDelegate.h"
#include <QPainter>
#include <QTableWidget>
#include <QApplication>
MyTableWidgetDelegate::MyTableWidgetDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
void MyTableWidgetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
#ifdef Q_OS_WIN
// 選択枠を描画
if (option.showDecorationSelected) {
QTableWidget const *tablewidget = qobject_cast<QTableWidget const *>(option.widget);
Q_ASSERT(tablewidget);
int w = tablewidget->viewport()->rect().width();
painter->save();
QStyleOptionViewItem o = option;
painter->setClipRect(o.rect);
o.rect = QRect(1, o.rect.y(), w - 2, o.rect.height());
- qApp->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &o, painter, 0);
+ qApp->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &o, painter, nullptr);
painter->restore();
}
opt.state &= ~QStyle::State_Selected; // 行の選択枠は描画しない
#endif
opt.state &= ~QStyle::State_HasFocus; // セルのフォーカス枠は描画しない
QStyledItemDelegate::paint(painter, opt, index); // デフォルトの描画
}
diff --git a/src/SelectCommandDialog.cpp b/src/SelectCommandDialog.cpp
index 4d2e094..25c5757 100644
--- a/src/SelectCommandDialog.cpp
+++ b/src/SelectCommandDialog.cpp
@@ -1,98 +1,98 @@
#include "SelectCommandDialog.h"
#include "ui_SelectCommandDialog.h"
#include <QFileDialog>
QStringList uniqueStringList(const QStringList &list)
{
QStringList tmp_list = list;
std::sort(tmp_list.begin(), tmp_list.end());
auto end = std::unique(tmp_list.begin(), tmp_list.end());
QStringList ret_list;
for (auto it = tmp_list.begin(); it != end; it++) {
ret_list.push_back(*it);
}
return ret_list;
}
SelectCommandDialog::SelectCommandDialog(QWidget *parent, const QString &cmdname, const QStringList &cmdfiles, const QString &path, const QStringList &list) :
QDialog(parent),
ui(new Ui::SelectCommandDialog)
{
ui->setupUi(this);
Qt::WindowFlags flags = windowFlags();
flags &= ~Qt::WindowContextHelpButtonHint;
setWindowFlags(flags);
command_name = cmdname;
command_files = cmdfiles;
QString text = tr("Please select the '%1' command you want to use.");
ui->label->setText(text.arg(cmdfiles.front()));
this->path = path;
QStringList list2 = uniqueStringList(list);
for (QString const &s : list2) {
if (s.isEmpty()) continue;
ui->listWidget->addItem(s);
}
ui->listWidget->setFocus();
ui->listWidget->setCurrentRow(0);
}
SelectCommandDialog::~SelectCommandDialog()
{
delete ui;
}
void SelectCommandDialog::on_pushButton_browse_clicked()
{
QString dir;
#ifdef _WIN32
QString filter;
for (QString const &cmd : command_files) {
if (cmd.isEmpty()) continue;
filter += tr("%1 command (%2);;").arg(command_name).arg(cmd);
}
filter += tr("Executable files (*.exe)");
#else
QString filter;
for (QString const &cmd : command_files) {
if (cmd.isEmpty()) continue;
filter += tr("%1 command (%2);;").arg(command_name).arg(cmd);
}
filter += "All files (*)";
#endif
QFileDialog dlg(this);
dlg.setWindowTitle(tr("%1 command").arg(command_name));
dlg.setDirectory(dir);
dlg.setNameFilter(filter);
dlg.setFilter(QDir::Dirs | QDir::Executable);
dlg.setFileMode(QFileDialog::ExistingFile);
if (dlg.exec() == QDialog::Accepted) {
QStringList list = dlg.selectedFiles();
- if (list.size() > 0) {
+ if (!list.empty()) {
path = list.first();
accept();
}
}
}
void SelectCommandDialog::on_listWidget_currentTextChanged(const QString ¤tText)
{
path = currentText;
}
QString SelectCommandDialog::selectedFile() const
{
return path;
}
void SelectCommandDialog::on_listWidget_itemDoubleClicked(QListWidgetItem * /*item*/)
{
accept();
}
diff --git a/src/webclient.cpp b/src/webclient.cpp
index c2ff4fc..323203d 100644
--- a/src/webclient.cpp
+++ b/src/webclient.cpp
@@ -1,1083 +1,1083 @@
#include "webclient.h"
#include <string.h>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib")
#if USE_OPENSSL
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#endif
typedef SOCKET socket_t;
#pragma warning(disable:4996)
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <netdb.h>
#define closesocket(S) ::close(S)
typedef int socket_t;
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)
#define stricmp(A, B) strcasecmp(A, B)
#define strnicmp(A, B, C) strncasecmp(A, B, C)
#endif
#if USE_OPENSSL
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#else
typedef void SSL;
typedef void SSL_CTX;
#endif
#include <assert.h>
#include "charvec.h"
#define USER_AGENT "Generic Web Client"
struct WebContext::Private {
SSL_CTX *ctx;
bool use_keep_alive = false;
WebProxy http_proxy;
WebProxy https_proxy;
};
WebClient::URL::URL(std::string const &addr)
{
data.full_request = addr;
char const *str = addr.c_str();
char const *left;
char const *right;
left = str;
right = strstr(left, "://");
if (right) {
data.scheme.assign(str, right - str);
left = right + 3;
}
right = strchr(left, '/');
if (!right) {
right = left + strlen(left);
}
if (right) {
char const *p = strchr(left, ':');
if (p && left < p && p < right) {
int n = 0;
char const *q = p + 1;
while (q < right) {
if (isdigit(*q & 0xff)) {
n = n * 10 + (*q - '0');
} else {
n = -1;
break;
}
q++;
}
data.host.assign(left, p - left);
if (n > 0 && n < 65536) {
data.port = n;
}
} else {
data.host.assign(left, right - left);
}
data.path = right;
}
}
bool WebClient::URL::isssl() const
{
if (scheme() == "https") return true;
if (scheme() == "http") return false;
if (port() == 443) return true;
return false;
}
void WebClientHandler::abort(const std::string &message)
{
throw WebClient::Error(message);
}
struct WebClient::Private {
std::vector<std::string> request_header;
Error error;
Response response;
WebContext *webcx;
int crlf_state = 0;
size_t content_offset = 0;
std::string last_host_name;
int last_port = 0;
bool keep_alive = false;
socket_t sock = INVALID_SOCKET;
SSL *ssl = nullptr;
};
WebClient::WebClient(WebContext *webcx)
: m(new Private)
{
assert(webcx);
m->webcx = webcx;
}
WebClient::~WebClient()
{
close();
delete m;
}
void WebClient::initialize()
{
#ifdef _WIN32
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup(wVersionRequested, &wsaData);
atexit(cleanup);
#endif
#if USE_OPENSSL
OpenSSL_add_all_algorithms();
#endif
}
void WebClient::cleanup()
{
#if USE_OPENSSL
ERR_free_strings();
#endif
#ifdef _WIN32
WSACleanup();
#endif
}
void WebClient::reset()
{
m->request_header.clear();
m->error = Error();
m->response = Response();
m->crlf_state = 0;
m->content_offset = 0;
}
void WebClient::output_debug_string(char const *str)
{
if (0) {
#ifdef _WIN32
OutputDebugStringA(str);
#else
fwrite(str, 1, strlen(str), stderr);
#endif
}
}
void WebClient::output_debug_strings(std::vector<std::string> const &vec)
{
for (std::string const &s : vec) {
output_debug_string((s + '\n').c_str());
}
}
WebClient::Error const &WebClient::error() const
{
return m->error;
}
void WebClient::clear_error()
{
m->error = Error();
}
int WebClient::get_port(URL const *url, char const *scheme, char const *protocol)
{
int port = url->port();
if (port < 1 || port > 65535) {
struct servent *s;
s = getservbyname(url->scheme().c_str(), protocol);
if (s) {
port = ntohs(s->s_port);
} else {
s = getservbyname(scheme, protocol);
if (s) {
port = ntohs(s->s_port);
}
}
if (port < 1 || port > 65535) {
port = 80;
}
}
return port;
}
static inline std::string to_s(size_t n)
{
char tmp[100];
sprintf(tmp, "%u", (int)n);
return tmp;
}
void WebClient::set_default_header(URL const &url, Post const *post, RequestOption const &opt)
{
std::vector<std::string> header;
auto AddHeader = [&](std::string const &s){
header.push_back(s);
};
AddHeader("Host: " + url.host());
AddHeader("User-Agent: " USER_AGENT);
AddHeader("Accept: */*");
if (opt.keep_alive) {
AddHeader("Connection: keep-alive");
} else {
AddHeader("Connection: close");
}
if (post) {
AddHeader("Content-Length: " + to_s(post->data.size()));
std::string ct = "Content-Type: ";
if (post->content_type.empty()) {
ct += "application/octet-stream";
} else if (post->content_type == CT_MULTIPART_FORM_DATA) {
ct += post->content_type;
if (!post->boundary.empty()) {
ct += "; boundary=";
ct += post->boundary;
}
} else {
ct += post->content_type;
}
AddHeader(ct);
}
header.insert(header.end(), m->request_header.begin(), m->request_header.end());
m->request_header = std::move(header);
}
std::string WebClient::make_http_request(URL const &url, Post const *post, WebProxy const *proxy, bool https)
{
std::string str;
str = post ? "POST " : "GET ";
if (proxy && !https) {
str += url.data.full_request;
str += " HTTP/1.0";
str += "\r\n";
} else {
str += url.path();
str += " HTTP/1.0";
str += "\r\n";
}
for (std::string const &s: m->request_header) {
str += s;
str += "\r\n";
}
str += "\r\n";
return str;
}
void WebClient::parse_http_header(char const *begin, char const *end, std::vector<std::string> *header)
{
if (begin < end) {
char const *left = begin;
char const *right = left;
while (1) {
if (right >= end) {
break;
}
if (*right == '\r' || *right == '\n') {
if (left < right) {
header->push_back(std::string(left, right));
}
if (right + 1 < end && *right == '\r' && right[1] == '\n') {
right++;
}
right++;
if (*right == '\r' || *right == '\n') {
if (right + 1 < end && *right == '\r' && right[1] == '\n') {
right++;
}
right++;
left = right;
break;
}
left = right;
} else {
right++;
}
}
}
}
void WebClient::parse_http_header(const char *begin, const char *end, WebClient::Response *out)
{
*out = Response();
parse_http_header(begin, end, &out->header);
parse_header(&out->header, out);
}
static void send_(socket_t s, char const *ptr, int len)
{
while (len > 0) {
int n = send(s, ptr, len, 0);
if (n < 1 || n > len) {
throw WebClient::Error("send request failed.");
}
ptr += n;
len -= n;
}
}
void WebClient::on_end_header(std::vector<char> const *vec, WebClientHandler *handler)
{
if (vec->empty()) return;
char const *begin = &vec->at(0);
char const *end = begin + vec->size();
parse_http_header(begin, end, &m->response);
if (handler) {
handler->checkHeader(this);
}
}
void WebClient::append(char const *ptr, size_t len, std::vector<char> *out, WebClientHandler *handler)
{
size_t offset = out->size();
out->insert(out->end(), ptr, ptr + len);
if (m->crlf_state < 0) {
// nop
} else {
for (size_t i = 0; i < len; i++) {
int c = ptr[i] & 0xff;
if (c == '\r') {
m->crlf_state |= 1;
} else if (c == '\n') {
m->crlf_state |= 1;
m->crlf_state++;
} else {
m->crlf_state = 0;
}
if (m->crlf_state == 4) {
m->content_offset = offset + i + 1;
on_end_header(out, handler);
m->crlf_state = -1;
break;
}
}
}
if (handler && m->content_offset > 0) {
offset = out->size();
if (offset > m->content_offset) {
size_t len = offset - m->content_offset;
char const *ptr = &out->at(m->content_offset);
handler->checkContent(ptr, len);
}
}
}
static char *stristr(char *str1, char const *str2)
{
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
for (size_t i = 0; i + len2 <= len1; i++) {
if (strnicmp(str1 + i, str2, len2) == 0) {
return str1 + i;
}
}
return nullptr;
}
class ResponseHeader {
public:
size_t pos = 0;
std::vector<char> line;
int content_length = -1;
bool connection_keep_alive = false;
bool connection_close = false;
int lf = 0;
enum State {
Header,
Content,
};
State state = Header;
void put(int c)
{
pos++;
if (state == Header) {
if (c== '\r' || c == '\n') {
if (!line.empty()) {
line.push_back(0);
char *begin = &line[0];
char *p = strchr(begin, ':');
if (p && *p == ':') {
*p++ = 0;
auto IS = [&](char const *name){ return stricmp(begin, name) == 0; };
if (IS("content-length")) {
content_length = strtol(p, nullptr, 10);
} else if (IS("connection")) {
if (stristr(p, "keep-alive")) {
connection_keep_alive = true;
} else if (stristr(p, "close")) {
connection_close = true;
}
}
}
line.clear();
}
if (c== '\r') {
return;
}
if (c == '\n') {
lf++;
if (lf == 2) {
state = Content;
}
return;
}
}
lf = 0;
line.push_back(c);
}
}
};
void WebClient::receive_(RequestOption const &opt, std::function<int(char *, int)> rcv, std::vector<char> *out)
{
char buf[4096];
size_t pos = 0;
ResponseHeader rh;
while (1) {
int n;
if (rh.state == ResponseHeader::Content && rh.content_length >= 0) {
n = rh.pos + rh.content_length - pos;
if (n > (int)sizeof(buf)) {
n = sizeof(buf);
}
if (n < 1) break;
} else {
n = sizeof(buf);
}
n = rcv(buf, n);
if (n < 1) break;
if (0) { // debug
fwrite(buf, 1, n, stderr);
}
append(buf, n, out, opt.handler);
pos += n;
if (rh.state == ResponseHeader::Header) {
for (int i = 0; i < n; i++) {
rh.put(buf[i]);
if (rh.state == ResponseHeader::Content) {
m->keep_alive = rh.connection_keep_alive && !rh.connection_close;
break;
}
}
}
}
}
bool WebClient::http_get(URL const &request_url, Post const *post, RequestOption const &opt, std::vector<char> *out)
{
clear_error();
out->clear();
URL server_url;
WebProxy const *proxy = m->webcx->http_proxy();
if (proxy) {
server_url = URL(proxy->server);
} else {
server_url = request_url;
}
std::string hostname = server_url.host();
int port = get_port(&server_url, "http", "tcp");
m->keep_alive = opt.keep_alive && hostname == m->last_host_name && port == m->last_port;
if (!m->keep_alive) close();
if (m->sock == INVALID_SOCKET) {
struct hostent *servhost;
struct sockaddr_in server;
servhost = gethostbyname(hostname.c_str());
if (!servhost) {
throw Error("gethostbyname failed.");
}
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
memcpy((char *)&server.sin_addr, servhost->h_addr, servhost->h_length);
server.sin_port = htons(port);
m->sock = socket(AF_INET, SOCK_STREAM, 0);
if (m->sock == INVALID_SOCKET) {
throw Error("socket failed.");
}
if (connect(m->sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) {
throw Error("connect failed.");
}
}
m->last_host_name = hostname;
m->last_port = port;
set_default_header(request_url, post, opt);
std::string request = make_http_request(request_url, post, proxy, false);
send_(m->sock, request.c_str(), (int)request.size());
if (post && !post->data.empty()) {
send_(m->sock, (char const *)&post->data[0], (int)post->data.size());
}
m->crlf_state = 0;
m->content_offset = 0;
receive_(opt, [&](char *ptr, int len){
return recv(m->sock, ptr, len, 0);
}, out);
if (!m->keep_alive) close();
return true;
}
bool WebClient::https_get(const URL &request_url, Post const *post, RequestOption const &opt, std::vector<char> *out)
{
#if USE_OPENSSL
if (!m->webcx || !m->webcx->m->ctx) {
output_debug_string("SSL context is null.\n");
return false;
}
auto sslctx = [&](){ return m->webcx->m->ctx; };
clear_error();
out->clear();
auto get_ssl_error = []()->std::string{
char tmp[1000];
unsigned long e = ERR_get_error();
ERR_error_string_n(e, tmp, sizeof(tmp));
return tmp;
};
URL server_url;
WebProxy const *proxy = m->webcx->https_proxy();
if (proxy) {
server_url = URL(proxy->server);
} else {
server_url = request_url;
}
std::string hostname = server_url.host();
int port = get_port(&server_url, "https", "tcp");
m->keep_alive = opt.keep_alive && hostname == m->last_host_name && port == m->last_port;
if (!m->keep_alive) close();
socket_t sock = m->sock;
SSL *ssl = m->ssl;
if (sock == INVALID_SOCKET || !ssl) {
int ret;
struct hostent *servhost;
struct sockaddr_in server;
servhost = gethostbyname(server_url.host().c_str());
if (!servhost) {
throw Error("gethostbyname failed.");
}
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
memcpy((char *)&server.sin_addr, servhost->h_addr, servhost->h_length);
server.sin_port = htons(port);
if (sock == INVALID_SOCKET) {
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
throw Error("socket failed.");
}
if (connect(sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) {
throw Error("connect failed.");
}
}
if (proxy) { // testing
char port[10];
sprintf(port, ":%u", get_port(&request_url, "https", "tcp"));
std::string str = "CONNECT ";
str += request_url.data.host;
str += port;
str += " HTTP/1.0\r\n\r\n";
send_(sock, str.c_str(), str.size());
char tmp[1000];
int n = recv(sock, tmp, sizeof(tmp), 0);
int i;
for (i = 0; i < n; i++) {
char c = tmp[i];
if (c < 0x20) break;
}
if (i > 0) {
std::string s(tmp, i);
s = "proxy: " + s + '\n';
#ifdef _WIN32
OutputDebugStringA(s.c_str());
#else
fprintf(stderr, "%s", tmp);
#endif
}
}
ssl = SSL_new(sslctx());
if (!ssl) {
throw Error(get_ssl_error());
}
SSL_set_options(ssl, SSL_OP_NO_SSLv2);
SSL_set_options(ssl, SSL_OP_NO_SSLv3);
ret = SSL_set_fd(ssl, sock);
if (ret == 0) {
throw Error(get_ssl_error());
}
RAND_poll();
while (RAND_status() == 0) {
unsigned short rand_ret = rand() % 65536;
RAND_seed(&rand_ret, sizeof(rand_ret));
}
ret = SSL_connect(ssl);
if (ret != 1) {
throw Error(get_ssl_error());
}
std::string cipher = SSL_get_cipher(ssl);
cipher += '\n';
output_debug_string(cipher.c_str());
std::string version = SSL_get_cipher_version(ssl);
version += '\n';
output_debug_string(version.c_str());
X509 *x509 = SSL_get_peer_certificate(ssl);
if (x509) {
#ifndef OPENSSL_NO_SHA1
std::string fingerprint;
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
if (i > 0) {
fingerprint += ':';
}
char tmp[10];
sprintf(tmp, "%02X", x509->sha1_hash[i]);
fingerprint += tmp;
}
fingerprint += '\n';
output_debug_string(fingerprint.c_str());
#endif
long l = SSL_get_verify_result(ssl);
if (l == X509_V_OK) {
// ok
} else {
// wrong
std::string err = X509_verify_cert_error_string(l);
err += '\n';
output_debug_string(err.c_str());
}
std::vector<std::string> vec;
auto GETSTRINGS = [](X509_NAME *x509name, std::vector<std::string> *out){
out->clear();
if (x509name) {
int n = X509_NAME_entry_count(x509name);
for (int i = 0; i < n; i++) {
X509_NAME_ENTRY *entry = X509_NAME_get_entry(x509name, i);
ASN1_STRING *asn1str = X509_NAME_ENTRY_get_data(entry);
int asn1len = ASN1_STRING_length(asn1str);
unsigned char *p = ASN1_STRING_data(asn1str);
std::string str((char const *)p, asn1len);
out->push_back(str);
}
}
};
X509_NAME *subject = X509_get_subject_name(x509);
GETSTRINGS(subject, &vec);
output_debug_string("--- subject ---\n");
output_debug_strings(vec);
X509_NAME *issuer = X509_get_issuer_name(x509);
GETSTRINGS(issuer, &vec);
output_debug_string("--- issuer ---\n");
output_debug_strings(vec);
ASN1_TIME *not_before = X509_get_notBefore(x509);
ASN1_TIME *not_after = X509_get_notAfter(x509);
(void)not_before;
(void)not_after;
X509_free(x509);
} else {
// wrong
}
}
m->last_host_name = hostname;
m->last_port = port;
set_default_header(request_url, post, opt);
std::string request = make_http_request(request_url, post, proxy, true);
auto SEND = [&](char const *ptr, int len){
while (len > 0) {
int n = SSL_write(ssl, ptr, len);
if (n < 1 || n > len) {
throw WebClient::Error(get_ssl_error());
}
ptr += n;
len -= n;
}
};
SEND(request.c_str(), (int)request.size());
if (post && !post->data.empty()) {
SEND((char const *)&post->data[0], (int)post->data.size());
}
m->crlf_state = 0;
m->content_offset = 0;
receive_(opt, [&](char *ptr, int len){
return SSL_read(ssl, ptr, len);
}, out);
m->sock = sock;
m->ssl = ssl;
if (!m->keep_alive) close();
return true;
#endif
return false;
}
void WebClient::get(URL const &url, Post const *post, Response *out, WebClientHandler *handler)
{
reset();
try {
if (!m->webcx->m) {
throw Error("WebContext is null.");
}
RequestOption opt;
opt.keep_alive = m->webcx->m->use_keep_alive;
opt.handler = handler;
std::vector<char> res;
if (url.isssl()) {
#if USE_OPENSSL
https_get(url, post, opt, &res);
#endif
} else {
http_get(url, post, opt, &res);
}
if (!res.empty()) {
char const *begin = &res[0];
char const *end = begin + res.size();
char const *ptr = begin + m->content_offset;
if (ptr < end) {
out->content.assign(ptr, end);
}
}
return;
} catch (Error const &e) {
m->error = e;
close();
}
*out = Response();
}
void WebClient::parse_header(std::vector<std::string> const *header, WebClient::Response *res)
{
- if (header->size() > 0) {
+ if (!header->empty()) {
std::string const &line = header->at(0);
char const *begin = line.c_str();
char const *end = begin + line.size();
if (line.size() > 5 && strncmp(line.c_str(), "HTTP/", 5) == 0) {
int state = 0;
res->version.hi = res->version.lo = res->code = 0;
char const *ptr = begin + 5;
while (1) {
int c = 0;
if (ptr < end) {
c = *ptr & 0xff;
}
switch (state) {
case 0:
if (isdigit(c)) {
res->version.hi = res->version.hi * 10 + (c - '0');
} else if (c == '.') {
state = 1;
} else {
state = -1;
}
break;
case 1:
if (isdigit(c)) {
res->version.lo = res->version.lo * 10 + (c - '0');
} else if (isspace(c)) {
state = 2;
} else {
state = -1;
}
break;
case 2:
if (isspace(c)) {
if (res->code != 0) {
state = -1;
}
} else if (isdigit(c)) {
res->code = res->code * 10 + (c - '0');
} else {
state = -1;
}
break;
default:
state = -1;
break;
}
if (c == 0 || state < 0) {
break;
}
ptr++;
}
}
}
}
std::string WebClient::header_value(std::vector<std::string> const *header, std::string const &name)
{
for (size_t i = 1; i < header->size(); i++) {
std::string const &line = header->at(i);
char const *begin = line.c_str();
char const *end = begin + line.size();
char const *colon = strchr(begin, ':');
if (colon) {
if (strnicmp(begin, name.c_str(), name.size()) == 0) {
char const *ptr = colon + 1;
while (ptr < end && isspace(*ptr & 0xff)) ptr++;
return std::string(ptr, end);
}
}
}
return std::string();
}
std::string WebClient::header_value(std::string const &name) const
{
return header_value(&m->response.header, name);
}
std::string WebClient::content_type() const
{
std::string s = header_value("Content-Type");
char const *begin = s.c_str();
char const *end = begin + s.size();
char const *ptr = begin;
while (ptr < end) {
int c = *ptr & 0xff;
if (c == ';' || c < 0x21) break;
ptr++;
}
if (ptr < end) return std::string(begin, ptr);
return s;
}
size_t WebClient::content_length() const
{
return m->response.content.size();
}
char const *WebClient::content_data() const
{
if (m->response.content.empty()) return "";
return &m->response.content[0];
}
int WebClient::get(URL const &url, WebClientHandler *handler)
{
get(url, nullptr, &m->response, handler);
return m->response.code;
}
int WebClient::post(URL const &url, Post const *post, WebClientHandler *handler)
{
get(url, post, &m->response, handler);
return m->response.code;
}
void WebClient::close()
{
#if USE_OPENSSL
if (m->ssl) {
SSL_shutdown(m->ssl);
SSL_free(m->ssl);
m->ssl = nullptr;
}
#endif
if (m->sock != INVALID_SOCKET) {
shutdown(m->sock, 2); // SD_BOTH or SHUT_RDWR
closesocket(m->sock);
m->sock = INVALID_SOCKET;
}
}
void WebClient::add_header(std::string const &text)
{
m->request_header.push_back(text);
}
WebClient::Response const &WebClient::response() const
{
return m->response;
}
void WebClient::make_application_www_form_urlencoded(char const *begin, char const *end, WebClient::Post *out)
{
*out = WebClient::Post();
out->content_type = CT_APPLICATION_X_WWW_FORM_URLENCODED;
print(&out->data, begin, end - begin);
}
void WebClient::make_multipart_form_data(std::vector<Part> const &parts, WebClient::Post *out, std::string const &boundary)
{
*out = WebClient::Post();
out->content_type = CT_MULTIPART_FORM_DATA;
out->boundary = boundary;
for (Part const &part : parts) {
print(&out->data, "--");
print(&out->data, out->boundary);
print(&out->data, "\r\n");
if (!part.content_disposition.type.empty()) {
ContentDisposition const &cd = part.content_disposition;
std::string s;
s = "Content-Disposition: ";
s += cd.type;
auto Add = [&s](std::string const &name, std::string const &value){
if (!value.empty()) {
s += "; " + name + "=\"";
s += value;
s += '\"';
}
};
Add("name", cd.name);
Add("filename", cd.filename);
print(&out->data, s);
print(&out->data, "\r\n");
}
if (!part.content_type.empty()) {
print(&out->data, "Content-Type: " + part.content_type + "\r\n");
}
if (!part.content_transfer_encoding.empty()) {
print(&out->data, "Content-Transfer-Encoding: " + part.content_transfer_encoding + "\r\n");
}
print(&out->data, "\r\n");
print(&out->data, part.data, part.size);
print(&out->data, "\r\n");
}
print(&out->data, "--");
print(&out->data, out->boundary);
print(&out->data, "--\r\n");
}
void WebClient::make_multipart_form_data(char const *data, size_t size, WebClient::Post *out, std::string const &boundary)
{
Part part;
part.data = data;
part.size = size;
std::vector<Part> parts;
parts.push_back(part);
make_multipart_form_data(parts, out, boundary);
}
//
WebContext::WebContext()
: m(new Private)
{
#if USE_OPENSSL
SSL_load_error_strings();
SSL_library_init();
m->ctx = SSL_CTX_new(SSLv23_client_method());
#endif
}
WebContext::~WebContext()
{
#if USE_OPENSSL
SSL_CTX_free(m->ctx);
#endif
delete m;
}
void WebContext::set_keep_alive_enabled(bool f)
{
m->use_keep_alive = f;
}
void WebContext::set_http_proxy(const std::string &proxy)
{
m->http_proxy = WebProxy();
m->http_proxy.server = proxy;
}
void WebContext::set_https_proxy(const std::string &proxy)
{
m->https_proxy = WebProxy();
m->https_proxy.server = proxy;
}
const WebProxy *WebContext::http_proxy() const
{
if (!m->http_proxy.empty()) {
return &m->http_proxy;
}
return nullptr;
}
const WebProxy *WebContext::https_proxy() const
{
if (!m->https_proxy.empty()) {
return &m->https_proxy;
}
if (!m->http_proxy.empty()) {
return &m->http_proxy;
}
return nullptr;
}
bool WebContext::load_cacert(char const *path)
{
#if USE_OPENSSL
int r = SSL_CTX_load_verify_locations(m->ctx, path, nullptr);
return r == 1;
#else
return false;
#endif
}
diff --git a/src/win32/win32.cpp b/src/win32/win32.cpp
index d5efcaf..0b53983 100644
--- a/src/win32/win32.cpp
+++ b/src/win32/win32.cpp
@@ -1,354 +1,342 @@
#include <QFileInfo>
#include <QtGlobal>
#include "win32.h"
#include <Windows.h>
#include <ShlObj.h>
#include <windows.h>
#include <shlobj.h>
#include <shellapi.h>
#include <commoncontrols.h>
#include <QtWinExtras/QtWinExtras>
QString getModuleFileName()
{
wchar_t tmp[300];
DWORD n = GetModuleFileNameW(nullptr, tmp, 300);
return QString::fromUtf16((ushort const *)tmp, n);
}
-//QString getModuleFileDir()
-//{
-// QString path = getModuleFileName();
-// int i = path.lastIndexOf('\\');
-// int j = path.lastIndexOf('/');
-// if (i < j) i = j;
-// if (i > 0) path = path.mid(0, i);
-// return path;
-//}
-
QString getAppDataLocation()
{
wchar_t tmp[300];
if (SHGetSpecialFolderPathW(nullptr, tmp, CSIDL_APPDATA, TRUE)) {
return QString::fromUtf16((ushort const *)tmp);
}
return QString();
}
#include "thread.h"
#include "event.h"
#include <deque>
#define FAILED_(TEXT) throw std::string(TEXT)
-class ProcessThread : Thread {
+class ProcessThread : public Thread {
friend class StreamThread;
private:
Event start_event;
QString command;
DWORD exit_code = 0;
HANDLE hOutputRead;
HANDLE hInputWrite;
HANDLE hErrorWrite;
bool isProcessRunning = false;
class StreamThread : public Thread {
private:
ProcessThread *procthread;
std::deque<char> out;
Mutex mutex;
protected:
void run() override
{
try {
// 子プロセスの標準出力を読み出す
while (1) {
CHAR tmp[1024];
DWORD len;
if (!ReadFile(procthread->hOutputRead, tmp, sizeof(tmp), &len, nullptr) || len == 0) {
if (GetLastError() == ERROR_BROKEN_PIPE) {
break; // pipe done - normal exit path.
}
FAILED_("ReadFile"); // Something bad happened.
}
mutex.lock();
out.insert(out.end(), tmp, tmp + len);
mutex.unlock();
}
} catch (std::string const &e) { // 例外
OutputDebugStringA(e.c_str());
}
procthread = nullptr;
}
public:
void Prepare(ProcessThread *pt)
{
procthread = pt;
}
- int ReadOutput(char *ptr, int len)
+ int ReadOutput(char *ptr, size_t len)
{
mutex.lock();
size_t n = 0;
if (ptr && len > 0) {
n = out.size();
- if (len > len) {
+ if (n > len) {
n = len;
}
for (size_t i = 0; i < n; i++) {
*ptr++ = out.front();
out.pop_front();
}
}
mutex.unlock();
if (n == 0 && !procthread) return -1;
return n;
}
};
StreamThread stream;
protected:
void CloseOutput()
{
if (hOutputRead != INVALID_HANDLE_VALUE) {
if (!CloseHandle(hOutputRead)) FAILED_("CloseHandle"); // 子プロセスの標準出力を閉じる
hOutputRead = INVALID_HANDLE_VALUE;
}
}
void run() override
{
hOutputRead = INVALID_HANDLE_VALUE;
hInputWrite = INVALID_HANDLE_VALUE;
hErrorWrite = INVALID_HANDLE_VALUE;
HANDLE hOutputReadTmp = INVALID_HANDLE_VALUE;
HANDLE hOutputWrite = INVALID_HANDLE_VALUE;
HANDLE hInputWriteTmp = INVALID_HANDLE_VALUE;
HANDLE hInputRead = INVALID_HANDLE_VALUE;
try {
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = nullptr;
sa.bInheritHandle = TRUE;
HANDLE currproc = GetCurrentProcess();
// パイプを作成
if (!CreatePipe(&hOutputReadTmp, &hOutputWrite, &sa, 0))
FAILED_("CreatePipe");
// 子プロセスのエラー出力
if (!DuplicateHandle(currproc, hOutputWrite, currproc, &hErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS))
FAILED_("DuplicateHandle");
// パイプを作成
if (!CreatePipe(&hInputRead, &hInputWriteTmp, &sa, 0))
FAILED_("CreatePipe");
// 子プロセスの標準出力
if (!DuplicateHandle(currproc, hOutputReadTmp, currproc, &hOutputRead, 0, FALSE, DUPLICATE_SAME_ACCESS))
FAILED_("DupliateHandle");
// 子プロセスの標準入力
if (!DuplicateHandle(currproc, hInputWriteTmp, currproc, &hInputWrite, 0, FALSE, DUPLICATE_SAME_ACCESS))
FAILED_("DupliateHandle");
// 不要なハンドルを閉じる
CloseHandle(hOutputReadTmp);
CloseHandle(hInputWriteTmp);
// プロセス起動
PROCESS_INFORMATION pi;
STARTUPINFOW si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdInput = hInputRead; // 標準入力ハンドル
si.hStdOutput = hOutputWrite; // 標準出力ハンドル
si.hStdError = hErrorWrite; // エラー出力ハンドル
std::vector<wchar_t> tmp;
tmp.resize(command.size() + 1);
wcscpy(&tmp[0], (wchar_t const *)command.utf16());
if (!CreateProcessW(nullptr, &tmp[0], nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) {
FAILED_("CreateProcess");
}
// 不要なハンドルを閉じる
CloseHandle(hOutputWrite);
CloseHandle(hInputRead);
CloseHandle(hErrorWrite);
stream.start(); // ストリームスレッドを開始
isProcessRunning = true;
start_event.signal(); // 開始イベントを発行
stream.join(); // ストリームスレッドの終了を待つ
isProcessRunning = false;
CloseOutput(); // 標準出力を閉じる
WaitForSingleObject(pi.hProcess, INFINITE); // プロセス終了を待つ
GetExitCodeProcess(pi.hProcess, &exit_code);
// 終了
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
} catch (std::string const &e) { // 例外
stream.stop();
OutputDebugStringA(e.c_str());
}
}
void WaitForStart() // プロセスの開始を待つ
{
start_event.wait();
}
public:
- ProcessThread()
- {
- }
+ ProcessThread() = default;
- ~ProcessThread()
+ ~ProcessThread() override
{
WaitForExit();
}
void Start(QString const &cmd, bool input)
{
command = cmd;
exit_code = 0;
stream.Prepare(this);
start();
WaitForStart();
if (!input) {
CloseInput();
}
}
void WriteInput(char const *ptr, int len)
{
if (ptr && len > 0) {
DWORD l = 0;
WriteFile(hInputWrite, ptr, len, &l, nullptr);
}
}
int ReadOutput(char *ptr, int len)
{
return stream.ReadOutput(ptr, len);
}
void CloseInput()
{
if (hInputWrite != INVALID_HANDLE_VALUE) {
if (!CloseHandle(hInputWrite)) FAILED_("CloseHandle"); // 子プロセスの標準入力を閉じる
hInputWrite = INVALID_HANDLE_VALUE;
}
}
int WaitForExit()
{
CloseInput();
join();
return exit_code;
}
bool IsRunning()
{
return isProcessRunning;
}
};
int winRunCommand(QString const &cmd, QByteArray *out)
{
out->clear();
ProcessThread proc;
proc.Start(cmd, false);
while (1) {
char tmp[1024];
bool r = proc.IsRunning();
int n = proc.ReadOutput(tmp, sizeof(tmp));
if (n > 0) {
out->append(tmp, n);
} else if (!r) {
break;
}
Sleep(0);
}
return proc.WaitForExit();
}
void setEnvironmentVariable(QString const &name, QString const &value)
{
SetEnvironmentVariableW((wchar_t const *)name.utf16(), (wchar_t const *)value.utf16());
}
QString getWin32HttpProxy()
{
HKEY hk = nullptr;
auto Close = [&](){
RegCloseKey(hk);
};
try {
LSTATUS s;
s = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, KEY_READ, &hk);
if (s != ERROR_SUCCESS) throw s;
char tmp[1000];
DWORD type = 0;
DWORD len = sizeof(tmp);
s = RegQueryValueExA(hk, "ProxyServer", nullptr, &type, (unsigned char *)tmp, &len);
if (s != ERROR_SUCCESS) throw s;
while (len > 0 && tmp[len - 1] == 0) {
len--;
}
Close();
return QString::fromLatin1(tmp, len);
} catch (LSTATUS s) {
Close();
(void)s;
}
return QString();
}
namespace {
QIcon iconFromExtension_(QString const &ext, UINT flag)
{
QIcon icon;
QString name = "*." + ext;
SHFILEINFOW shinfo;
if (SHGetFileInfoW((wchar_t const *)name.utf16(), 0, &shinfo, sizeof(shinfo), flag | SHGFI_ICON | SHGFI_USEFILEATTRIBUTES) != 0) {
if (shinfo.hIcon) {
QPixmap pm = QtWin::fromHICON(shinfo.hIcon);
if (!pm.isNull()) {
icon = QIcon(pm);
}
DestroyIcon(shinfo.hIcon);
}
}
return icon;
}
}
QIcon winIconFromExtensionLarge(QString const &ext)
{
return iconFromExtension_(ext, SHGFI_LARGEICON);
}
QIcon winIconFromExtensionSmall(QString const &ext)
{
return iconFromExtension_(ext, SHGFI_SMALLICON);
}
diff --git a/src/win32/win32.h b/src/win32/win32.h
index 944e4d6..bc55ca8 100644
--- a/src/win32/win32.h
+++ b/src/win32/win32.h
@@ -1,18 +1,17 @@
#ifndef WIN32_H
#define WIN32_H
#include <QtGlobal>
#include <QIcon>
#include <QString>
QString getModuleFileName();
-//QString getModuleFileDir();
QString getAppDataLocation();
int winRunCommand(QString const &cmd, QByteArray *out);
void setEnvironmentVariable(QString const &name, QString const &value);
QIcon winIconFromExtensionLarge(QString const &ext);
QIcon winIconFromExtensionSmall(QString const &ext);
#endif // WIN32_H
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Tue, Jun 16, 12:30 AM (2 w, 1 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
71312
Default Alt Text
(59 KB)
Attached To
Mode
R77 Guitar
Attached
Detach File
Event Timeline