ukui-greeter/ 0000755 0001750 0001750 00000000000 13643021103 012077 5 ustar feng feng ukui-greeter/ukui-greeter/ 0000755 0001750 0001750 00000000000 13640355124 014521 5 ustar feng feng ukui-greeter/ukui-greeter/translations/ 0000755 0001750 0001750 00000000000 13640355124 017242 5 ustar feng feng ukui-greeter/ukui-greeter/translations/pt.ts 0000644 0001750 0001750 00000016044 13640355124 020242 0 ustar feng feng
BioAuthentication
authentication failed, restart after 2 seconds
autenticação falhou, reinicie após 2 segundos
BioDeviceView
password login
senha de acesso
fingerprint
impressão digital
fingerevin
fingerevin
iris
íris
BiometricAuthWidget
Current device:
Identify failed, Please retry.
BiometricDevicesWidget
Please select the biometric device
Device type:
Device name:
OK
DeviceType
FingerPrint
FingerVein
Iris
Face
VoicePrint
FakeDialog
cancel
GreeterWindow
CN
CN
EN
EN
GreeterWrapper
failed to start session.
falhou ao iniciar a sessão.
IconEdit
Login
Entrar
KeyboardWidget
KeyboardWidget
LoginWindow
Login
Entrar
logged in
logado
login
entrar
Password:
Senha:
login:
entrar:
Incorrect password, please input again
Senha incorreta, por favor introduza novamente
please select the type of authentication
por favor selecione o tipo de autenticação
Incorrect user name, please input again
Retry
Biometric Authentication
Password Authentication
Other Devices
MainWindow
MainWindow
Janela principal
PowerWindow
Goodbye. Would you like to…
Adeus. Você gostaria de…
Other users are currently logged in to this computer, shutting down now will also close these other sessions.
Outros usuários estão atualmente conectados a este computador, desligar agora também fechará essas outras sessões.
suspend
suspender
hibernate
hibernar
restart
reiniciar
shutdown
desligar
Goodbye. Would you like to...
SessionWindow
select the desktop environment
selecione o ambiente de área de trabalho
(Default)
(Padrão)
UserEntry
logged in
logado
UsersModel
Guest Session
Sessão Convidada
Login
Entrar
Guest
ukui-greeter/ukui-greeter/translations/es.ts 0000644 0001750 0001750 00000016137 13640355124 020231 0 ustar feng feng
BioAuthentication
authentication failed, restart after 2 seconds
autenticación fallida, reinicie después de 2 segundos
BioDeviceView
password login
contraseña de acceso
fingerprint
huella dactilar
fingerevin
fingerevin
iris
iris
BiometricAuthWidget
Current device:
Identify failed, Please retry.
BiometricDevicesWidget
Please select the biometric device
Device type:
Device name:
OK
DeviceType
FingerPrint
FingerVein
Iris
Face
VoicePrint
FakeDialog
cancel
GreeterWindow
CN
CN
EN
ES
GreeterWrapper
failed to start session.
Error al iniciar sesión.
IconEdit
Login
Iniciar sesión
KeyboardWidget
KeyboardWidget
LoginWindow
Login
Iniciar sesión
logged in
conectado
login
iniciar sesión
Password:
Contraseña:
login:
iniciar sesión:
Incorrect password, please input again
Contraseña incorrecta, por favor ingrese nuevamente
please select the type of authentication
Por favor seleccione el tipo de autenticación
Incorrect user name, please input again
Retry
Biometric Authentication
Password Authentication
Other Devices
MainWindow
MainWindow
Ventana principal
PowerWindow
Goodbye. Would you like to…
Adiós. Te gustaria…
Other users are currently logged in to this computer, shutting down now will also close these other sessions.
Otros usuarios están actualmente conectados a esta computadora, apagar ahora también cerrará estas otras sesiones.
suspend
suspender
hibernate
hibernar
restart
reiniciar
shutdown
apagar
Goodbye. Would you like to...
SessionWindow
select the desktop environment
seleccione el entorno de escritorio
(Default)
(Defecto)
UserEntry
logged in
conectado
UsersModel
Guest Session
Sesión de invitado
Login
Iniciar sesión
Guest
ukui-greeter/ukui-greeter/translations/zh_CN.ts 0000644 0001750 0001750 00000030113 13640355124 020611 0 ustar feng feng
BioAuthentication
authentication failed, restart after 2 seconds
认证失败,两秒后重新开始
BioDeviceView
password login<<
密码登录<<
password login
密码登录
fingerprint
指纹设备
fingerevin
指静脉设备
iris
虹膜设备
BiometricAuthWidget
Current device:
当前设备:
Identify failed, Please retry.
识别失败,请重试
BiometricDevicesWidget
Please select the biometric device
请选择生物设备
Device type:
设备类型:
Device name:
设备型号:
OK
确定
DeviceType
FingerPrint
指纹
FingerVein
指静脉
Iris
虹膜
Face
人脸
VoicePrint
声纹
FakeDialog
cancel
取消
GreeterWindow
Zh
中
En
英
Guest
游客登录
English
英语
Chinese
汉语
zh_CN
中
CN
中
EN
英
GreeterWrapper
failed to start session.
启动会话失败
IconEdit
Login
登录
KeyboardWidget
KeyboardWidget
LanguageWidget
Please select the language of session
请选择桌面环境语言
LoginWindow
logged in
已登录
login
登录
Incorrect user name, please input again
用户名不正确,请重新输入
Biometric Authentication
生物识别认证
Password Authentication
密码认证
Other Devices
其他设备
Retry
重试
please select the type of authentication
请选择认证方式
Please select the type of authentication
请选择认证方式
Please select the device of authentication
请选择要进行认证的生物识别设备
Guest
游客登录
Password:
密码:
login:
登录:
Password:
密码:
Incorrect password, please input again
密码错误,请重新输入
Login
登录
Username
用户名
Failed to start session
启动会话失败
password error, please input again
密码错误,请重新输入
MainWindow
MainWindow
PowerWindow
Goodbye. Would you like to…
再见,你是否想要...
Goodbye. Would you like to...
再见,你是否想要...
Other users are currently logged in to this computer, shutting down now will also close these other sessions.
当前已有其他用户登录此电脑,现在关机,其他用户的会话也将被终止。
suspend
挂起
hibernate
休眠
restart
重启
shutdown
关机
SessionWindow
select the desktop environment
选择桌面环境
Please select the desktop environment
请选择桌面环境
(Default)
(默认)
UserEntry
logged in
已登录
UsersModel
Guest Session
游客登录
Guest
游客登录
Login
登录
ukui-greeter/ukui-greeter/translations/ru.ts 0000644 0001750 0001750 00000024241 13640355124 020243 0 ustar feng feng
BioAuthentication
authentication failed, restart after 2 seconds
не удалось идентифицировать, перезапустить после 2 секунды
BioDeviceView
password login
пароль и логин
fingerprint
отпечатки пальцев
fingerevin
палец эвин
iris
айрис
BiometricAuthWidget
Current device:
Identify failed, Please retry.
BiometricDevicesWidget
Please select the biometric device
Device type:
Device name:
OK
DeviceType
FingerPrint
FingerVein
Iris
Face
VoicePrint
FakeDialog
cancel
GreeterWrapper
failed to start session.
не начала сессии.
IconEdit
Login
вход
KeyboardWidget
KeyboardWidget
LoginWindow
Login
вход
logged in
войти в систему
login
вход
Password:
пароль:
login:
вход:
Incorrect user name, please input again
Retry
Biometric Authentication
Password Authentication
Other Devices
Incorrect password, please input again
неверный пароль, пожалуйста, введите снова
please select the type of authentication
пожалуйста, выберите тип аутентификации
MainWindow
MainWindow
PowerWindow
Goodbye. Would you like to…
до свидания.хотели бы вы...
Goodbye. Would you like to...
Other users are currently logged in to this computer, shutting down now will also close these other sessions.
другие пользователи, в настоящее время вход в этот компьютер, закрыв теперь будет также закрыть эти другие занятия.
suspend
приостановить
hibernate
гибернация
restart
перезагрузка
shutdown
остановка
SessionWindow
select the desktop environment
выберите окружение рабочего стола
(Default)
(по умолчанию)
UserEntry
logged in
войти в систему
UsersModel
Guest
Guest Session
гость.
Login
вход
ukui-greeter/ukui-greeter/translations/fr.ts 0000644 0001750 0001750 00000016243 13640355124 020227 0 ustar feng feng
BioAuthentication
authentication failed, restart after 2 seconds
L'authentification a échoué, redémarrez après 2 secondes
BioDeviceView
password login
mot de passe
fingerprint
les empreintes digitales
fingerevin
doigt evin
iris
iris
BiometricAuthWidget
Current device:
Identify failed, Please retry.
BiometricDevicesWidget
Please select the biometric device
Device type:
Device name:
OK
DeviceType
FingerPrint
FingerVein
Iris
Face
VoicePrint
FakeDialog
cancel
GreeterWindow
CN
CN
EN
EN
GreeterWrapper
failed to start session.
impossible de démarrer la session.
IconEdit
Login
S'identifier
KeyboardWidget
KeyboardWidget
LoginWindow
Login
S'identifier
logged in
connecté
login
s'identifier
Password:
Mot de passe:
login:
s'identifier:
Incorrect password, please input again
Mot de passe incorrect, veuillez saisir à nouveau
please select the type of authentication
veuillez sélectionner le type d'authentification
Incorrect user name, please input again
Retry
Biometric Authentication
Password Authentication
Other Devices
MainWindow
MainWindow
Fenêtre principale
PowerWindow
Goodbye. Would you like to…
Au revoir. Voudriez-vous…
Other users are currently logged in to this computer, shutting down now will also close these other sessions.
D'autres utilisateurs sont actuellement connectés à cet ordinateur, leur fermeture ferme également ces autres sessions.
suspend
suspendre
hibernate
hiberner
restart
redémarrer
shutdown
fermer
Goodbye. Would you like to...
SessionWindow
select the desktop environment
sélectionner l'environnement de bureau
(Default)
(Défaut)
UserEntry
logged in
connecté
UsersModel
Guest Session
Session d'invité
Login
S'identifier
Guest
ukui-greeter/ukui-greeter/man/ 0000755 0001750 0001750 00000000000 13627165621 015302 5 ustar feng feng ukui-greeter/ukui-greeter/man/ukui-greeter.8 0000644 0001750 0001750 00000001064 13627165621 020004 0 ustar feng feng .\" Man Page for ukui-greeter
.TH UKUI-GREETER 8 "March 05, 2018"
.SH "NAME"
ukui-greeter \- LightDM greeter for the UKUI desktop
.SH "SYNOPSIS"
.B ukui-greeter
.SH "DESCRIPTION"
.B UKUI Greeter
is a LightDM greeter for the UKUI desktop.
It is run by the LightDM daemon if configured in lightdm.conf.
.SH "BUGS"
.SS Should you encounter any bugs, they may be reported at:
http://github.com/ukui/ukui-greeter/issues
.SH "AUTHORS"
.SS This Manual Page has been written for the UKUI Desktop Environment by:
yanghao (2018)
.SH SEE ALSO
.B lightdm
ukui-greeter/ukui-greeter/greeter/ 0000755 0001750 0001750 00000000000 13643021142 016147 5 ustar feng feng ukui-greeter/ukui-greeter/greeter/languagewidget.cpp 0000644 0001750 0001750 00000005047 13627147146 021667 0 ustar feng feng /**
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "languagewidget.h"
#include
#include
#include
#include
#include
LanguageWidget::LanguageWidget(QWidget *parent)
: QMenu (parent),
languagesVector(getLanguages())
{
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
this->installEventFilter(this);
initUserMenu();
}
void LanguageWidget::setCurrentLanguage(const QString &language)
{
for(auto action : this->actions())
{
if(action->data().toString()== language)
this->setActiveAction(action);
}
}
void LanguageWidget::initUserMenu()
{
connect(this, &QMenu::triggered,
this, &LanguageWidget::onLanguageMenuTrigged);
for(Language &lang : languagesVector)
{
QString text = lang.name + (lang.territory.isEmpty() ? "" : ("-" + lang.territory));
QAction *action = new QAction (this);
action->setText(text);
action->setData(lang.code);
addAction(action);
}
}
void LanguageWidget::onLanguageAdded(QString lang)
{
}
void LanguageWidget::onLanguageDeleted(QString lang)
{
for(auto action : this->actions())
{
if(action->data().toString() == lang)
this->removeAction(action);
}
}
void LanguageWidget::onLanguageMenuTrigged(QAction *action)
{
QString languageCode = action->data().toString();
auto iter = std::find_if(languagesVector.begin(), languagesVector.end(),
[&](const Language &language) {
return language.code == languageCode;
});
Q_EMIT languageChanged(*iter);
close();
}
bool LanguageWidget::eventFilter(QObject *obj, QEvent *event)
{
//失去焦点时隐藏窗口
if(event->type() == 23)
{
hide();
}
return false;
}
ukui-greeter/ukui-greeter/greeter/rootWindowBackground.h 0000644 0001750 0001750 00000001550 13640355124 022503 0 ustar feng feng /* rootWindowBackground.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
void setRootWindowBackground(int width,int height,char *filename);
ukui-greeter/ukui-greeter/greeter/mainwindow.h 0000644 0001750 0001750 00000006152 13621375753 020520 0 ustar feng feng /* mainwindow.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include "screenmodel.h"
enum BackgroundMode
{
DRAW_USER_BACKGROUND,
DRAW_BACKGROUND,
DRAW_COLOR,
DRAW_DEFAULT
};
enum BackgroundType
{
BACKGROUND_IMAGE,
BACKGROUND_COLOR
};
struct Background
{
BackgroundType type;
QColor color;
QString image;
};
struct Transition
{
QSharedPointer from;
QSharedPointer to;
float stage;
bool started;
};
class GreeterWindow;
class Configuration;
class MonitorWatcher;
class QTimer;
class MainWindow : public QWidget
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
void setBackground(QSharedPointer &);
protected:
void paintEvent(QPaintEvent *);
void mouseMoveEvent(QMouseEvent *);
signals:
void activeScreenChanged(const QRect& rect);
private slots:
void onScreenResized();
void onScreenCountChanged(int newCount);
void onTransition();
private:
void moveToScreen(QScreen *screen = nullptr);
void startTransition(QSharedPointer &, QSharedPointer &);
void stopTransition();
void drawTransitionAlpha(const QRect &rect);
void drawBackground(QSharedPointer &, const QRect &, float alpha = 1.0);
QPixmap * getBackground(const QString &path, const QRect &rect);
private:
ScreenModel *m_screenModel;
GreeterWindow *m_greeterWnd;
Configuration *m_configuration;
QScreen *m_activeScreen;
bool m_drawUserBackground;
QString m_defaultBackgroundPath;
QString m_backgroundPath;
QString m_backgroundColor;
QString m_lastBackgroundPath;
QPixmap m_logo;
QPixmap m_cof;
//QMap, background>
//对每张背景图片的不同分辨率进行缓存,减少CPU占用率(这里分辨率格式:1080x960)
QMap, QPixmap*> m_backgrounds;
static bool m_first;
MonitorWatcher *m_monitorWatcher;
QTimer *m_timer;
// bool m_switchBackground;
QSharedPointer m_background;
Transition m_transition;
// QPainter *m_painter;
BackgroundMode m_backgroundMode;
};
#endif // MAINWINDOW_H
ukui-greeter/ukui-greeter/greeter/usersview.cpp 0000644 0001750 0001750 00000032006 13640355124 020717 0 ustar feng feng /* usersview.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "usersview.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "xeventmonitor.h"
#define ITEM1_X 0
#define ITEM2_X (ITEM1_X + CENTER_ENTRY_WIDTH * 2 - ENTRY_WIDTH)
#define ITEM3_X (ITEM2_X + CENTER_ENTRY_WIDTH * 2 - ENTRY_WIDTH )
#define ITEM4_X (ITEM3_X + CENTER_ENTRY_WIDTH*3 - ENTRY_WIDTH*2)
#define ITEM5_X (ITEM4_X + CENTER_ENTRY_WIDTH * 2 - ENTRY_WIDTH)
UsersView::UsersView(QWidget *parent) :
QWidget(parent),
usersModel(nullptr),
currentUser(0),
lasttime(QTime::currentTime()),
mouseClickLast(QTime::currentTime())
{
QSize size = QApplication::primaryScreen()->size();
scale = QString::number(size.width() / 1920.0, 'f', 1).toFloat();
scale = scale > 0.5 ? scale : (width() >= 800 ? 0.5 : scale);
if(scale > 1)
scale = 1;
resize(CENTER_ENTRY_WIDTH*9 - ENTRY_WIDTH*4 , CENTER_ENTRY_HEIGHT);
initUI();
}
UsersView::~UsersView()
{
}
void UsersView::initUI()
{
setFocusPolicy(Qt::NoFocus);
connect(XEventMonitor::instance(), SIGNAL(keyRelease(const QString &)),
this, SLOT(onGlobalKeyRelease(const QString &)));
}
bool UsersView::eventFilter(QObject *obj, QEvent *event)
{
int interval = mouseClickLast.msecsTo(QTime::currentTime());
if(interval < 300 && interval > -300)
return false;
mouseClickLast = QTime::currentTime();
for(int i=0;itype() == QEvent::MouseButtonRelease){
setCurrentRow(i);
}
}
}
return false;
}
void UsersView::setModel(QAbstractListModel *model)
{
usersModel = model;
connect(usersModel, &QAbstractListModel::rowsInserted, this, &UsersView::onUserAdded);
connect(usersModel, &QAbstractListModel::rowsRemoved, this, &UsersView::onUserRemoved);
connect(usersModel, &QAbstractListModel::dataChanged, this, &UsersView::onUserChanged);
for(int i = 0; i < usersModel->rowCount(); i++)
insertUserEntry(i);
setCurrentRow(0);
}
void UsersView::setCurrentUser(const QString &userName, bool entered)
{
if(userName.isEmpty() || userlist.count() == 0)
return ;
for(int i = 0;iuserIndex().data(QLightDM::UsersModel::NameRole).toString() == userName)
{
setCurrentRow(i);
return ;
}
}
}
void UsersView::onGlobalKeyRelease(const QString &key)
{
int interval = lasttime.msecsTo(QTime::currentTime());
if(interval < 200 && interval > -200)
return ;
lasttime = QTime::currentTime();
if(key.compare("right",Qt::CaseInsensitive)==0)
{
rightKeyPressed();
}
else if (key.compare("left",Qt::CaseInsensitive)==0) {
leftKeyPressed();
}
}
void UsersView::leftKeyPressed()
{
if(currentUser <= 0)
return;
rightToRight();
centerToRight();
leftToRight();
currentUser-- ;
UserEntry *entry = userlist.at(currentUser);
uid_t uid = entry->userIndex().data(QLightDM::UsersModel::UidRole).toUInt();
int x = 0;
for(x = 0; x < usersModel->rowCount(); x++)
{
uid_t id= usersModel->index(x).data(QLightDM::UsersModel::UidRole).toUInt();
if(uid == id)
break;
}
QModelIndex index = usersModel->index(x, 0);
Q_EMIT currentUserChanged(index);
Q_EMIT userSelected(index);
}
void UsersView::rightKeyPressed()
{
if(currentUser >= userlist.count() - 1)
return ;
leftToLeft();
centerToleft();
rightToLeft();
currentUser++;
UserEntry *entry = userlist.at(currentUser);
uid_t uid = entry->userIndex().data(QLightDM::UsersModel::UidRole).toUInt();
int x = 0;
for(x = 0; x < usersModel->rowCount(); x++)
{
uid_t id= usersModel->index(x).data(QLightDM::UsersModel::UidRole).toUInt();
if(uid == id)
break;
}
QModelIndex index = usersModel->index(x, 0);
Q_EMIT currentUserChanged(index);
Q_EMIT userSelected(index);
}
void UsersView::showEvent(QShowEvent *event)
{
QWidget::showEvent(event);
}
void UsersView::insertUserEntry(int row)
{
QModelIndex index = usersModel->index(row, 0);
QPersistentModelIndex persistentIndex(index);
UserEntry *entry = new UserEntry(this);
entry->setUserIndex(persistentIndex);
entry->installEventFilter(this);
entry->hide();
userlist.append(entry);
}
void UsersView::removeUserEntry(int row)
{
QModelIndex index = usersModel->index(row,0);
uid_t uid = index.data(QLightDM::UsersModel::UidRole).toUInt();
for(int i=0;iuserIndex().data(QLightDM::UsersModel::UidRole).toUInt();
if(id == uid){
userlist.takeAt(i);
currentUser = 0;
}
}
}
void UsersView::onUserAdded(const QModelIndex &parent, int left, int right)
{
Q_UNUSED(parent);
for(int i = left; i <= right; i++){
insertUserEntry(i);
}
}
void UsersView::onUserRemoved(const QModelIndex &parent, int left, int right)
{
Q_UNUSED(parent);
for(int i = left; i <= right; i++){
removeUserEntry(i);
}
}
void UsersView::onUserChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
int left = topLeft.row();
int right = topLeft.row();
for(int i = left;i<=right;i++)
{
QModelIndex index = usersModel->index(i,0);
uid_t uid = index.data(QLightDM::UsersModel::UidRole).toUInt();
for(int j = 0;juserIndex().data(QLightDM::UsersModel::UidRole).toUInt();
if(id == uid)
{
entry->setUserName(index.data(Qt::DisplayRole).toString());
entry->setFace(index.data(QLightDM::UsersModel::ImagePathRole).toString());
entry->setLogin(index.data(QLightDM::UsersModel::LoggedInRole).toBool());
break;
}
}
}
}
void UsersView::centerToleft()
{
if(currentUser >= userlist.count() - 1)
return ;
UserEntry *entry = userlist.at(currentUser);
QRect rec1 = entry->geometry();
QRect rec2 = QRect(ITEM2_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
moveAnimation(entry,rec1,rec2);
}
void UsersView::centerToRight()
{
qDebug()<<"centerToRight currentuser = "<geometry();
QRect rec2 = QRect(ITEM4_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
moveAnimation(entry,rec1,rec2);
}
void UsersView::leftToLeft()
{
int left = currentUser;
if(left <= 0){
return ;
}
UserEntry *entry = userlist.at(currentUser-1);
QRect rec1 = entry->geometry();
QRect rec2 = QRect(ITEM1_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
moveAnimation(entry,rec1,rec2);
if(left >= 2){
UserEntry *entry2 = userlist.at(currentUser-2);
entry2->hide();
}
}
void UsersView::leftToRight()
{
int left = currentUser;
if(left <= 0)
return ;
UserEntry *entry = userlist.at(currentUser-1);
QRect rec1 = entry->geometry();
QRect rec2 = QRect(ITEM3_X,0,CENTER_ENTRY_WIDTH,CENTER_ENTRY_HEIGHT);
moveAnimation(entry,rec1,rec2);
entry->setSelected();
if(left >= 2){
UserEntry *entry2 = userlist.at(currentUser - 2);
rec1 = entry2->geometry();
rec2 = QRect(ITEM2_X,CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,ENTRY_WIDTH,ENTRY_HEIGHT);
moveAnimation(entry2,rec1,rec2);
}
if(left >= 3){
UserEntry *entry3 = userlist.at(currentUser - 3);
entry3->setGeometry(ITEM1_X,CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,ENTRY_WIDTH,ENTRY_HEIGHT);
entry3->show();
}
}
void UsersView::rightToLeft()
{
int right = userlist.count() - currentUser - 1;
if(right <= 0)
return ;
UserEntry *entry = userlist.at(currentUser + 1);
QRect rec1 = entry->geometry();
QRect rec2 = QRect(ITEM3_X,0,CENTER_ENTRY_WIDTH,CENTER_ENTRY_HEIGHT);
moveAnimation(entry,rec1,rec2);
entry->setSelected();
if(right >= 2){
UserEntry *entry2 = userlist.at(currentUser + 2);
rec1 = entry2->geometry();
rec2 = QRect(ITEM4_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
moveAnimation(entry2,rec1,rec2);
}
if(right >= 3){
UserEntry *entry3 = userlist.at(currentUser + 3);
entry3->setGeometry(ITEM5_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
entry3->show();
}
}
void UsersView::rightToRight()
{
int right = userlist.count() - currentUser - 1;
if(right <= 0)
return ;
UserEntry *entry = userlist.at(currentUser + 1);
QRect rec1 = entry->geometry();
QRect rec2 = QRect(ITEM5_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
moveAnimation(entry,rec1,rec2);
if(right >= 2){
UserEntry *entry2 = userlist.at(currentUser + 2);
entry2->hide();
}
}
void UsersView::moveAnimation(UserEntry *entry, QRect preRect, QRect nextRect)
{
QPropertyAnimation *pScaleAnimation = new QPropertyAnimation(entry, "geometry");
pScaleAnimation->setDuration(300);
pScaleAnimation->setStartValue(preRect);
pScaleAnimation->setEndValue(nextRect);
pScaleAnimation->setEasingCurve(QEasingCurve::InOutQuad);
pScaleAnimation->start();
}
void UsersView::setCurrentRow(int user)
{
if(userlist.count() == 0)
return ;
if(user < 0 || user >= userlist.count())
user = 0;
currentUser = user;
for(int i=0;ihide();
userlist.at(user) -> setGeometry(ITEM3_X,0,CENTER_ENTRY_WIDTH,CENTER_ENTRY_HEIGHT);
userlist.at(user)->show();
userlist.at(user)->setSelected();
for(int i = user + 1; i < userlist.count() && i - user < 3; ++i)
{
int val = i - user;
if(val == 1)
userlist.at(i)->setGeometry(ITEM4_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
if(val == 2)
userlist.at(i)->setGeometry(ITEM5_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
userlist.at(i)->show();
}
for(int i = user - 1;i >= 0 && user - i < 3; i--)
{
int val = user - i;
if(val == 1)
userlist.at(i)->setGeometry(ITEM2_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
if(val == 2)
userlist.at(i)->setGeometry(ITEM1_X,
CENTER_ENTRY_HEIGHT-ENTRY_HEIGHT,
ENTRY_WIDTH,
ENTRY_HEIGHT);
userlist.at(i)->show();
}
UserEntry *entry = userlist.at(currentUser);
uid_t uid = entry->userIndex().data(QLightDM::UsersModel::UidRole).toUInt();
int x = 0;
for(x = 0; x < usersModel->rowCount(); x++)
{
uid_t id= usersModel->index(x).data(QLightDM::UsersModel::UidRole).toUInt();
if(uid == id)
break;
}
QModelIndex index = usersModel->index(x, 0);
Q_EMIT currentUserChanged(index);
Q_EMIT userSelected(index);
}
ukui-greeter/ukui-greeter/greeter/iconedit.h 0000644 0001750 0001750 00000003625 13621375753 020144 0 ustar feng feng /* iconedit.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef ICONEDIT_H
#define ICONEDIT_H
#include
#include
#include
#include
class IconEdit : public QWidget
{
Q_OBJECT
public:
IconEdit(QWidget *parent = 0);
void setIcon(const QString &text);
void setIcon(const QIcon &icon);
void clear();
void setPrompt(const QString &);
const QString text();
void setType(QLineEdit::EchoMode type = QLineEdit::Password);
void startWaiting();
void stopWaiting();
void setCapsState(bool capsState);
protected:
void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE;
bool eventFilter(QObject *obj, QEvent *event);
private:
void updatePixmap();
signals:
void clicked(const QString &);
void focusOut();
private slots:
void clicked_cb();
void onGlobalKeyRelease(const QString &key);
private:
QLineEdit *m_edit;
QLabel *m_capsIcon;
QPushButton *m_iconButton;
QPushButton *m_modeButton;
QTimer *m_timer;
QPixmap m_waitingPixmap;
QString m_iconText; //文字作为图标
QIcon m_icon;
};
#endif // ICONEDIT_H
ukui-greeter/ukui-greeter/greeter/proxymodel.h 0000644 0001750 0001750 00000004107 13621375753 020544 0 ustar feng feng /* proxymodel.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef PROXYMODEL_H
#define PROXYMODEL_H
#include
#include
#include
/* 扩展QAbstractListModel, 用代理的方式实现在固定的model中增加额外的数据 */
class ProxyModel : public QAbstractListModel
{
Q_OBJECT
public:
ProxyModel(QObject *parent = 0);
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QHash roleNames() const;
void setSourceModel(QAbstractListModel *sourceModel);
QStandardItemModel* extraRowModel();
public slots:
void onSourceDataChanged ( const QModelIndex & topLeft, const QModelIndex & bottomRight );
void onSourceRowsInserted ( const QModelIndex & parent, int start, int end );
void onSourceRowsRemoved ( const QModelIndex & parent, int start, int end );
void onExtraDataChanged ( const QModelIndex & topLeft, const QModelIndex & bottomRight );
void onExtraRowsInserted ( const QModelIndex & parent, int start, int end );
void onExtraRowsRemoved ( const QModelIndex & parent, int start, int end );
private:
// QWeakPointer m_model;
QAbstractListModel *m_model;
QStandardItemModel *m_extraModel;
int sourceRowCount() const;
};
#endif // PROXYMODEL_H
ukui-greeter/ukui-greeter/greeter/powerwindow.cpp 0000644 0001750 0001750 00000015256 13640355124 021257 0 ustar feng feng /* powerwindow.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "powerwindow.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include "globalv.h"
PowerWindow::PowerWindow(bool hasOpenSessions, QWidget *parent)
: FakeDialog(parent),
m_hasOpenSessions(hasOpenSessions),
m_power(new QLightDM::PowerInterface(this))
{
initUI();
}
void PowerWindow::initUI()
{
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground, true);
setGeometry(parentWidget()->rect());
//重启和关机一定存在,根据是否能挂起和休眠确定窗口宽度
int cnt = 0;
if(m_power->canHibernate())
cnt++;
if(m_power->canSuspend())
cnt++;
setDialogSize(455 + 188 * cnt, 400);
//根据提示内容的长度确定窗口的高度
QFont font("ubuntu", 12);
QString text = tr("Goodbye. Would you like to...");
int lineNum = 1;
if(m_hasOpenSessions) {
QString text2 = tr("Other users are currently logged in to this computer, "
"shutting down now will also close these other sessions.");
text = QString("%1\n\n%2").arg(text2).arg(text);
QFontMetrics fm(font);
int textWide = fm.width(text2);
lineNum = qCeil(textWide * 1.0 / centerWidget()->width()) + 1 + lineNum;
}
setDialogSize(455 + 188 * cnt, 400 + 20*lineNum);
QVBoxLayout *vbox = new QVBoxLayout(centerWidget());
vbox->setContentsMargins(20, 10, 20, 2);
vbox->setSpacing(20);
m_prompt = new QLabel(centerWidget());
m_prompt->adjustSize();
m_prompt->setText(text);
m_prompt->setWordWrap(true);
m_prompt->setAlignment(Qt::AlignLeft | Qt::AlignTop);
m_prompt->setFont(font);
vbox->addWidget(m_prompt);
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setSpacing(20);
/* 挂起 */
if(m_power->canSuspend()){
QVBoxLayout *vboxSuspend = new QVBoxLayout();
m_suspend = new QLabel(centerWidget());
m_suspend->setFixedSize(168, 168);
m_suspend->setObjectName(QStringLiteral("suspend"));
m_suspend->installEventFilter(this);
m_suspendLabel = new QLabel(centerWidget());
m_suspendLabel->setAlignment(Qt::AlignCenter);
m_suspendLabel->setFixedSize(168, 30);
m_suspendLabel->setText(tr("suspend"));
vboxSuspend->addWidget(m_suspend);
vboxSuspend->addWidget(m_suspendLabel);
hbox->addLayout(vboxSuspend);
}
/* 休眠 */
if(m_power->canHibernate()) {
QVBoxLayout *vboxHibernate = new QVBoxLayout();
m_hibernate = new QLabel(centerWidget());
m_hibernate->setFixedSize(168, 168);
m_hibernate->setObjectName(QStringLiteral("hibernate"));
m_hibernate->installEventFilter(this);
m_hibernateLabel = new QLabel(centerWidget());
m_hibernateLabel->setAlignment(Qt::AlignCenter);
m_hibernateLabel->setFixedSize(168, 30);
m_hibernateLabel->setText(tr("hibernate"));
vboxHibernate->addWidget(m_hibernate);
vboxHibernate->addWidget(m_hibernateLabel);
hbox->addLayout(vboxHibernate);
}
/* 重启 */
QVBoxLayout *vboxStart = new QVBoxLayout();
m_restart = new QLabel(centerWidget());
m_restart->setFixedSize(168, 168);
m_restart->setObjectName(QStringLiteral("restart"));
m_restart->installEventFilter(this);
m_restartLabel = new QLabel(centerWidget());
m_restartLabel->setAlignment(Qt::AlignCenter);
m_restartLabel->setFixedSize(168, 30);
m_restartLabel->setText(tr("restart"));
vboxStart->addWidget(m_restart);
vboxStart->addWidget(m_restartLabel);
/* 关机 */
QVBoxLayout *vboxShutdown = new QVBoxLayout();
m_shutdown = new QLabel(centerWidget());
m_shutdown->setFixedSize(168, 168);
m_shutdown->setObjectName(QStringLiteral("shutdown"));
m_shutdown->installEventFilter(this);
m_shutdownLabel = new QLabel(centerWidget());
m_shutdownLabel->setAlignment(Qt::AlignCenter);
m_shutdownLabel->setFixedSize(168, 30);
m_shutdownLabel->setText(tr("shutdown"));
vboxShutdown->addWidget(m_shutdown);
vboxShutdown->addWidget(m_shutdownLabel);
hbox->addLayout(vboxStart);
hbox->addLayout(vboxShutdown);
vbox->addLayout(hbox);
vbox->addStretch();
}
bool PowerWindow::eventFilter(QObject *obj, QEvent *event)
{
if(obj == m_suspend) {
if(event->type() == QEvent::MouseButtonRelease){
qDebug() << "suspend";
try{
m_power->suspend();
close();
}catch(QException &e) {
qWarning() << e.what();
}
}
}else if(obj == m_hibernate) {
if(event->type() == QEvent::MouseButtonRelease){
qDebug() << "hibernate";
try{
m_power->hibernate();
close();
}catch(QException &e) {
qWarning() << e.what();
}
}
} else if(obj == m_restart) {
if(event->type() == QEvent::MouseButtonRelease){
qDebug() << "restart";
try{
m_power->restart();
close();
}catch(QException &e) {
qWarning() << e.what();
}
}
} else if(obj == m_shutdown) {
if(event->type() == QEvent::MouseButtonRelease){
try{
qDebug() << "shutdown";
m_power->shutdown();
close();
}catch(QException &e) {
qWarning() << e.what();
}
}
}
return QWidget::eventFilter(obj, event);
}
void PowerWindow::mousePressEvent(QMouseEvent *event)
{
if(!dialog()->geometry().contains(event->pos()))
close();
}
void PowerWindow::showEvent(QShowEvent *event)
{
emit windowVisibleChanged(true);
}
void PowerWindow::closeEvent(QCloseEvent *event)
{
emit windowVisibleChanged(false);
}
ukui-greeter/ukui-greeter/greeter/greeterwrapper.cpp 0000644 0001750 0001750 00000005220 13640355124 021717 0 ustar feng feng /* greeterwrapper.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "greeterwrapper.h"
#include "rootWindowBackground.h"
#include
#include
#include
#include "globalv.h"
#include "common/configuration.h"
GreeterWrapper::GreeterWrapper(QObject *parent) : QLightDM::Greeter(parent)
{
//连接到lightdm
if(!connectToDaemonSync()){
qDebug() << "connect to Daemon failed";
exit(1);
}
}
void GreeterWrapper::setLang(const QString &lang)
{
this->m_language = lang;
}
QString GreeterWrapper::lang()
{
return this->m_language;
}
void GreeterWrapper::setSession(const QString &session)
{
m_session = session;
}
QString GreeterWrapper::session()
{
return m_session;
}
QString GreeterWrapper::userName()
{
return m_userName;
}
void GreeterWrapper::setUserName(const QString &userName)
{
m_userName = userName;
}
void GreeterWrapper::setrootWindowBackground(QString path)
{
m_rootWindowBackground = path;
}
void GreeterWrapper::setrootWindow()
{
Configuration *m_configure = Configuration::instance();
QString m_defaultBackgroundPath = m_configure->getDefaultBackgroundName();
if(m_rootWindowBackground.isEmpty())
m_rootWindowBackground = m_defaultBackgroundPath;
if(m_rootWindowBackground.isEmpty())
return;
char* path;
QByteArray ba = m_rootWindowBackground.toLatin1(); // must
path=ba.data();
QDesktopWidget desktop;
setRootWindowBackground(desktop.width(),desktop.height(),path);
}
void GreeterWrapper::startSession()
{
if(isAuthenticated())
Q_EMIT authenticationSucess();
//设置language
if(!m_language.isEmpty()) {
setLanguage(m_language);
}
//启动session
setrootWindow();
if(!startSessionSync(m_session)) {
Q_EMIT startSessionFailed();
Q_EMIT showMessage(tr("failed to start session."), QLightDM::Greeter::MessageTypeError);
}
}
ukui-greeter/ukui-greeter/greeter/usersmodel.h 0000644 0001750 0001750 00000002510 13621375753 020520 0 ustar feng feng /* usersmodel.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef USERSMODEL_H
#define USERSMODEL_H
#include "proxymodel.h"
class UsersModel : public ProxyModel
{
Q_OBJECT
Q_PROPERTY(bool m_showGuest READ showGuest WRITE setShowGuest)
Q_PROPERTY(bool m_showManualLogin READ showManualLogin WRITE setShowManualLogin)
public:
explicit UsersModel(bool hideUsers=false, QObject *parent=0);
void setShowGuest(bool);
bool showGuest() const;
void setShowManualLogin(bool);
bool showManualLogin() const;
private:
bool m_showGuest;
bool m_showManualLogin;
};
#endif // USERSMODEL_H
ukui-greeter/ukui-greeter/greeter/userentry.cpp 0000644 0001750 0001750 00000016077 13640355124 020735 0 ustar feng feng /* userentry.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "userentry.h"
#include
#include
#include
#include
#include
#include
#include
#include "globalv.h"
int UserEntry::count = 0;
int UserEntry::selectedId = 0;
UserEntry::UserEntry(const QString &name, const QString &facePath, bool isLogin, QWidget *parent)
: QWidget(parent),
id(count++)
{
initUI();
setUserName(name);
setFace(facePath);
setLogin(isLogin);
}
UserEntry::UserEntry(QWidget *parent)
: UserEntry("kylin", "", true, parent)
{
setUserName("Kylin"+QString::number(id));
}
void UserEntry::initUI()
{
if (objectName().isEmpty())
setObjectName(QString::fromUtf8("Entry")+QString::number(id));
m_faceLabel = new QLabel(this);
m_faceLabel->setObjectName(QString::fromUtf8("faceLabel"));
m_faceLabel->setScaledContents(true);
m_faceLabel->installEventFilter(this);
m_nameLabel = new QLabel(this);
m_nameLabel->setObjectName(QString::fromUtf8("nameLabel"));
m_nameLabel->setFont(QFont("Ubuntu", fontSize));
m_loginLabel = new QLabel(this);
m_loginLabel->setObjectName(QString::fromUtf8("isloginLabel"));
m_loginLabel->setAlignment(Qt::AlignCenter);
}
void UserEntry::paintEvent(QPaintEvent *event)
{
//绘制阴影边框
return QWidget::paintEvent(event);
}
void UserEntry::resizeEvent(QResizeEvent *)
{
setResize();
}
bool UserEntry::eventFilter(QObject *obj, QEvent *event)
{
if(obj == m_faceLabel){
if(event->type() == QEvent::MouseButtonPress){
QMouseEvent *mouseEvent = static_cast(event);
if(mouseEvent->button() == Qt::LeftButton){
Q_EMIT pressed();
return true;
}
}
}
return QWidget::eventFilter(obj, event);
}
void UserEntry::onClicked()
{
this->setSelected();
emit clicked(index.row());
}
QPixmap UserEntry::PixmapToRound(const QPixmap &src, int radius)
{
if (src.isNull()) {
return QPixmap();
}
QPixmap pixmapa(src);
QPixmap pixmap(radius*2,radius*2);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
QPainterPath path;
path.addEllipse(0, 0, radius*2, radius*2);
painter.setClipPath(path);
painter.drawPixmap(0, 0, radius*2, radius*2, pixmapa);
return pixmap;
}
void UserEntry::setFace(const QString &facePath)
{
this->m_face = facePath;
QFile faceFile(facePath);
if(!faceFile.exists())
this->m_face = ":/resource/default_face.png";
if(id == selectedId){
const QString SheetStyle = QString("border-radius: %1px; border:2px solid white;").arg(CENTER_IMG_WIDTH/2);
m_faceLabel->setStyleSheet(SheetStyle);
userface = scaledPixmap(CENTER_IMG_WIDTH, CENTER_IMG_WIDTH, m_face);
userface = PixmapToRound(userface, CENTER_IMG_WIDTH/2);
}
else{
const QString SheetStyle = QString("border-radius: %1px; border:2px solid white;").arg(IMG_WIDTH/2);
m_faceLabel->setStyleSheet(SheetStyle);
userface = scaledPixmap(IMG_WIDTH, IMG_WIDTH, m_face);
userface = PixmapToRound(userface, IMG_WIDTH/2);
}
m_faceLabel->setAlignment(Qt::AlignCenter);
m_faceLabel->setPixmap(userface);
}
const QString& UserEntry::userName()
{
return this->m_name;
}
void UserEntry::setUserName(const QString &name)
{
if(m_name != name)
m_name = name;
this->m_nameLabel->setText(m_name);
/* 当用户名短的时候居中, 否则是居左显示前半部分 */
QFont font("ubuntu", 16);
QFontMetrics fm(font);
int pixelsWide = fm.width(m_name);
if(pixelsWide < IMG_WIDTH)
m_nameLabel->setAlignment(Qt::AlignCenter);
else{
QFontMetrics fontWidth(font);
QString str = fontWidth.elidedText(m_name,Qt::ElideRight,IMG_WIDTH);
this->m_nameLabel->setText(str);
}
}
void UserEntry::setLogin(bool isLogin)
{
if(m_login != isLogin)
m_login = isLogin;
if(isLogin)
m_loginLabel->show();
else
m_loginLabel->hide();
}
void UserEntry::setResize()
{
QRect faceRect,nameRect,loginRect;
const QString SheetStyle = QString("border-radius: %1px; border:2px solid white;").arg(width()/2);
m_faceLabel->setStyleSheet(SheetStyle);
faceRect.setRect(0, 0, width(), width());
userface = scaledPixmap(width(), width(), m_face);
userface = PixmapToRound(userface, width()/2);
m_faceLabel->setGeometry(faceRect);
m_faceLabel->move((width() - m_faceLabel->width())/2,m_faceLabel->y());
m_faceLabel->setPixmap(userface);
m_loginLabel->setPixmap(QPixmap(":/resource/is_logined.png"));
m_loginLabel->resize(24,24);
m_loginLabel->setGeometry(m_faceLabel->x(),m_faceLabel->y(),24,24);
if(id == selectedId)
{
m_nameLabel->setFont(QFont("Ubuntu", 16));
QGraphicsOpacityEffect opacityEffect;
opacityEffect.setOpacity(1);
m_faceLabel->setGraphicsEffect(&opacityEffect);
m_nameLabel->adjustSize();
m_nameLabel->move((width() - m_nameLabel->width())/2,m_faceLabel->y() + m_faceLabel->height() + 25);
}
else
{
m_nameLabel->setFont(QFont("Ubuntu", 14));
QGraphicsOpacityEffect opacityEffect;
opacityEffect.setOpacity(0.6);
m_faceLabel->setGraphicsEffect(&opacityEffect);
m_nameLabel->adjustSize();
m_nameLabel->move((width() - m_nameLabel->width())/2,m_faceLabel->y() + m_faceLabel->height() + 32);
}
}
void UserEntry::setSelected(bool selected)
{
if(selected) {
selectedId = this->id;
}
setResize();
}
bool UserEntry::selected()
{
return id == selectedId;
}
void UserEntry::setUserIndex(const QPersistentModelIndex &index)
{
Q_ASSERT(index.isValid());
this->index = index;
QString realName = index.data(QLightDM::UsersModel::RealNameRole).toString();
QString name = index.data(QLightDM::UsersModel::NameRole).toString();
QString facePath = index.data(QLightDM::UsersModel::ImagePathRole).toString();
bool isLoggedIn = index.data(QLightDM::UsersModel::LoggedInRole).toBool();
setUserName(realName.isEmpty() ? name : realName);
setFace(facePath);
setLogin(isLoggedIn);
}
QPersistentModelIndex UserEntry::userIndex()
{
return index;
}
ukui-greeter/ukui-greeter/greeter/screenmodel.h 0000644 0001750 0001750 00000002567 13621375753 020652 0 ustar feng feng /* screenmodel.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef SCREENMODEL_H
#define SCREENMODEL_H
#include
#include
#include
class QDesktopWidget;
class ScreenModel : public QAbstractListModel
{
Q_OBJECT
public:
ScreenModel(QObject *parent=0);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::UserRole) const;
private slots:
void onScreenResized(int screen);
void onScreenCountChanged(int newCount);
void loadScreens();
private:
QVector m_screen;
QDesktopWidget *_desktop;
};
#endif // SCREENMODEL_H
ukui-greeter/ukui-greeter/greeter/pagelistview.h 0000644 0001750 0001750 00000004721 13621375753 021047 0 ustar feng feng /* pagelistview.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef PAGELISTVIEW_H
#define PAGELISTVIEW_H
#include
#include
#include
#include
#include
#include "userentry.h"
#include "usersmodel.h"
class PageListView : public QWidget
{
Q_OBJECT
Q_PROPERTY(int page NOTIFY pageChanged)
public:
explicit PageListView(QWidget *parent = 0);
void setModel(QSharedPointer);
void pageUp(); //切换到上一页 留给父窗口通过按钮调用
void pageDown(); //切换到下一页
bool hasPrev();
bool hasNext();
protected:
void keyReleaseEvent(QKeyEvent *);
void resizeEvent(QResizeEvent *);
private:
UserEntry* createEntry(int );
void drawPage();
void goHome(); //切换到首页
void goEnd(); //切换到尾页
void preItem(); //切换到上一项
void nextItem(); //切换到下一项
void moveFocus(); //移动焦点
signals:
void pageChanged(); //当焦点所在项发生变化时发出
void selectedChanged(const QModelIndex& index); //当选定用户时发出
private slots:
void onEntrySelected(const QString &name);
void onUserChanged(const QModelIndex&, const QModelIndex&);
void onUserInserted(const QModelIndex&, int, int);
void onUserRemoved(const QModelIndex&, int, int);
private:
QSharedPointer m_model;
QVector m_itemList;
QHBoxLayout *m_layout;
int m_lastItem; //上一次选择的项
int m_curItem; //当前焦点所在项
int m_end; //当前页的最后一项
int m_lastend; //上一次的最后一项
int m_itemCount;
};
#endif // PAGELISTVIEW_H
ukui-greeter/ukui-greeter/greeter/proxymodel.cpp 0000644 0001750 0001750 00000010764 13621375753 021105 0 ustar feng feng /* proxymodel.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "proxymodel.h"
#include
ProxyModel::ProxyModel(QObject *parent)
: QAbstractListModel(parent),
m_model(nullptr),
m_extraModel(new QStandardItemModel(this))
{
connect(m_extraModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)),
this, SLOT(onExtraRowsInserted(const QModelIndex&, int, int)));
connect(m_extraModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)),
this, SLOT(onExtraRowsRemoved(const QModelIndex&, int, int)));
connect(m_extraModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)),
this, SLOT(onExtraDataChanged(const QModelIndex&, const QModelIndex&)));
}
QVariant ProxyModel::data(const QModelIndex &index, int role) const
{
if(index.row() < sourceRowCount())
return m_model->index(index.row(), 0).data(role);
else
return m_extraModel->index(index.row() - sourceRowCount(), 0).data(role);
}
int ProxyModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return sourceRowCount() + m_extraModel->rowCount();
}
QHash ProxyModel::roleNames() const
{
return m_model == nullptr ? QHash() : m_model->roleNames();
}
QStandardItemModel* ProxyModel::extraRowModel()
{
return m_extraModel;
}
void ProxyModel::setSourceModel(QAbstractListModel *sourceModel)
{
if(m_model)
{
disconnect(m_model, SIGNAL(rowsInserted(const QModelIndex&, int, int)),
this, SLOT(onSourceRowsInserted(const QModelIndex&, int, int)));
disconnect(m_model, SIGNAL(rowsRemoved(const QModelIndex&, int, int)),
this, SLOT(onSourceRowsRemoved(const QModelIndex&, int, int)));
disconnect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(onSourceDataChanged(const QModelIndex&, const QModelIndex&)));
}
// m_model = QWeakPointer(sourceModel);
m_model = sourceModel;
// reset();
beginResetModel();
endResetModel();
// setRoleNames(m_model->roleNames());
connect(m_model, SIGNAL(rowsInserted(const QModelIndex&, int, int)),
this, SLOT(onSourceRowsInserted(const QModelIndex&, int, int)));
connect(m_model, SIGNAL(rowsRemoved(const QModelIndex&, int, int)),
this, SLOT(onSourceRowsRemoved(const QModelIndex&, int, int)));
connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(onSourceDataChanged(const QModelIndex&, const QModelIndex&)));
}
int ProxyModel::sourceRowCount() const
{
return m_model == nullptr ? 0 : m_model->rowCount();
}
void ProxyModel::onSourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
dataChanged(createIndex(topLeft.row(), 0), createIndex(bottomRight.row(), 0));
}
void ProxyModel::onSourceRowsInserted(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
beginInsertRows(parent, start, end);
endInsertRows();
}
void ProxyModel::onSourceRowsRemoved(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
beginRemoveRows(parent, start, end);
endRemoveRows();
}
void ProxyModel::onExtraDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
dataChanged(createIndex(sourceRowCount() + topLeft.row(), 0), createIndex(sourceRowCount() + bottomRight.row(), 0));
}
void ProxyModel::onExtraRowsInserted(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
beginInsertRows(parent, sourceRowCount() + start, sourceRowCount() + end);
endInsertRows();
}
void ProxyModel::onExtraRowsRemoved(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
beginRemoveRows(parent, sourceRowCount() + start, sourceRowCount() + end);
endRemoveRows();
}
ukui-greeter/ukui-greeter/greeter/greeterwindow.h 0000644 0001750 0001750 00000006141 13640355124 021216 0 ustar feng feng /* greeterwindow.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef GREETERWINDOW_H
#define GREETERWINDOW_H
#include
#include
#include
#include "loginwindow.h"
#include "sessionwindow.h"
#include "usersmodel.h"
#include "greeterwrapper.h"
class UsersView;
class QProcess;
class QGraphicsOpacityEffect;
class Configuration;
class VirtualKeyboard;
class LanguageWidget;
class Language;
class PowerWindow;
class GreeterWindow : public QWidget
{
Q_OBJECT
public:
GreeterWindow(QWidget *parent = 0);
void initUI();
protected:
void resizeEvent(QResizeEvent *);
void keyReleaseEvent(QKeyEvent *event);
bool eventFilter(QObject *obj, QEvent *event);
private slots:
void onUserSelected(const QModelIndex &);
void onCurrentUserChanged(const QModelIndex&);
void timedAutologin();
void showPowerWnd();
void showVirtualKeyboard();
void onLanguageChanged(const Language &language);
void showSessionWnd();
void onSessionChanged(const QString &session);
void onUserChangedByManual(const QString &userName);
void showLanguageWnd();
void setWindowVisible(bool visible);
private:
void switchWnd(int);
void setBackground(const QModelIndex &index);
void setVirkeyboardPos();
void setWindowPos(QWidget *widget, Qt::Alignment align = Qt::AlignCenter);
bool sessionIsValid(const QString &session);
void updateLanguage(QString userName);
void updateSession(QString userName);
void setUserWindowVisible(bool visible);
QString getAccountBackground(uid_t uid);
UsersView *m_userWnd;
LoginWindow *m_loginWnd;
SessionWindow *m_sessionWnd;
PowerWindow *m_powerWnd;
QPushButton *m_keyboardLB;
QPushButton *m_powerLB;
QPushButton *m_sessionLB;
QPushButton *m_languageLB;
VirtualKeyboard *m_virtualKeyboard;
LanguageWidget *m_languageWnd;
GreeterWrapper *m_greeter;
UsersModel *m_usersModel;
QAbstractItemModel *m_sessionsModel;
Configuration *m_configuration;
bool m_languageHasChanged;
bool m_sessionHasChanged;
QTimer *timer;
QWidget *widgetTime;
QLabel *lblDate;
QLabel *lblTime;
};
#endif // GREETERWINDOW_H
ukui-greeter/ukui-greeter/greeter/loginwindow.h 0000644 0001750 0001750 00000012373 13635402757 020706 0 ustar feng feng /* loginwindow.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef LOGINWINDOW_H
#define LOGINWINDOW_H
#include
#include
#include
#include "biometricdeviceinfo.h"
class QTimer;
class QLabel;
class QPushButton;
class QListWidget;
class GreeterWrapper;
class IconEdit;
class BiometricProxy;
class BiometricAuthWidget;
class BiometricDevicesWidget;
class LoginWindow : public QWidget
{
Q_OBJECT
public:
explicit LoginWindow(GreeterWrapper *greeter, QWidget *parent = 0);
~LoginWindow(){}
bool setUserIndex(const QModelIndex& index);
void setGreeter(GreeterWrapper *greeter);
void setUserName(const QString& userName);
QString getUserName();
QString getRealName();
void setFace(const QString& faceFile);
void setLoggedIn(bool isLoggedIn);
void setPrompt(const QString& text);
QString getPassword();
void reset();
bool isloginauth;
void setDirLogin();
protected:
void showEvent(QShowEvent *);
void resizeEvent(QResizeEvent *);
void keyReleaseEvent(QKeyEvent *event);
signals:
void back();
void bioDeviceIsChoosed(bool);
/**
* @brief 手动输入用户名
* @param userName 用户名
*/
void userChangedByManual(const QString &userName);
public slots:
void onShowMessage(QString text, QLightDM::Greeter::MessageType type);
void onShowPrompt(QString text, QLightDM::Greeter::PromptType type);
void onAuthenticationComplete();
void setUserNotInView(const QString &userName);
private slots:
void onLogin(const QString &str);
void onBackButtonClicked();
void onBiometricButtonClicked();
void onPasswordButtonClicked();
void onOtherDevicesButtonClicked();
void onRetryButtonClicked();
void onDeviceChanged(const DeviceInfoPtr &deviceInfo);
void onBiometricAuthComplete(bool result);
void onMessageButtonClicked();
private:
void initUI();
void initBiometricWidget();
void initBiometricButtonWidget();
void setChildrenGeometry();
void setBiometricWidgetGeometry();
void setBiometricButtonWidgetGeometry();
void startAuthentication();
void startWaiting();
void stopWaiting();
void clearMessage();
void performBiometricAuth();
void skipBiometricAuth();
void showPasswordAuthWidget();
void showBiometricAuthWidget();
void showBiometricDeviceWidget();
QPixmap DrawRound(QPixmap &src, int radius);
QPixmap PixmapToRound(const QPixmap &src, int radius);
void show_authenticated (bool successful = true);
private:
GreeterWrapper *m_greeter;
QString m_name; //m_nameLabel显示的是全名(显示的),m_name保存的是真名(用于登录的)
qint32 m_uid; //用户id
//手动输入用户标记,设置该标记的原因是判断是不是手动输入用户,
//如果输入了无法登录的用户,就会一直输出密码错误信息
bool isManual;
//密码错误标记,设置该标志的原因是,在有生物识别模块的情况下用户选择了密码登录,输入了错误的密码,
//此时应该直接进入密码登录,而不是再次进入登录生物识别设备选择界面
// bool isPasswordError;
enum AuthMode { PASSWORD, BIOMETRIC, UNKNOWN };
AuthMode authMode;
// 生物识别认证
int m_deviceCount;
int m_featureCount;
QString m_deviceName;
DeviceInfoPtr m_deviceInfo;
BiometricProxy *m_biometricProxy;
BiometricAuthWidget *m_biometricAuthWidget;
BiometricDevicesWidget *m_biometricDevicesWidget;
QWidget *m_buttonsWidget;
QPushButton *m_biometricButton;
QPushButton *m_passwordButton;
QPushButton *m_otherDeviceButton;
QPushButton *m_retryButton;
// UI
QPushButton *m_backButton; //返回用户列表
QLabel *m_faceLabel; //头像
QLabel *m_nameLabel; //用户名
QLabel *m_isLoginLabel; //提示是否已登录
QWidget *m_passwdWidget; //放置密码输入框和信息列表
IconEdit *m_passwordEdit; //密码输入框
QLabel *m_messageLabel; //PAM消息显示
QPushButton *m_messageButton;
bool isretry = true;
bool prompted = false;
bool unacknowledged_messages = false;
bool m_name_is_login = false;
bool isauto_switch = false;
bool direct_login = false;
};
#endif // LOGINWINDOW_H
ukui-greeter/ukui-greeter/greeter/usersmodel.cpp 0000644 0001750 0001750 00000005276 13621375753 021067 0 ustar feng feng /* usersmodel.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "usersmodel.h"
#include
#include
UsersModel::UsersModel(bool hideUsers, QObject *parent) :
ProxyModel(parent),
m_showGuest(false)
{
if(!hideUsers)
setSourceModel(new QLightDM::UsersModel(this));
else {
qDebug() << "hide users, show manual";
setShowManualLogin(true);
}
}
void UsersModel::setShowGuest(bool isShowGuest)
{
if(m_showGuest == isShowGuest)
return;
m_showGuest = isShowGuest;
if(m_showGuest)
{
QStandardItem *guest = new QStandardItem(tr("Guest"));
guest->setData("*guest", QLightDM::UsersModel::NameRole);
guest->setData(tr("Guest"), QLightDM::UsersModel::RealNameRole);
extraRowModel()->appendRow(guest);
}
else
{
QStandardItemModel *model = extraRowModel();
for(int i = 0; i < model->rowCount(); i++){
QStandardItem *item = model->item(i, 0);
if(item->text() == tr("Guest Session")){
model->removeRow(i);
}
}
}
}
bool UsersModel::showGuest() const
{
return m_showGuest;
}
void UsersModel::setShowManualLogin(bool isShowManualLogin)
{
if(m_showManualLogin == isShowManualLogin)
return;
m_showManualLogin = isShowManualLogin;
if(m_showManualLogin){
QStandardItem *manualLogin = new QStandardItem(tr("Login"));
manualLogin->setData("*login", QLightDM::UsersModel::NameRole);
manualLogin->setData(tr("Login"), QLightDM::UsersModel::RealNameRole);
extraRowModel()->appendRow(manualLogin);
}
else{
QStandardItemModel *model = extraRowModel();
for(int i = 0; i < model->rowCount(); i++){
QStandardItem *item = model->item(i, 0);
if(item->text() == tr("Login")){
model->removeRow(i);
}
}
}
}
bool UsersModel::showManualLogin() const
{
return m_showManualLogin;
}
ukui-greeter/ukui-greeter/greeter/greeterwrapper.h 0000644 0001750 0001750 00000002753 13621375753 021405 0 ustar feng feng /* greeterwrapper.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef GREETERWRAPPER_H
#define GREETERWRAPPER_H
#include
class GreeterWrapper : public QLightDM::Greeter
{
Q_OBJECT
public:
explicit GreeterWrapper(QObject *parent=0);
void setLang(const QString&);
QString lang();
void setSession(const QString&);
QString session();
void startSession();
QString userName();
void setUserName(const QString &);
void setrootWindow();
void setrootWindowBackground(QString);
private:
QString m_language;
QString m_session;
QString m_userName;
QString m_rootWindowBackground;
signals:
void aboutToLogin();
void startSessionFailed();
void authenticationSucess();
};
#endif // GREETERWRAPPER_H
ukui-greeter/ukui-greeter/greeter/greeterwindow.cpp 0000644 0001750 0001750 00000055375 13640355124 021566 0 ustar feng feng /* greeterwindow.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "greeterwindow.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "globalv.h"
#include "loginwindow.h"
#include "usersview.h"
#include "usersmodel.h"
#include "powerwindow.h"
#include "common/configuration.h"
#include "mainwindow.h"
#include "virtualkeyboard.h"
#include "languagewidget.h"
#include "language.h"
float scale;
int fontSize;
GreeterWindow::GreeterWindow(QWidget *parent)
: QWidget(parent),
m_userWnd(nullptr),
m_loginWnd(nullptr),
m_sessionWnd(nullptr),
m_powerWnd(nullptr),
m_sessionLB(nullptr),
m_virtualKeyboard(nullptr),
m_languageWnd(nullptr),
m_greeter(new GreeterWrapper()),
m_usersModel(new UsersModel(m_greeter->hideUsersHint())),
m_sessionsModel(new QLightDM::SessionsModel(QLightDM::SessionsModel::LocalSessions)),
m_configuration(Configuration::instance()),
m_languageHasChanged(false),
m_sessionHasChanged(false)
{
scale = 1.0;
if(m_greeter->hasGuestAccountHint()){ //允许游客登录
qDebug() << "allow guest";
m_usersModel->setShowGuest(true);
}
if(m_greeter->showManualLoginHint()) { //允许手动输入用户名
qDebug() << "allow manual login";
m_usersModel->setShowManualLogin(true);
}
m_greeter->setSession(m_greeter->defaultSessionHint());
for(int i = 0; i < m_usersModel->rowCount(); i++)
qDebug() << "load user " << m_usersModel->index(i).
data(QLightDM::UsersModel::NameRole).toString();
for(int i = 0; i < m_sessionsModel->rowCount(); i++)
qDebug() << "load session " << m_sessionsModel->index(i, 0).
data(QLightDM::SessionsModel::KeyRole).toString();
connect(m_greeter, SIGNAL(autologinTimerExpired()),this, SLOT(timedAutologin()));
connect(m_greeter, SIGNAL(authenticationSucess()), this, SLOT(hide()));
connect(m_greeter, SIGNAL(startSessionFailed()), this, SLOT(show()));
installEventFilter(this);
}
void GreeterWindow::initUI()
{
installEventFilter(this);
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [&]{
QString time = QDateTime::currentDateTime().toString("hh:mm");
lblTime->setText(time);
QString date = QDate::currentDate().toString("yyyy/MM/dd dddd");
lblDate->setText(date);
});
widgetTime = new QWidget(this);
QVBoxLayout *widgetlayout = new QVBoxLayout(widgetTime);
lblDate = new QLabel(this);
lblTime = new QLabel(this);
widgetlayout->addWidget(lblTime);
widgetlayout->addWidget(lblDate);
QString time = QDateTime::currentDateTime().toString("hh:mm");
lblTime->setText(time);
lblTime->setStyleSheet("QLabel{color:white; font-size: 50px;}");
lblTime->adjustSize();
timer->start(1000);
QString date = QDate::currentDate().toString("yyyy/MM/dd dddd");
qDebug() << "current date: " << date;
lblDate->setText(date);
lblDate->setStyleSheet("QLabel{color:white; font-size: 16px;}");
lblDate->adjustSize();
widgetTime->adjustSize();
//电源对话框打开按钮
m_powerLB = new QPushButton(this);
m_powerLB->setObjectName(QStringLiteral("powerButton"));
m_powerLB->setIcon(QPixmap(":/resource/power.png"));
m_powerLB->setIconSize(QSize(39, 39));
m_powerLB->setFocusPolicy(Qt::NoFocus);
m_powerLB->setFixedSize(48, 48);
m_powerLB->setCursor(Qt::PointingHandCursor);
m_powerLB->installEventFilter(this);
connect(m_powerLB, &QPushButton::clicked, this, &GreeterWindow::showPowerWnd);
//虚拟键盘启动按钮
m_keyboardLB = new QPushButton(this);
m_keyboardLB->setObjectName(QStringLiteral("keyboardButton"));
m_keyboardLB->setIcon(QPixmap(":/resource/keyboard.png"));
m_keyboardLB->setIconSize(QSize(30, 30));
m_keyboardLB->setFocusPolicy(Qt::NoFocus);
m_keyboardLB->setFixedSize(48, 48);
m_keyboardLB->setCursor(Qt::PointingHandCursor);
m_keyboardLB->installEventFilter(this);
connect(m_keyboardLB, &QPushButton::clicked,
this, &GreeterWindow::showVirtualKeyboard);
//桌面环境选择按钮
if(m_sessionsModel->rowCount() > 0)
{
m_sessionLB = new QPushButton(this);
m_sessionLB->setObjectName((QStringLiteral("sessionButton")));
m_sessionLB->setIconSize(QSize(39, 39));
m_sessionLB->setFocusPolicy(Qt::NoFocus);
m_sessionLB->setFixedSize(48, 48);
m_sessionLB->setCursor(Qt::PointingHandCursor);
m_sessionLB->installEventFilter(this);
m_sessionLB->setIcon(QIcon(IMAGE_DIR + QString("badges/unknown_badge.png")));
onSessionChanged(m_greeter->defaultSessionHint());
connect(m_sessionLB, &QPushButton::clicked, this, &GreeterWindow::showSessionWnd);
}
//语言选择按钮
m_languageLB = new QPushButton(this);
m_languageLB->setObjectName(QStringLiteral("languageButton"));
m_languageLB->setFocusPolicy(Qt::NoFocus);
m_languageLB->setFont(QFont("Ubuntu", 16));
m_languageLB->setFixedHeight(48);
m_languageLB->setCursor(Qt::PointingHandCursor);
LanguagesVector defaultLang = getLanguages();
if(defaultLang.count()>0){
m_languageLB->setText(defaultLang.at(0).name);
m_languageLB->adjustSize();
}
else{
m_languageLB->hide();
}
connect(m_languageLB, &QPushButton::clicked, this, &GreeterWindow::showLanguageWnd);
//用户列表
m_userWnd = new UsersView(this);
connect(m_userWnd, &UsersView::currentUserChanged, this, &GreeterWindow::onCurrentUserChanged);
connect(m_userWnd, &UsersView::userSelected, this, &GreeterWindow::onUserSelected);
//登录窗口
m_loginWnd = new LoginWindow(m_greeter, this);
connect(m_loginWnd, &LoginWindow::userChangedByManual,
this, &GreeterWindow::onUserChangedByManual);
connect(m_loginWnd, &LoginWindow::bioDeviceIsChoosed,
this, &GreeterWindow::setUserWindowVisible);
connect(m_userWnd, &UsersView::userNotFound, m_loginWnd, &LoginWindow::setUserNotInView);
m_userWnd->setModel(m_usersModel);
setFocusProxy(m_loginWnd);
//显示lightdm传过来的被选中的用户且自动进入认证界面 -- SwitchToUser()
QString selectedUser = m_greeter->selectUserHint();
if(!selectedUser.isEmpty())
{
qDebug() << "SelectUserHint: " << selectedUser;
m_userWnd->setCurrentUser(selectedUser, true);
}
// SwitchToGuest()且自动进入认证界面
else if(m_greeter->selectGuestHint())
{
qDebug() << "SelectGuest";
m_userWnd->setCurrentUser("*guest", true);
}
//如果没有可显示出来的用户,则开启手动输入用户名登录
else if(m_usersModel->rowCount() == 0)
{
m_usersModel->setShowManualLogin(true);
QString userName = m_usersModel->index(0, 0).data(QLightDM::UsersModel::NameRole).toString();
m_userWnd->setCurrentUser(userName, true);
}
//如果只有一个用户,直接进入认证界面
else if(m_usersModel->rowCount() == 1)
{
QString userName = m_usersModel->index(0, 0).data(QLightDM::UsersModel::NameRole).toString();
m_userWnd->setCurrentUser(userName, true);
}
else
{
//选中上一次登录的用户,但不进入认证界面
QString lastLoginUser = Configuration::instance()->getLastLoginUser();
m_userWnd->setCurrentUser(lastLoginUser);
}
}
void GreeterWindow::setUserWindowVisible(bool visible)
{
if(m_userWnd)
m_userWnd->setVisible(visible);
if(!visible){
QRect loginRect((width()-m_loginWnd->width())/2,
widgetTime->y() + widgetTime->height() + 176*scale,
m_loginWnd->width(),
m_loginWnd->height());
m_loginWnd->setGeometry(loginRect);
}
else{
QRect loginRect((width()-m_loginWnd->width())/2,
m_userWnd->y() + m_userWnd->height() + 46 *scale,
m_loginWnd->width(),
height() - (m_userWnd->y() + m_userWnd->height() + 46 *scale));
m_loginWnd->setGeometry(loginRect);
}
}
/**
* @brief GreeterWindow::resizeEvent
* @param event
* GreeterWindow的大小发生改变
*/
void GreeterWindow::resizeEvent(QResizeEvent *event)
{
QSize size = event->size();
//重新计算缩放比例
scale = QString::number(size.width() / 1920.0, 'f', 1).toFloat();
scale = scale > 0.5 ? scale : (width() >= 800 ? 0.5 : scale);
if(scale > 1)
scale = 1;
fontSize = scale > 0.5 ? 10 : 8;
qDebug() << "GreeterWindow resize to " << size;
qDebug() << "scale: " << scale;
if(m_userWnd){
m_userWnd->resize(CENTER_ENTRY_WIDTH*9 - ENTRY_WIDTH*4, CENTER_ENTRY_HEIGHT);
QRect userRect((width()-m_userWnd->width())/2,
widgetTime->y() + widgetTime->height() + 176*scale,
m_userWnd->width(), m_userWnd->height());
m_userWnd->setGeometry(userRect);
}
if(m_loginWnd){
QRect loginRect((width()-m_loginWnd->width())/2,
m_userWnd->y() + m_userWnd->height() + 46 *scale,
m_loginWnd->width(),
height() - (m_userWnd->y() + m_userWnd->height() + 46 *scale));
m_loginWnd->setGeometry(loginRect);
}
if(m_languageWnd)
{
m_languageWnd->move(m_languageLB->x(),m_languageLB->y()+m_languageWnd->height());
}
//电源按钮位置
int x = 39;
int y = 66;
x+=m_powerLB->width();
m_powerLB->move(this->width() - x,height() - y);
//虚拟键盘按钮位置
x += (m_keyboardLB->width() + 10);
m_keyboardLB->move(this->width() - x, height() - y);
//桌面环境选择按钮位置
if(m_sessionLB)
{
x += (m_sessionLB->width() + 10);
m_sessionLB->move(this->width() - x, height() - y);
}
//语言选择按钮位置
x += (m_languageLB->width() + 10);
m_languageLB->move(this->width() - x, height() - y);
widgetTime->move((width()-widgetTime->geometry().width())/2, 59);
//虚拟键盘位置
setVirkeyboardPos();
}
void GreeterWindow::setVirkeyboardPos()
{
if(m_virtualKeyboard)
{
m_virtualKeyboard->setGeometry(0,
height() - height()/3,
width(), height()/3);
}
}
bool GreeterWindow::eventFilter(QObject *obj, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress){
if(m_sessionWnd && m_sessionWnd->isVisible())
m_sessionWnd->hide();
if(m_languageWnd && m_languageWnd->isVisible())
m_languageWnd->hide();
}
return false;
}
void GreeterWindow::keyReleaseEvent(QKeyEvent *e)
{
switch(e->key())
{
case Qt::Key_L:
if(e->modifiers() & Qt::ControlModifier)
m_languageLB->click();
break;
case Qt::Key_K:
if(e->modifiers() & Qt::ControlModifier)
m_keyboardLB->click();
break;
case Qt::Key_P:
if(e->modifiers() & Qt::ControlModifier)
m_powerLB->click();
break;
case Qt::Key_Escape:
if(m_powerWnd && !m_powerWnd->isHidden()){
m_powerWnd->close();
}
break;
}
QWidget::keyReleaseEvent(e);
}
QString GreeterWindow::getAccountBackground(uid_t uid)
{
QDBusInterface iface("org.freedesktop.Accounts", "/org/freedesktop/Accounts",
"org.freedesktop.Accounts",QDBusConnection::systemBus());
QDBusReply userPath = iface.call("FindUserById", (qint64)uid);
if(!userPath.isValid())
qWarning() << "Get UserPath error:" << userPath.error();
else {
QDBusInterface userIface("org.freedesktop.Accounts", userPath.value().path(),
"org.freedesktop.DBus.Properties", QDBusConnection::systemBus());
QDBusReply backgroundReply = userIface.call("Get", "org.freedesktop.Accounts.User", "BackgroundFile");
if(backgroundReply.isValid())
return backgroundReply.value().variant().toString();
}
return "";
}
void GreeterWindow::setBackground(const QModelIndex &index)
{
QString backgroundPath = index.data(QLightDM::UsersModel::BackgroundPathRole).toString();
if(backgroundPath.isEmpty())
{
uid_t uid = index.data(QLightDM::UsersModel::UidRole).toUInt();
backgroundPath = getAccountBackground(uid);
if(backgroundPath.isEmpty())
backgroundPath = "/usr/share/backgrounds/warty-final-ubuntukylin.jpg";
}
QSharedPointer background(new Background);
background->type = BACKGROUND_IMAGE;
background->image = backgroundPath;
static_cast(parentWidget())->setBackground(background);
m_greeter->setrootWindowBackground(background->image);
}
void GreeterWindow::onUserSelected(const QModelIndex &index)
{
qDebug() << index.data(QLightDM::UsersModel::NameRole).toString() << "selected";
m_loginWnd->setUserIndex(index);
}
void GreeterWindow::updateLanguage(QString userName)
{
QString language;
QDBusInterface iface("org.freedesktop.Accounts", "/org/freedesktop/Accounts",
"org.freedesktop.Accounts",QDBusConnection::systemBus());
QDBusReply userPath = iface.call("FindUserByName", userName);
if(!userPath.isValid())
qWarning() << "Get UserPath error:" << userPath.error();
else {
QDBusInterface userIface("org.freedesktop.Accounts", userPath.value().path(),
"org.freedesktop.DBus.Properties", QDBusConnection::systemBus());
QDBusReply languageReply = userIface.call("Get", "org.freedesktop.Accounts.User", "Language");
if(!languageReply.isValid())
qWarning() << "Get User's language error" << languageReply.error();
else {
language = languageReply.value().variant().toString();
if(!language.isEmpty()){
onLanguageChanged(getLanguage(language));
}
}
}
}
void GreeterWindow::updateSession(QString userName)
{
QDBusInterface iface("org.freedesktop.Accounts", "/org/freedesktop/Accounts",
"org.freedesktop.Accounts",QDBusConnection::systemBus());
QDBusReply userPath = iface.call("FindUserByName", userName);
if(!userPath.isValid())
qWarning() << "Get UserPath error:" << userPath.error();
else {
QDBusInterface userIface("org.freedesktop.Accounts", userPath.value().path(),
"org.freedesktop.DBus.Properties", QDBusConnection::systemBus());
QDBusReply sessionReply = userIface.call("Get", "org.freedesktop.Accounts.User", "XSession");
if(!sessionReply.isValid())
qWarning() << "Get User's session error" << sessionReply.error();
else {
QString session = sessionReply.value().variant().toString();
onSessionChanged(session);
}
}
}
void GreeterWindow::onCurrentUserChanged(const QModelIndex &index)
{
setBackground(index);
if(!m_languageHasChanged)
{
//获取用户的session语言
QString language;
QString realName = index.data(QLightDM::UsersModel::NameRole).toString();
if(realName == "*guest" || realName == "*login")
return;
updateLanguage(realName);
}
if(!m_sessionHasChanged && m_sessionsModel->rowCount() > 1)
{
QString session = index.data(QLightDM::UsersModel::SessionRole).toString();
onSessionChanged(session);
}
}
void GreeterWindow::onUserChangedByManual(const QString &userName)
{
m_userWnd->setCurrentUser(userName, true);
updateLanguage(userName);
updateSession(userName);
}
void GreeterWindow::setWindowVisible(bool visible)
{
m_loginWnd->setVisible(!visible);
m_userWnd->setVisible(!visible);
}
/**
* @brief GreeterWindow::showPowerWnd
* 显示电源对话框
*/
void GreeterWindow::showPowerWnd()
{
m_userWnd->hide();
m_loginWnd->hide();
//如果已经打开了电源对话框则关闭
if(m_powerWnd && !m_powerWnd->isHidden()){
m_powerWnd->close();
return;
}
//判断是否已经有用户登录
bool hasOpenSessions = false;
for(int i = 0; i < m_usersModel->rowCount(); i++) {
hasOpenSessions = m_usersModel->index(i, 0).data(QLightDM::UsersModel::LoggedInRole).toBool();
if(hasOpenSessions)
break;
}
m_powerWnd = new PowerWindow(hasOpenSessions, this);
connect(m_powerWnd, &PowerWindow::windowVisibleChanged,
this, &GreeterWindow::setWindowVisible);
m_powerWnd->setObjectName(QStringLiteral("powerWnd"));
m_powerWnd->show();
}
/**
* @brief GreeterWindow::showVirtualKeyboard
* 显示或隐藏虚拟键盘
*/
void GreeterWindow::showVirtualKeyboard()
{
if(!m_virtualKeyboard)
{
m_virtualKeyboard = new VirtualKeyboard(this);
connect(m_virtualKeyboard, &VirtualKeyboard::aboutToClose,
m_virtualKeyboard, &VirtualKeyboard::close);
}
m_virtualKeyboard->setVisible(!m_virtualKeyboard->isVisible());
setVirkeyboardPos();
}
/**
* @brief GreeterWindow::timedAutologin
* 处理延时自动登录
*/
void GreeterWindow::timedAutologin()
{
if(m_greeter->isAuthenticated()) {
if(!m_greeter->authenticationUser().isEmpty())
m_greeter->startSession();
else if(m_greeter->autologinGuestHint())
m_greeter->startSession();
else if(!m_greeter->autologinUserHint().isEmpty())
m_greeter->authenticate(m_greeter->autologinUserHint());
}
else
m_greeter->authenticateAutologin();
}
/**
* @brief GreeterWindow::showLanguageWnd
* 显示语言选择窗口
*/
void GreeterWindow::showLanguageWnd()
{
if(!m_languageWnd){
m_languageWnd = new LanguageWidget(this);
m_languageWnd->setObjectName("languageWnd");
connect(m_languageWnd, &LanguageWidget::languageChanged,
this, &GreeterWindow::onLanguageChanged);
}
m_languageHasChanged = true;
if(m_languageWnd->isVisible()){
m_languageWnd->hide();
setFocus();
}
else{
m_languageWnd->show();
m_languageWnd->setFocus();
m_languageWnd->setCurrentLanguage(m_greeter->lang());
m_languageWnd->move(m_languageLB->x(),m_languageLB->y()-m_languageWnd->height() - 5);
}
}
void GreeterWindow::setWindowPos(QWidget *widget, Qt::Alignment align)
{
QRect rect;
rect.setSize(widget->size());
if(align & Qt::AlignHCenter)
{
rect.setLeft((width() - widget->width())/2);
}
if(align & Qt::AlignVCenter)
{
rect.setTop((height() - widget->height())/2);
}
if(align & Qt::AlignBottom)
{
rect.setTop(height() - widget->height());
}
widget->setGeometry(rect);
}
void GreeterWindow::onLanguageChanged(const Language &language)
{
if(language.code == "" || language.name == "")
return ;
if(m_greeter->lang() == language.code)
{
return;
}
m_greeter->setLang(language.code);
m_languageLB->setText(language.name);
const QFont &font = m_languageLB->font();
QFontMetrics fm(font);
int pixelWidth = fm.width(language.name);
m_languageLB->setFixedWidth(pixelWidth + 4);
int x,y;
if(m_sessionLB)
{
x = m_sessionLB->geometry().left();
y = m_sessionLB->y();
}
else
{
x = m_keyboardLB->geometry().left();
y = m_keyboardLB->y();
}
m_languageLB->move(x - 10 - m_languageLB->width() , y);
if(m_userWnd && !m_userWnd->isHidden())
{
m_userWnd->setFocus();
}
}
void GreeterWindow::showSessionWnd()
{
if(!m_sessionWnd){
m_sessionWnd = new SessionWindow(m_sessionsModel, this);
connect(m_sessionWnd, &SessionWindow::sessionChanged, \
this, &GreeterWindow::onSessionChanged);
}
m_sessionHasChanged = true;
if(m_sessionWnd->isVisible()){
m_sessionWnd->hide();
setFocus();
}
else{
m_sessionWnd->move(m_languageLB->x(),m_languageLB->y()-m_sessionWnd->height());
m_sessionWnd->show();
m_sessionWnd->setCurrentSession(m_greeter->session());
m_sessionWnd->setFocus();
}
}
void GreeterWindow::onSessionChanged(const QString &session)
{
qDebug() << "session changed: " << session;
QString sessionTmp(session);
if(session.isEmpty() || !sessionIsValid(session))
{ //session不存在
QString defaultSession = m_greeter->defaultSessionHint();
//默认session存在
if(defaultSession != session && sessionIsValid(defaultSession))
{
sessionTmp = defaultSession;
}
//列表中的第一个session
else if(m_sessionsModel && m_sessionsModel->rowCount() > 0)
{
sessionTmp = m_sessionsModel->index(0, 0)
.data(QLightDM::SessionsModel::KeyRole).toString();
}
else
{
sessionTmp = "";
}
}
QString sessionPrefix = sessionTmp.left(sessionTmp.indexOf('-'));
QString sessionIcon = IMAGE_DIR + QString("badges/%1_badge.png")
.arg(sessionPrefix.toLower());
QFile iconFile(sessionIcon);
if(!iconFile.exists()){
sessionIcon = IMAGE_DIR + QString("badges/unknown_badge.png");
}
qDebug() << sessionIcon;
if(m_sessionLB)
m_sessionLB->setIcon(QIcon(sessionIcon));
m_greeter->setSession(sessionTmp);
if(m_userWnd && !m_userWnd->isHidden())
{
m_userWnd->setFocus();
}
}
bool GreeterWindow::sessionIsValid(const QString &session)
{
for(int i = 0; i < m_sessionsModel->rowCount(); i++)
{
QString sessionKey = m_sessionsModel->index(i, 0)
.data(QLightDM::SessionsModel::KeyRole).toString();
if(sessionKey == session)
return true;
}
return false;
}
ukui-greeter/ukui-greeter/greeter/iconedit.cpp 0000644 0001750 0001750 00000013111 13640355124 020455 0 ustar feng feng /* iconedit.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "iconedit.h"
#include
#include
#include
#include
#include
#include
#include
#include "xeventmonitor.h"
IconEdit::IconEdit(QWidget *parent)
: QWidget(parent),
m_timer(nullptr)
{
m_edit = new QLineEdit(this);
m_edit->setObjectName(QStringLiteral("passwdEdit"));
m_edit->setAttribute(Qt::WA_InputMethodEnabled, false); //禁用输入法
m_edit->setContextMenuPolicy(Qt::NoContextMenu); //禁用右键菜单
m_edit->installEventFilter(this);
m_capsIcon = new QLabel(this);
m_capsIcon->setObjectName(QStringLiteral("capsIconLabel"));
m_iconButton = new QPushButton(this);
m_iconButton->setObjectName(QStringLiteral("loginButton"));
m_iconButton->setFocusPolicy(Qt::NoFocus);
m_iconButton->setCursor(QCursor(Qt::PointingHandCursor));
m_modeButton = new QPushButton(this);
m_modeButton->setObjectName(QStringLiteral("echoModeButton"));
m_modeButton->setCheckable(true);
m_modeButton->setFocusPolicy(Qt::NoFocus);
m_modeButton->setCursor(Qt::PointingHandCursor);
connect(m_modeButton, &QPushButton::clicked, this, [&](bool checked){
setType(checked ? QLineEdit::Normal : QLineEdit::Password);
});
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(1, 1, 1, 1);
layout->setSpacing(0);
layout->addStretch();
layout->addWidget(m_capsIcon);
layout->addWidget(m_modeButton);
layout->addWidget(m_iconButton);
connect(m_edit, &QLineEdit::returnPressed, this, &IconEdit::clicked_cb);
connect(m_iconButton, &QPushButton::clicked, this, &IconEdit::clicked_cb);
connect(XEventMonitor::instance(), SIGNAL(keyRelease(const QString &)),
this, SLOT(onGlobalKeyRelease(const QString &)));
setFocusProxy(m_edit);
setCapsState(checkCapsState());
}
bool IconEdit::eventFilter(QObject *obj, QEvent *event)
{
if(obj == m_edit){
if(event->type() == QEvent::KeyPress){
QKeyEvent *keyEvent = static_cast(event);
if(keyEvent->key()==80 &&keyEvent->modifiers() ==(Qt::MetaModifier)){
event->ignore();
return true;
}
}
}
return false;
}
void IconEdit::setType(QLineEdit::EchoMode type)
{
m_edit->setEchoMode(type);
if(type == 0)
m_modeButton->setChecked(true);
else
m_modeButton->setChecked(false);
}
void IconEdit::resizeEvent(QResizeEvent *)
{
// 设置输入框中文件输入区,不让输入的文字在被隐藏在按钮下
int w = m_iconButton->width() + m_modeButton->width();
m_edit->setTextMargins(1, 1, m_capsIcon->isVisible() ? w + m_capsIcon->width() : w, 1);
m_edit->setFixedSize(size());
}
void IconEdit::clicked_cb()
{
// m_iconButton->setFocus(); //按回车后输入框光标会消失或者不再闪烁,先让其他控件获取焦点,就会解决该问题
startWaiting();
emit clicked(m_edit->text());
}
void IconEdit::onGlobalKeyRelease(const QString &key)
{
if(key == "Caps_Lock")
{
setCapsState(!m_capsIcon->isVisible());
}
}
void IconEdit::setCapsState(bool capsState)
{
m_capsIcon->setVisible(capsState);
int w = m_iconButton->width() + m_modeButton->width();
m_edit->setTextMargins(1, 1, capsState ? w + m_capsIcon->width() : w, 1);
}
void IconEdit::setIcon(const QString &text)
{
m_iconButton->setIcon(QIcon());
m_iconButton->setText(text);
m_iconText = text;
m_icon = QIcon();
}
void IconEdit::setIcon(const QIcon &icon)
{
m_iconButton->setIcon(icon);
m_iconButton->setText("");
m_icon = icon;
m_iconText = "";
}
void IconEdit::clear()
{
m_edit->setText("");
setPrompt("");
}
void IconEdit::setPrompt(const QString &prompt)
{
m_edit->setPlaceholderText(prompt);
}
const QString IconEdit::text()
{
return m_edit->text();
}
void IconEdit::startWaiting()
{
m_edit->setReadOnly(true);
m_iconButton->setEnabled(false);
if(!m_timer)
{
m_timer = new QTimer(this);
m_timer->setInterval(120);
connect(m_timer, &QTimer::timeout, this, &IconEdit::updatePixmap);
}
m_waitingPixmap.load(":/resource/waiting.png");
m_iconButton->setIconSize(m_iconButton->size());
m_iconButton->setIcon(QIcon(m_waitingPixmap));
m_timer->start();
}
void IconEdit::stopWaiting()
{
if(m_timer && m_timer->isActive())
{
m_timer->stop();
}
m_edit->setReadOnly(false);
m_iconButton->setEnabled(true);
if(!m_icon.isNull())
m_iconButton->setIcon(m_icon);
else
m_iconButton->setText(m_iconText);
}
void IconEdit::updatePixmap()
{
QMatrix matrix;
matrix.rotate(90.0);
m_waitingPixmap = m_waitingPixmap.transformed(matrix, Qt::FastTransformation);
m_iconButton->setIcon(QIcon(m_waitingPixmap));
}
ukui-greeter/ukui-greeter/greeter/languagewidget.h 0000644 0001750 0001750 00000003026 13627147146 021327 0 ustar feng feng /**
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef LANGUAGEWIDGET_H
#define LANGUAGEWIDGET_H
#include
#include
#include "language.h"
#include "fakedialog.h"
class QListWidget;
class QListWidgetItem;
class QLabel;
class LanguageWidget : public QMenu
{
Q_OBJECT
public:
explicit LanguageWidget(QWidget *parent = nullptr);
void setCurrentLanguage(const QString &language);
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
void initUserMenu();
private Q_SLOTS:
void onLanguageAdded(QString lang);
void onLanguageDeleted(QString lang);
void onLanguageMenuTrigged(QAction *action);
Q_SIGNALS:
void languageChanged(const Language &language);
private:
LanguagesVector &languagesVector;
QMenu *menu;
};
#endif // LANGUAGEWIDGET_H
ukui-greeter/ukui-greeter/greeter/screenmodel.cpp 0000644 0001750 0001750 00000004420 13621375753 021173 0 ustar feng feng /* screenmodel.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "screenmodel.h"
#include
#include
#include
ScreenModel::ScreenModel(QObject *parent)
: QAbstractListModel(parent),
_desktop(QApplication::desktop())
{
loadScreens();
connect(_desktop, &QDesktopWidget::workAreaResized, this, &ScreenModel::onScreenResized);
connect(_desktop, &QDesktopWidget::resized, this, &ScreenModel::onScreenResized);
connect(_desktop, &QDesktopWidget::screenCountChanged, this, &ScreenModel::onScreenCountChanged);
}
int ScreenModel::rowCount(const QModelIndex &parent) const
{
if(parent == QModelIndex()){
return m_screen.size();
}
return 0;
}
QVariant ScreenModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid()){
return QVariant();
}
int row = index.row();
if(row < m_screen.size() && role == Qt::UserRole){
return m_screen[row];
} else {
return QVariant();
}
}
void ScreenModel::onScreenResized(int screen)
{
if(screen >= 0 && screen < m_screen.size()){
m_screen[screen] = _desktop->screenGeometry(screen);
}
QModelIndex index = createIndex(screen, 0);
emit dataChanged(index, index);
}
void ScreenModel::onScreenCountChanged(int newCount)
{
Q_UNUSED(newCount)
loadScreens();
}
void ScreenModel::loadScreens()
{
beginResetModel();
m_screen.clear();
for(int i = 0; i < _desktop->screenCount(); i++){
m_screen.append(_desktop->screenGeometry(i));
}
endResetModel();
}
ukui-greeter/ukui-greeter/greeter/loginwindow.cpp 0000644 0001750 0001750 00000066550 13640355124 021236 0 ustar feng feng /* loginwindow.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "loginwindow.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include "greeterwrapper.h"
#include "iconedit.h"
#include "globalv.h"
#include "configuration.h"
#include "biometricproxy.h"
#include "biometricauthwidget.h"
#include "biometricdeviceswidget.h"
LoginWindow::LoginWindow(GreeterWrapper *greeter, QWidget *parent)
: QWidget(parent),
m_greeter(greeter),
isManual(false),
authMode(UNKNOWN),
m_deviceCount(-1),
m_featureCount(-1),
m_biometricProxy(nullptr),
m_biometricAuthWidget(nullptr),
m_biometricDevicesWidget(nullptr),
m_buttonsWidget(nullptr)
{
initUI();
connect(m_greeter, SIGNAL(showMessage(QString,QLightDM::Greeter::MessageType)),
this, SLOT(onShowMessage(QString,QLightDM::Greeter::MessageType)));
connect(m_greeter, SIGNAL(showPrompt(QString,QLightDM::Greeter::PromptType)),
this, SLOT(onShowPrompt(QString,QLightDM::Greeter::PromptType)));
connect(m_greeter, SIGNAL(authenticationComplete()),
this, SLOT(onAuthenticationComplete()));
}
QPixmap LoginWindow::PixmapToRound(const QPixmap &src, int radius)
{
if (src.isNull()) {
return QPixmap();
}
QPixmap pixmapa(src);
QPixmap pixmap(radius*2,radius*2);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
QPainterPath path;
path.addEllipse(0, 0, radius*2, radius*2);
painter.setClipPath(path);
painter.drawPixmap(0, 0, radius*2, radius*2, pixmapa);
return pixmap;
}
void LoginWindow::initUI()
{
setFixedWidth(500);
// m_userWidget = new QWidget(this);
// m_userWidget->setObjectName(QStringLiteral("userWidget"));
/* 头像 */
// m_faceLabel = new QLabel(m_userWidget);
// m_faceLabel->setObjectName(QStringLiteral("faceLabel"));
// m_faceLabel->setFocusPolicy(Qt::NoFocus);
/* 返回按钮 */
// m_backButton = new QPushButton(m_userWidget);
// m_backButton->setObjectName(QStringLiteral("backButton"));
// m_backButton->setFocusPolicy(Qt::NoFocus);
// m_backButton->show();
// connect(m_backButton, &QPushButton::clicked,
// this, &LoginWindow::onBackButtonClicked);
// /* 用户名 */
// m_nameLabel = new QLabel(m_userWidget);
// m_nameLabel->setObjectName(QStringLiteral("login_nameLabel"));
// m_nameLabel->setFocusPolicy(Qt::NoFocus);
// m_nameLabel->setAlignment(Qt::AlignCenter);
// /* 是否已登录 */
// m_isLoginLabel = new QLabel(m_userWidget);
// m_isLoginLabel->setObjectName(QStringLiteral("isLoginLabel"));
// m_isLoginLabel->setFocusPolicy(Qt::NoFocus);
// m_isLoginLabel->setAlignment(Qt::AlignCenter);
/* 密码框所在窗口 */
m_passwdWidget = new QWidget(this);
m_passwdWidget->setObjectName(QStringLiteral("passwordWidget"));
/* 密码框 */
m_passwordEdit = new IconEdit(m_passwdWidget);
m_passwordEdit->setObjectName(QStringLiteral("passwordEdit"));
m_passwordEdit->setIcon(QIcon(":/resource/login-button.png"));
m_passwordEdit->setFocusPolicy(Qt::StrongFocus);
m_passwordEdit->installEventFilter(this);
m_passwordEdit->hide(); //收到请求密码的prompt才显示出来
connect(m_passwordEdit, SIGNAL(clicked(const QString&)),
this, SLOT(onLogin(const QString&)));
/* 密码认证信息显示列表 */
m_messageLabel = new QLabel(m_passwdWidget);
m_messageLabel->setObjectName(QStringLiteral("messageLabel"));
m_messageLabel->setAlignment(Qt::AlignCenter);
m_messageButton = new QPushButton(m_passwdWidget);
m_messageButton->setObjectName(QStringLiteral("messageButton"));
m_messageButton->hide();
setFocusProxy(m_passwordEdit);
isloginauth = false;
}
void LoginWindow::showEvent(QShowEvent *e)
{
QWidget::showEvent(e);
if(!m_passwordEdit->isHidden())
{
m_passwordEdit->setFocus();
}
}
void LoginWindow::resizeEvent(QResizeEvent *)
{
setChildrenGeometry();
}
#include
void LoginWindow::keyReleaseEvent(QKeyEvent *event)
{
// qDebug() << event->key();
if(event->key() == Qt::Key_Escape)
{
//退出设备选择
if(m_biometricDevicesWidget && m_biometricDevicesWidget->isVisible())
{
if(authMode == BIOMETRIC)
{
showBiometricAuthWidget();
}
else
{
showPasswordAuthWidget();
}
return;
}
//返回用户列表
else if(m_biometricAuthWidget && m_biometricAuthWidget->isVisible())
{
m_biometricAuthWidget->stopAuth();
Q_EMIT back();
return;
}
}
QWidget::keyReleaseEvent(event);
}
void LoginWindow::setChildrenGeometry()
{
// 用户信息显示位置
// m_userWidget->setGeometry(0, (height() - 240 - 150) / 2,
// width(), 240);
// m_faceLabel->setGeometry((width() - 130) / 2, 0, 130, 130);
// m_backButton->setGeometry(m_faceLabel->geometry().left() - 30 - 32,
// m_faceLabel->geometry().top() + (m_faceLabel->height() - 32) / 2,
// 32, 32);
// m_nameLabel->setGeometry(0, m_faceLabel->geometry().bottom() + 25,
// width(), 30);
// m_isLoginLabel->setGeometry(0, m_nameLabel->geometry().bottom() + 10,
// width(), 15);
// 密码框和提示信息显示位置
m_passwdWidget->setGeometry(0, 0, width(), 150);
m_passwordEdit->setGeometry((m_passwdWidget->width() - 300)/2, 0, 300, 34);
m_messageLabel->setGeometry((m_passwdWidget->width() - 600)/2,
m_passwordEdit->geometry().bottom() + 25,
600, 20);
m_messageButton->setGeometry((m_passwdWidget->width() - 200)/2, 0, 200, 40);
setBiometricWidgetGeometry();
setBiometricButtonWidgetGeometry();
}
/**
* @brief LoginWindow::reset
* 复原UI
*/
void LoginWindow::reset()
{
// m_nameLabel->clear();
// m_isLoginLabel->clear();
m_passwordEdit->clear();
m_passwordEdit->setType(QLineEdit::Password);
m_messageButton->hide();
clearMessage();
showPasswordAuthWidget();
m_deviceCount = -1;
authMode = UNKNOWN;
m_deviceInfo = DeviceInfoPtr();
m_deviceName = "";
}
void LoginWindow::clearMessage()
{
m_messageLabel->clear();
}
/**
* @brief LoginWindow::backToUsers
* 返回到用户列表窗口
*/
void LoginWindow::onBackButtonClicked()
{
reset();
Q_EMIT back();
}
/**
* @brief LoginWindow::setUserName
* @param userName 用户名
*
* 设置用户名
*/
void LoginWindow::setUserName(const QString& userName)
{
m_nameLabel->setText(userName);
}
/**
* @brief LoginWindow::userName
* @return 当前的用户名
*
* 获取当前用户名
*/
QString LoginWindow::getUserName()
{
if(m_nameLabel->text() == tr("Login"))
return "Login";
return m_nameLabel->text();
}
/**
* @brief LoginWindow::getRealName
* @return
* 获取用户真名
*/
QString LoginWindow::getRealName()
{
return m_name;
}
/**
* @brief LoginWindow::setFace
* @param faceFile 用户头像文件
*
* 设置用户头像
*/
void LoginWindow::setFace(const QString& facePath)
{
QFile faceFile(facePath);
QPixmap faceImage;
m_faceLabel->setFixedSize(128,128);
//如果头像文件不存在,则使用默认头像
if(faceFile.exists())
faceImage = scaledPixmap(128, 128, facePath);
else
faceImage = scaledPixmap(128, 128, ":/resource/default_face.png");
faceImage = PixmapToRound(faceImage,62);
m_faceLabel->setAlignment(Qt::AlignCenter);
m_faceLabel->setPixmap(faceImage);
}
/**
* @brief LoginWindow::setLoggedIn
* @param isLoggedIn
*
* 设置当前用户是否已已经登录
*/
void LoginWindow::setLoggedIn(bool isLoggedIn)
{
m_isLoginLabel->setText(isLoggedIn ? tr("logged in") : "");
}
/**
* @brief LoginWindow::setPrompt
* @param text
*
* 设置密码框的提示信息
*/
void LoginWindow::setPrompt(const QString& text)
{
m_passwordEdit->setPrompt(text);
}
/**
* @brief LoginWindow::password
* @return
*
* 获取密码
*/
QString LoginWindow::getPassword()
{
return m_passwordEdit->text();
}
bool LoginWindow::setUserIndex(const QModelIndex& index)
{
if(!index.isValid()){
return false;
}
//先清空设置
reset();
//设置用户名
QString name = index.data(QLightDM::UsersModel::RealNameRole).toString();
m_name = index.data(QLightDM::UsersModel::NameRole).toString();
// setUserName(name.isEmpty() ? m_name : name);
//设置头像
// QString facePath = index.data(QLightDM::UsersModel::ImagePathRole).toString();
// setFace(facePath);
//显示是否已经登录
// bool isLoggedIn = index.data(QLightDM::UsersModel::LoggedInRole).toBool();
// setLoggedIn(isLoggedIn);
//设置生物识别设备窗口的uid
m_uid = index.data(QLightDM::UsersModel::UidRole).toInt();
setChildrenGeometry();
if(!isloginauth)
startAuthentication();
isloginauth = false;
return true;
}
/**
* @brief 手动输入的用户名不在用户列表中(uid < 1000或者用户不存在)
* @param userName
*/
void LoginWindow::setUserNotInView(const QString &userName)
{
isloginauth = false;
m_name = userName;
setUserName(userName);
}
void LoginWindow::startAuthentication()
{
prompted = false;
unacknowledged_messages = false;
//用户认证
if(m_name == "*guest")
{ //游客登录
qDebug() << "guest login";
m_passwordEdit->show();
setPrompt(tr("login"));
}
else if(m_name == "*login")
{ //手动输入用户名
m_greeter->authenticate("");
}
else
{
qDebug() << "login: " << m_name;
m_greeter->authenticate(m_name);
}
}
/**
* @brief LoginWindow::startWaiting
*
* 等待认证结果
*/
void LoginWindow::startWaiting()
{
m_passwordEdit->startWaiting(); //等待认证结果期间不能再输入密码
}
void LoginWindow::stopWaiting()
{
m_passwordEdit->stopWaiting();
}
void LoginWindow::onLogin(const QString &str)
{
clearMessage();
qDebug()<authenticateAsGuest();
}
else if(m_name == "*login")
{ //用户输入用户名
isloginauth = true;
isManual = true;
m_name_is_login = true;
Q_EMIT userChangedByManual(str);
m_greeter->respond(str);
}
else
{ //发送密码
m_greeter->respond(str);
startWaiting();
}
}
void LoginWindow::onShowPrompt(QString text, QLightDM::Greeter::PromptType type)
{
qDebug()<< "prompt: "<< text;
if(text == BIOMETRIC_PAM)
{
if(authMode == PASSWORD)
{
skipBiometricAuth();
}
else
{
performBiometricAuth();
}
}
else
{
m_name_is_login = false;
qDebug()<<"m_name_is_login = false";
stopWaiting();
if(!text.isEmpty())
m_passwordEdit->show();
m_passwordEdit->setFocus();
if(type != QLightDM::Greeter::PromptTypeSecret){
isauto_switch = true;
m_passwordEdit->setType(QLineEdit::Normal);
}
else if(isauto_switch)
{
m_passwordEdit->setType(QLineEdit::Password);
isauto_switch = false;
}
prompted = true;
unacknowledged_messages = false;
qDebug()<<"unacknowledged_messages = false";
if(text == "Password: ")
text = tr("Password: ");
if(text == "login:") {
text = tr("Username");
m_name = "*login";
//m_nameLabel->setText(tr("login"));
m_name_is_login = true;
qDebug()<<"m_name_is_login = true";
}
m_passwordEdit->clear();
setPrompt(text);
}
}
void LoginWindow::onShowMessage(QString text, QLightDM::Greeter::MessageType type)
{
qDebug()<< "message: "<< text;
// if(type == QLightDM::Greeter::MessageTypeError)
// {
// m_messageLabel->setStyleSheet("#messageLabel{color: rgb(255, 0, 0, 180);}");
// }
// else
// {
// m_messageLabel->setStyleSheet("#messageLabel{color: black;}");
// }
unacknowledged_messages = true;
qDebug()<<"unacknowledged_messages = true";
m_messageLabel->setText(text);
stopWaiting();
}
void LoginWindow::onAuthenticationComplete()
{
stopWaiting();
if(m_greeter->isAuthenticated()) {
// 认证成功,启动session
qDebug()<< "authentication success";
if(prompted && !unacknowledged_messages ||direct_login){
direct_login = false;
Configuration::instance()->saveLastLoginUser(m_name);
m_greeter->startSession();
}
else
{
qDebug()<<"prompted = "<clear();
//如果用户输入了不存在的用户名导致的认证失败,让用户重新输入用户名
if(isManual){
if(m_name_is_login){
onShowMessage(tr("Incorrect user name, please input again"), QLightDM::Greeter::MessageTypeError);
m_name_is_login = false;
m_name = "*login";
}
else{
onShowMessage(tr("Incorrect password, please input again"), QLightDM::Greeter::MessageTypeError);
}
// m_name = "*login";
}
else{
onShowMessage(tr("Incorrect password, please input again"), QLightDM::Greeter::MessageTypeError);
authMode = PASSWORD;
}
isManual = false;
startAuthentication();
}
else
{
show_authenticated (false);
}
}
}
void LoginWindow::show_authenticated(bool successful)
{
m_passwordEdit->hide();
m_messageButton->show();
m_messageButton->setFocus();
m_messageButton->setDefault(true);
connect(m_messageButton, &QPushButton::clicked,
this, &LoginWindow::onMessageButtonClicked);
if(successful)
{
isretry = false;
// m_greeter->startSession();
m_messageButton->setText(tr("Login"));
}
else
{
isretry = true;
m_messageButton->setText(tr("Retry"));
}
}
void LoginWindow::onMessageButtonClicked()
{
m_messageButton->setDefault(false);
if(!isretry)
{
m_messageButton->hide();
Configuration::instance()->saveLastLoginUser(m_name);
m_greeter->startSession();
}
else
{
m_messageButton->hide();
// m_passwordEdit->show();
// m_passwordEdit->clear();
authMode = PASSWORD;
m_messageLabel->setText("");
startAuthentication();
}
}
void LoginWindow::setDirLogin()
{
direct_login = true;
}
void LoginWindow::performBiometricAuth()
{
if(!m_biometricProxy)
{
m_biometricProxy = new BiometricProxy(this);
}
//服务没启动,或者打开DBus连接出错
if(!m_biometricProxy->isValid())
{
qWarning() << "An error occurs when connect to the biometric DBus";
skipBiometricAuth();
return;
}
//初始化设备数量
if(m_deviceCount < 0)
{
m_deviceCount = m_biometricProxy->GetDevCount();
}
//没有可用设备,不启用生物识别认证
if(m_deviceCount < 1)
{
qWarning() << "No available devices";
skipBiometricAuth();
return;
}
//初始化用户对应特征数量
m_featureCount = m_biometricProxy->GetFeatureCount(m_uid);
qDebug()<<"m_featureCount = "<shortName : "");
//如果默认设备为空的话,第一次不启动生物识别认证
if(m_deviceName.isEmpty() && !m_deviceInfo)
{
qDebug() << "No default device";
skipBiometricAuth();
return;
}
//第一次,获取默认设备的设备信息,之后使用的则是从设备选择窗口传出的设备信息
if(!m_deviceInfo)
{
m_deviceInfo = m_biometricDevicesWidget->findDeviceByName(m_deviceName);
}
if(!m_deviceInfo)
{
qDebug() << "Device Not found: " << m_deviceName;
skipBiometricAuth();
return;
}
authMode = BIOMETRIC;
m_biometricAuthWidget->startAuth(m_deviceInfo, m_uid);
// m_biometricAuthWidget->show();
// m_passwdWidget->hide();
// m_biometricButton->hide();
// m_passwordButton->setVisible(true);
// m_otherDeviceButton->setVisible(m_deviceCount > 1);
// m_retryButton->setVisible(false);
showBiometricAuthWidget();
}
void LoginWindow::skipBiometricAuth()
{
m_greeter->respond(BIOMETRIC_IGNORE);
showPasswordAuthWidget();
// if(m_biometricAuthWidget)
// {
// m_biometricAuthWidget->hide();
// }
// if(m_buttonsWidget)
// {
// m_biometricButton->setVisible(true);
// m_passwordButton->setVisible(false);
// m_otherDeviceButton->setVisible(false);
// m_retryButton->setVisible(false);
// }
m_passwdWidget->show();
}
void LoginWindow::initBiometricWidget()
{
if(m_biometricAuthWidget)
{
return;
}
m_biometricAuthWidget = new BiometricAuthWidget(m_biometricProxy, this);
connect(m_biometricAuthWidget, &BiometricAuthWidget::authComplete,
this, &LoginWindow::onBiometricAuthComplete);
m_biometricDevicesWidget = new BiometricDevicesWidget(m_biometricProxy, this);
connect(m_biometricDevicesWidget, &BiometricDevicesWidget::deviceChanged,
this, &LoginWindow::onDeviceChanged);
setBiometricWidgetGeometry();
}
void LoginWindow::initBiometricButtonWidget()
{
if(m_buttonsWidget)
{
m_buttonsWidget->setVisible(true);
return;
}
m_buttonsWidget = new QWidget(this);
m_buttonsWidget->setObjectName(QStringLiteral("buttonsWidget"));
m_buttonsWidget->setFixedHeight(38);
QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
m_biometricButton = new QPushButton(m_buttonsWidget);
m_biometricButton->setObjectName(QStringLiteral("biometricButton"));
m_biometricButton->setIcon(QIcon(":/resource/bio-login.png"));
m_biometricButton->setText(tr("Biometric Authentication"));
m_biometricButton->setSizePolicy(sizePolicy);
m_biometricButton->setVisible(false);
m_biometricButton->setCursor(Qt::PointingHandCursor);
QFontMetrics fm(m_biometricButton->font(), m_biometricButton);
int width = fm.width(m_biometricButton->text());
m_biometricButton->setMaximumWidth(std::max(width + 20, 190));
connect(m_biometricButton, &QPushButton::clicked,
this, &LoginWindow::onBiometricButtonClicked);
m_passwordButton = new QPushButton(m_buttonsWidget);
m_passwordButton->setObjectName(QStringLiteral("passwordButton"));
m_passwordButton->setIcon(QIcon(":/resource/password-login.png"));
m_passwordButton->setText(tr("Password Authentication"));
fm = QFontMetrics(m_passwordButton->font(), m_passwordButton);
width = fm.width(m_passwordButton->text());
m_passwordButton->setMaximumWidth(std::max(width + 20, 140));
m_passwordButton->setSizePolicy(sizePolicy);
m_passwordButton->setVisible(false);
m_passwordButton->setCursor(Qt::PointingHandCursor);
connect(m_passwordButton, &QPushButton::clicked,
this, &LoginWindow::onPasswordButtonClicked);
m_otherDeviceButton = new QPushButton(m_buttonsWidget);
m_otherDeviceButton->setObjectName(QStringLiteral("otherDeviceButton"));
m_otherDeviceButton->setText(tr("Other Devices"));
m_otherDeviceButton->setSizePolicy(sizePolicy);
m_otherDeviceButton->setMaximumWidth(std::max(width + 20, 140));
m_otherDeviceButton->setVisible(false);
m_otherDeviceButton->setCursor(Qt::PointingHandCursor);
connect(m_otherDeviceButton, &QPushButton::clicked,
this, &LoginWindow::onOtherDevicesButtonClicked);
m_retryButton = new QPushButton(m_buttonsWidget);
m_retryButton->setObjectName(QStringLiteral("retryButton"));
m_retryButton->setText(tr("Retry"));
m_retryButton->setSizePolicy(sizePolicy);
m_retryButton->setMaximumWidth(110);
m_retryButton->setVisible(false);
m_retryButton->setCursor(Qt::PointingHandCursor);
connect(m_retryButton, &QPushButton::clicked,
this, &LoginWindow::onRetryButtonClicked);
QGridLayout *layout = new QGridLayout();
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(m_biometricButton, 0, 0);
layout->addWidget(m_passwordButton, 0, 1);
layout->addWidget(m_otherDeviceButton, 0, 2);
layout->addWidget(m_retryButton, 0, 3);
m_buttonsWidget->setLayout(layout);
m_buttonsWidget->show();
setBiometricButtonWidgetGeometry();
}
void LoginWindow::setBiometricWidgetGeometry()
{
//生物识别
if(m_biometricAuthWidget)
{
m_biometricAuthWidget->setGeometry(0, 0,
width(), m_biometricAuthWidget->height());
}
if(m_biometricDevicesWidget)
{
m_biometricDevicesWidget->setGeometry((width() - m_biometricDevicesWidget->width()) / 2,
(height() - m_biometricDevicesWidget->height()) / 2,
m_biometricDevicesWidget->width(),
m_biometricDevicesWidget->height());
}
}
void LoginWindow::setBiometricButtonWidgetGeometry()
{
if(m_buttonsWidget)
{
m_buttonsWidget->setGeometry(0, height() - 100,
width(), m_buttonsWidget->height());
}
}
void LoginWindow::onDeviceChanged(const DeviceInfoPtr &deviceInfo)
{
qDebug() << "device changed: " << *deviceInfo;
m_deviceInfo = deviceInfo;
if(authMode != BIOMETRIC){
authMode = BIOMETRIC;
startAuthentication();
}
else
m_biometricAuthWidget->startAuth(m_deviceInfo, m_uid);
// m_backButton->show();
// m_userWidget->show();
// m_passwdWidget->hide();
// m_biometricAuthWidget->show();
// m_buttonsWidget->show();
// m_biometricDevicesWidget->hide();
// m_biometricButton->hide();
// m_passwordButton->show();
// m_otherDeviceButton->show();
// m_retryButton->hide();
showBiometricAuthWidget();
}
void LoginWindow::onBiometricAuthComplete(bool result)
{
if(!result)
{
m_retryButton->setVisible(!m_biometricAuthWidget->isHidden());
}
else
{
setDirLogin();
m_greeter->respond(BIOMETRIC_SUCCESS);
}
}
void LoginWindow::onBiometricButtonClicked()
{
//当前没有设备,让用户选择设备
if(!m_deviceInfo)
{
if(m_deviceCount == 1)
{
DeviceList deviceList = m_biometricProxy->GetDevList();
m_deviceInfo = deviceList.at(0);
if(!m_deviceInfo)
{
m_otherDeviceButton->click();
}
else
{
authMode = BIOMETRIC;
startAuthentication();
}
}
else
{
m_otherDeviceButton->click();
}
}
else
{
authMode = BIOMETRIC;
startAuthentication();
}
}
void LoginWindow::onPasswordButtonClicked()
{
skipBiometricAuth();
// m_biometricAuthWidget->stopAuth();
}
void LoginWindow::onOtherDevicesButtonClicked()
{
m_biometricAuthWidget->stopAuth();
// m_backButton->hide();
// m_userWidget->hide();
// m_passwdWidget->hide();
// m_biometricAuthWidget->hide();
// m_buttonsWidget->hide();
// m_biometricDevicesWidget->show();
showBiometricDeviceWidget();
}
void LoginWindow::onRetryButtonClicked()
{
m_biometricAuthWidget->startAuth(m_deviceInfo, m_uid);
m_retryButton->setVisible(false);
}
void LoginWindow::showPasswordAuthWidget()
{
//m_userWidget->setVisible(true);
m_passwdWidget->setVisible(true);
if(m_biometricAuthWidget)
{
m_biometricAuthWidget->setVisible(false);
m_biometricDevicesWidget->setVisible(false);
m_biometricAuthWidget->stopAuth();
}
if(m_buttonsWidget)
{
if(m_deviceCount > 0 && m_featureCount > 0)
{
m_buttonsWidget->setVisible(true);
m_biometricButton->setVisible(true);
m_passwordButton->setVisible(false);
m_otherDeviceButton->setVisible(false);
m_retryButton->setVisible(false);
}
else
{
qDebug() << "hide buttons widget";
m_buttonsWidget->setVisible(false);
}
}
}
void LoginWindow::showBiometricAuthWidget()
{
emit bioDeviceIsChoosed(true);
m_passwdWidget->setVisible(false);
m_messageButton->hide();
if(m_biometricAuthWidget)
{
m_biometricAuthWidget->setVisible(true);
m_biometricDevicesWidget->setVisible(false);
}
if(m_buttonsWidget && m_deviceCount > 0)
{
m_buttonsWidget->setVisible(true);
m_biometricButton->setVisible(false);
m_passwordButton->setVisible(true);
m_otherDeviceButton->setVisible(m_deviceCount > 1);
m_retryButton->setVisible(!m_biometricAuthWidget->isAuthenticating());
}
else
{
m_buttonsWidget->setVisible(false);
}
}
void LoginWindow::showBiometricDeviceWidget()
{
emit bioDeviceIsChoosed(false);
m_passwdWidget->setVisible(false);
m_messageButton->hide();
if(m_biometricAuthWidget)
{
m_biometricAuthWidget->setVisible(false);
m_biometricDevicesWidget->setVisible(true);
}
if(m_buttonsWidget)
{
m_buttonsWidget->setVisible(false);
m_biometricButton->setVisible(false);
m_passwordButton->setVisible(false);
m_otherDeviceButton->setVisible(false);
m_retryButton->setVisible(false);
}
}
ukui-greeter/ukui-greeter/greeter/userentry.h 0000644 0001750 0001750 00000004525 13635402757 020406 0 ustar feng feng /* userentry.h
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#ifndef USERENTRY_H
#define USERENTRY_H
#include
#include
#include
#define FACE_WIDTH (150 * scale)
#define BORDER_WIDTH FACE_WIDTH
#define IMG_WIDTH (150 * scale)
#define ENTRY_HEIGHT (FACE_WIDTH + 70)
#define ENTRY_WIDTH (150 * scale)
#define CENTER_IMG_WIDTH (180 * scale)
#define CENTER_FACE_WIDTH (180 * scale)
#define CENTER_ENTRY_WIDTH (180 * scale )
#define CENTER_ENTRY_HEIGHT (CENTER_FACE_WIDTH + 70)
extern float scale;
class UserEntry : public QWidget
{
Q_OBJECT
public:
UserEntry(const QString &name, const QString &facePath, bool isLogin, QWidget *parent);
UserEntry(QWidget *parent=0);
void setUserIndex(const QPersistentModelIndex &index);
QPersistentModelIndex userIndex();
void setFace(const QString &facePath);
const QString& userName();
void setUserName(const QString &name);
void setLogin(bool isLogin);
void setSelected(bool selected=true);
bool selected();
void setResize();
QPixmap PixmapToRound(const QPixmap &src, int radius);
protected:
bool eventFilter(QObject *obj, QEvent *event);
void resizeEvent(QResizeEvent *);
void paintEvent(QPaintEvent *event);
private:
void onClicked();
void initUI();
signals:
void clicked(int row);
void pressed();
private:
QLabel *m_faceLabel;
QLabel *m_nameLabel;
QLabel *m_loginLabel;
QPixmap userface;
QPersistentModelIndex index;
QString m_face;
QString m_name;
bool m_login;
int id;
static int count;
static int selectedId;
};
#endif // USERENTRY_H
ukui-greeter/ukui-greeter/greeter/main.cpp 0000644 0001750 0001750 00000011713 13643021142 017602 0 ustar feng feng /* main.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "greeterwindow.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "globalv.h"
#include "mainwindow.h"
#include "display-switch/displayswitch.h"
#include "xeventmonitor.h"
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
Q_UNUSED(context)
QDateTime dateTime = QDateTime::currentDateTime();
QByteArray time = QString("[%1] ").arg(dateTime.toString("MM-dd hh:mm:ss.zzz")).toLocal8Bit();
QByteArray localMsg = msg.toLocal8Bit();
switch(type) {
case QtDebugMsg:
fprintf(stderr, "%s Debug: %s:%u: %s\n", time.constData(), context.file, context.line, localMsg.constData());
break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
case QtInfoMsg:
fprintf(stderr, "%s Info: %s:%u: %s\n", time.constData(), context.file, context.line, localMsg.constData());
break;
#endif
case QtWarningMsg:
fprintf(stderr, "%s Warnning: %s:%u: %s\n", time.constData(), context.file, context.line, localMsg.constData());
break;
case QtCriticalMsg:
fprintf(stderr, "%s Critical: %s:%u: %s\n", time.constData(), context.file, context.line, localMsg.constData());
break;
case QtFatalMsg:
fprintf(stderr, "%s Fatal: %s:%u: %s\n", time.constData(), context.file, context.line, localMsg.constData());
abort();
}
}
void waitMonitorsReady()
{
int n;
QScreen *screen = QApplication::primaryScreen();
while(n <= 0 && screen->geometry().x() <= 0 && screen->geometry().y() <= 0
&& screen->geometry().width() <= 0 && screen->geometry().height() <= 0){
XRRGetMonitors(QX11Info::display(), QX11Info::appRootWindow(), false, &n);
if(n == -1)
qWarning() << "get monitors failed";
else if(n > 0){
qDebug() << "found " << n << " monitors";
}
//启动xrandr,打开视频输出, 自动设置最佳分辨率
QProcess enableMonitors;
enableMonitors.start("xrandr --auto");
enableMonitors.waitForFinished(-1);
}
}
int main(int argc, char *argv[])
{
qInstallMessageHandler(outputMessage);
#if(QT_VERSION>=QT_VERSION_CHECK(5,6,0))
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(true);
QResource::registerResource("image.qrc");
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(codec);
QLocale::Language language;
language = QLocale::system().language();
qDebug() << "current locale language: " << QLocale::languageToString(language);
//加载翻译文件
QTranslator translator;
QString qmFile = QM_DIR + QString("%1.qm").arg(QLocale::system().name());
translator.load(qmFile);
qDebug() << "load translation file " << qmFile;
a.installTranslator(&translator);
//加载qss文件
QFile qss(":/ukui-greeter.qss");
qss.open(QFile::ReadOnly);
a.setStyleSheet(qss.readAll());
qss.close();
//用于QSettings
QApplication::setOrganizationName("Kylin");
QApplication::setApplicationName("ukui-greeter");
//设置鼠标指针样式
XDefineCursor(QX11Info::display(), QX11Info::appRootWindow(), XCreateFontCursor(QX11Info::display(), XC_arrow));
//等待显示器准备完毕
/*waitMonitorsReady();
qDebug() << "monitors ready"*/;
XEventMonitor::instance()->start();
MainWindow w;
w.showFullScreen();
//在没有窗口管理器的情况下,需要激活窗口,行为类似于用鼠标点击窗口
w.activateWindow();
DisplaySwitch ds(&w);
ds.connect(&w, &MainWindow::activeScreenChanged, &ds, &DisplaySwitch::onPositionChanged);
QObject::connect(XEventMonitor::instance(), SIGNAL(keyRelease(QString)),
&ds, SLOT(onGlobalKeyRelease(QString)));
return a.exec();
}
ukui-greeter/ukui-greeter/greeter/mainwindow.cpp 0000644 0001750 0001750 00000023261 13640355124 021042 0 ustar feng feng /* mainwindow.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "mainwindow.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "globalv.h"
#include "greeterwindow.h"
#include "common/configuration.h"
#include "common/monitorwatcher.h"
#include "display-switch/displayservice.h"
bool MainWindow::m_first = true;
QT_BEGIN_NAMESPACE
extern void qt_blurImage(QPainter *p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0);
QT_END_NAMESPACE
#define BLUR_RADIUS 100
QPixmap blurPixmap(QPixmap pixmap)
{
QPainter painter(&pixmap);
QImage srcImg = pixmap.toImage();
qt_blurImage(&painter, srcImg, BLUR_RADIUS, false, false);
painter.end();
return pixmap;
}
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent),
m_screenModel(new ScreenModel(this)),
m_configuration(Configuration::instance()),
m_activeScreen(nullptr),
m_monitorWatcher(new MonitorWatcher(this)),
m_timer(nullptr),
m_background(nullptr)
{
QDesktopWidget *_desktop = QApplication::desktop();
connect(_desktop, &QDesktopWidget::resized, this, &MainWindow::onScreenResized);
/* QDesktopWidget对显示器的插拔的支持不好 */
connect(m_monitorWatcher, &MonitorWatcher::monitorCountChanged, this, &MainWindow::onScreenCountChanged);
//设置窗口大小
setFixedSize(QApplication::primaryScreen()->virtualSize());
//设置监控鼠标移动
setMouseTracking(true);
//cof
//m_cof.load(m_configuration->getValue("cof").toString());
//背景图片 优先级:用户桌面背景、背景图片、背景颜色
m_defaultBackgroundPath = m_configuration->getDefaultBackgroundName();
bool drawUserBackground = m_configuration->getValue("draw-user-background").toBool();
if(drawUserBackground) {
m_backgroundMode = DRAW_USER_BACKGROUND;
} else {
m_background = QSharedPointer(new Background);
QString backgroundPath = m_configuration->getValue("background").toString();
if(!backgroundPath.isEmpty()) {
m_backgroundMode = DRAW_BACKGROUND;
m_background->type = BACKGROUND_IMAGE;
m_background->image = backgroundPath;
} else {
QString color = m_configuration->getValue("background-color").toString();
if(!color.isEmpty()) {
m_backgroundMode = DRAW_COLOR;
m_background->type = BACKGROUND_COLOR;
m_background->color = color;
} else {
m_backgroundMode = DRAW_DEFAULT;
m_background->type = BACKGROUND_IMAGE;
m_background->image = m_defaultBackgroundPath;
}
}
}
qDebug() << "default background:" << m_defaultBackgroundPath;
if(m_background)
qDebug() << m_background->type << m_background->image;
m_timer = new QTimer(this);
m_transition.started = false;
//激活屏幕(即Greeter窗口所在屏幕位置)
m_greeterWnd = new GreeterWindow(this);
moveToScreen(QApplication::primaryScreen());
m_greeterWnd->initUI();
m_monitorWatcher->start();
connect(m_timer, &QTimer::timeout, this, &MainWindow::onTransition);
}
void MainWindow::paintEvent(QPaintEvent *e)
{
for(QScreen *screen : QApplication::screens()){
//在每个屏幕上绘制背景
QRect rect = screen->geometry();
if(m_transition.started)
drawTransitionAlpha(rect);
else {
drawBackground(m_background, rect);
}
QPainter painter(this);
//在没有登录窗口的屏幕上显示图标
// if(screen != m_azctiveScreen)
// {
// QRect cofRect(rect.left() + (rect.width()-m_cof.width())/2,
// rect.top() + (rect.height()-m_cof.height())/2,
// m_cof.width(), m_cof.height());
// painter.drawPixmap(cofRect, m_cof);
// }
}
return QWidget::paintEvent(e);
}
/**
* 根据鼠标指针移动位置移动Greeter窗口所在屏幕
*/
void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
if(QApplication::screens().count() > 1){
QPoint point = e->pos();
QScreen *curScreen = nullptr;
for(QScreen *screen : QApplication::screens()){
QRect screenRect = screen->geometry();
if(screenRect.contains(point)) {
curScreen = screen;
break;
}
}
if(curScreen != m_activeScreen && curScreen != nullptr){
qDebug() << "active screen: from " << m_activeScreen << "to " << curScreen;
moveToScreen(curScreen);
}
}
return QWidget::mouseMoveEvent(e);
}
/**
* 有屏幕分辨率发生改变,移动Greeter窗口位置
*/
void MainWindow::onScreenResized()
{
setGeometry(QApplication::desktop()->geometry());
qDebug() << "screen resize to " << geometry();
moveToScreen(QApplication::primaryScreen());
}
/**
* 有屏幕插拔,移动GreeterWindow到主屏幕
*/
void MainWindow::onScreenCountChanged(int newCount)
{
if(newCount < 2) {
QProcess enableMonitors;
enableMonitors.start("xrandr --auto");
enableMonitors.waitForFinished(-1);
} else {
DisplayService displayService;
displayService.switchDisplayMode(DISPLAY_MODE_EXTEND);
}
// if(m_first){
// show();
// activateWindow();
// }
move(0, 0);
setFixedSize(m_monitorWatcher->getVirtualSize());
moveToScreen(QApplication::primaryScreen());
repaint();
qDebug() << "total screen resize to " << geometry();
}
/**
* 移动Greeter窗口到screen屏幕上
*/
void MainWindow::moveToScreen(QScreen *screen)
{
m_activeScreen = screen;
QRect activeScreenRect = m_activeScreen->geometry();
qDebug() << "moveToScreen activeScreenRect " << activeScreenRect;
//if(m_monitorWatcher->getMonitorCount() == 1)
// activeScreenRect = QRect(QPoint(0, 0), m_monitorWatcher->getVirtualSize());
m_greeterWnd->setGeometry(activeScreenRect);
Q_EMIT activeScreenChanged(activeScreenRect);
repaint();
}
void MainWindow::setBackground(QSharedPointer &background)
{
if(background)
qDebug() << background->image;
if(m_backgroundMode != DRAW_USER_BACKGROUND)
return;
stopTransition();
if(background) {
if(background->image.isEmpty())
background->image = m_defaultBackgroundPath;
}
if(m_background && background &&
m_background->image == background->image){
repaint();
return;
}
//如果是第一次绘制背景,则不需要渐变
if(!m_background.isNull())
startTransition(m_background, background);
m_background = background;
}
void MainWindow::startTransition(QSharedPointer &from,
QSharedPointer &to)
{
stopTransition();
m_transition.from = from;
m_transition.to = to;
m_transition.stage = 0.0;
m_transition.started = true;
m_timer->start(50);
}
void MainWindow::stopTransition()
{
if(m_timer && m_timer->isActive())
m_timer->stop();
m_transition.stage = 1.0;
m_transition.started = false;
}
void MainWindow::onTransition()
{
m_transition.stage += 0.05;//= (1 - cos(M_PI * m_transition.stage)) / 2;
if(m_transition.stage >= 1.0)
stopTransition();
repaint();
}
void MainWindow::drawTransitionAlpha(const QRect &rect)
{
drawBackground(m_transition.from, rect, 1.0 - m_transition.stage);
drawBackground(m_transition.to, rect, m_transition.stage);
}
void MainWindow::drawBackground(QSharedPointer &background,
const QRect &rect, float alpha)
{
if(background == nullptr)
return;
QPainter painter(this);
painter.setOpacity(alpha);
switch(background->type) {
case BACKGROUND_IMAGE:
{
QPixmap *pixmap = getBackground(background->image, rect);
if(pixmap->isNull())
{
QString color = m_configuration->getValue("background-color").toString();
QColor cor;
if(!color.isEmpty())
cor = color;
else
cor = "#035290";
painter.setBrush(cor);
painter.drawRect(rect);
}
else
{
painter.drawPixmap(rect, *pixmap);
}
break;
}
case BACKGROUND_COLOR:
{
painter.setBrush(background->color);
painter.drawRect(rect);
break;
}
}
}
QPixmap * MainWindow::getBackground(const QString &path, const QRect &rect)
{
QString resolution = QString("%1x%2").arg(rect.width()).arg(rect.height());
QPair key(path, resolution);
if(!m_backgrounds.contains(key))
m_backgrounds[key] = new QPixmap(scaledPixmap(width(), height(), path));
return m_backgrounds[key];
}
ukui-greeter/ukui-greeter/greeter/rootWindowBackground.cpp 0000644 0001750 0001750 00000003660 13640355124 023042 0 ustar feng feng /* rootWindowBackground.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include
#include
#include
#include "rootWindowBackground.h"
void setRootWindowBackground(int width,int height,char *filename)
{
Imlib_Image img;
Display *dpy;
Pixmap pix;
Window root;
Screen *scn;
img = imlib_load_image(filename);
if (!img) {
fprintf(stderr, "%s:Unable to load image\n", filename);
return ;
}
imlib_context_set_image(img);
dpy = XOpenDisplay(NULL);
if (!dpy)
return ;
scn = DefaultScreenOfDisplay(dpy);
root = DefaultRootWindow(dpy);
pix = XCreatePixmap(dpy, root, width, height,
DefaultDepthOfScreen(scn));
imlib_context_set_display(dpy);
imlib_context_set_visual(DefaultVisualOfScreen(scn));
imlib_context_set_colormap(DefaultColormapOfScreen(scn));
imlib_context_set_drawable(pix);
imlib_render_image_on_drawable_at_size(0, 0, width, height);
XSetWindowBackgroundPixmap(dpy, root, pix);
XClearWindow(dpy, root);
while (XPending(dpy)) {
XEvent ev;
XNextEvent(dpy, &ev);
}
XFreePixmap(dpy, pix);
imlib_free_image();
XCloseDisplay(dpy);
return ;
}
ukui-greeter/ukui-greeter/greeter/pagelistview.cpp 0000644 0001750 0001750 00000023521 13621375753 021401 0 ustar feng feng /* pagelistview.cpp
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "pagelistview.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "globalv.h"
#include "userentry.h"
PageListView::PageListView(QWidget *parent)
: QWidget(parent),
m_layout(nullptr),
m_lastItem(-1)
{
}
void PageListView::keyReleaseEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Return:
{
UserEntry *entry = m_itemList[m_curItem];
onEntrySelected(entry->userName());
break;
}
case Qt::Key_PageUp:
pageUp();
break;
case Qt::Key_PageDown:
pageDown();
break;
case Qt::Key_Left:
preItem();
break;
case Qt::Key_Right:
nextItem();
break;
case Qt::Key_Home:
goHome();
break;
case Qt::Key_End:
goEnd();
break;
default:
break;
}
QWidget::keyReleaseEvent(event);
}
void PageListView::resizeEvent(QResizeEvent *)
{
for(int i = 0; i < m_itemList.size(); i++)
if(m_itemList[i])
m_itemList[i]->setFixedSize(130 * scale + 20, 130 * scale + 75);
}
void PageListView::setModel(QSharedPointer model)
{
if(model.isNull())
return;
if(!m_model.isNull())
{
}
m_model = model;
connect(m_model.data(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onUserInserted(QModelIndex,int,int)));
connect(m_model.data(), SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(onUserRemoved(QModelIndex,int,int)));
connect(m_model.data(), SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector)),
this, SLOT(onUserChanged(QModelIndex,QModelIndex)));
// m_itemList = QVector(m_model.data()->rowCount(), NULL);
for(int i = 0; i < m_model->rowCount(); i++)
{
UserEntry *entry = createEntry(i);
entry->hide();
m_itemList.append(entry);
}
m_lastend = m_curItem = -1;
m_itemCount = m_model.data()->rowCount();
/* 读取上一次登录的用户 */
QSettings config(configFile, QSettings::IniFormat);
QString lastUser = config.value("lastLoginUser").toString();
qDebug() << "lastLoginUser: " << lastUser;
for(int i = 0; i < m_model->rowCount(); i++) {
QString user = m_model->index(i, 0).data(QLightDM::UsersModel::NameRole).toString();
if(lastUser == user) {
m_curItem = i;
break;
}
}
if(m_curItem < 0) {
m_curItem = 0;
}
//当前要显示的用户是哪几个
int np = qCeil((m_curItem + 1) * 1.0 / 5);
if(m_itemCount <= np * 5){
m_end = m_itemCount -1;
} else {
m_end = np * 5 - 1;
}
drawPage();
}
void PageListView::drawPage()
{
if(m_layout != nullptr)
delete(m_layout);
m_layout = new QHBoxLayout(this);
m_layout->setSpacing(10);
int begin = m_end - (m_itemCount > 5 ? 4 : m_itemCount - 1);
if(m_lastend > 0)
{
int lastbegin = m_lastend - (m_itemCount > 5 ? 4 : m_itemCount - 1);
lastbegin = lastbegin > 0 ? lastbegin : 0;
for(int i = lastbegin; i <= m_lastend; i++)
{
m_layout->removeWidget(m_itemList[i]);
m_itemList[i]->hide();
}
}
// if(m_itemCount < 5)
// m_layout->addStretch();
for(int i = begin; i <= m_end; i++)
{
//如果entry不存在则创建,添加到layout中
if(m_itemList[i] == NULL) {
m_itemList[i] = createEntry(i);
} else if(m_itemList[i]->userName() != m_model->index(i, 0).data().toString()) {
m_itemList.insert(i, createEntry(i));
}
m_itemList[i]->show();
m_layout->insertWidget(i - begin, m_itemList[i], 0);
// m_layout->addStretch();
}
if(m_itemList.size() > 0) {
// m_itemList[m_curItem]->setFocus();
moveFocus();
}
emit pageChanged();
}
UserEntry* PageListView::createEntry(int i)
{
QModelIndex index = m_model->index(i, 0);
UserEntry *entry = new UserEntry(index.data(Qt::DisplayRole).toString(),
index.data(QLightDM::UsersModel::ImagePathRole).toString(),
index.data(QLightDM::UsersModel::LoggedInRole).toBool(), this);
connect(entry, SIGNAL(clicked(QString)), this, SLOT(onEntrySelected(QString)));
return entry;
}
void PageListView::pageUp()
{
if(m_itemCount <= 5 || m_end == 4) //位于首页
{
m_curItem = 0;
// m_itemList[m_curItem]->setFocus();
moveFocus();
return;
}
m_lastend = m_end;
m_end -= (m_end-5 >= 4 ? 5 : (m_end-4));
m_curItem = m_end - 4;
drawPage();
}
void PageListView::pageDown()
{
if(m_itemCount <= 5 || m_end == m_itemCount - 1) //位于尾页
{
m_curItem = m_end;
// m_itemList[m_curItem]->setFocus();
moveFocus();
return;
}
m_lastend = m_end;
m_end += (m_itemCount-1-m_end >= 5 ? 5 : (m_itemCount-1-m_end));
m_curItem = m_end;
drawPage();
}
void PageListView::goHome()
{
if(m_itemCount <= 5 || m_end == 4)
{
m_curItem = 0;
// m_itemList[m_curItem]->setFocus();
moveFocus();
return;
}
m_lastend = m_end;
m_end = 4;
m_curItem = 0;
drawPage();
}
void PageListView::goEnd()
{
if(m_itemCount <= 5 || m_end == m_itemCount - 1) //位于尾页
{
m_curItem = m_end;
// m_itemList[m_curItem]->setFocus();
moveFocus();
return;
}
m_lastend = m_end;
m_end = m_itemCount - 1;
m_curItem = m_end;
drawPage();
}
void PageListView::preItem()
{
int begin = m_itemCount > 5 ? m_end - 4 : 0;
if(m_curItem - begin > 0)
{
--m_curItem;
// m_itemList[m_curItem]->setFocus();
moveFocus();
}
else if(m_curItem > 0)
{
--m_curItem;
m_lastend = m_end;
--m_end;
drawPage();
}
}
void PageListView::nextItem()
{
if(m_curItem < m_end)
{
++m_curItem;
// m_itemList[m_curItem]->setFocus();
moveFocus();
}
else if(m_curItem < m_itemCount - 1)
{
++m_curItem;
m_lastend = m_end;
++m_end;
drawPage();
}
}
void PageListView::onEntrySelected(const QString &name)
{
for(int i = 0; i < m_itemList.size(); i++){
if(m_itemList[i]!=NULL && m_itemList[i]->userName() == name){
m_curItem = i;
}
}
moveFocus();
emit selectedChanged(m_model.data()->index(m_curItem, 0));
}
bool PageListView::hasPrev()
{
if(m_end > 4)
return true;
else
return false;
}
bool PageListView::hasNext()
{
if(m_end < m_itemCount -1)
return true;
else
return false;
}
/**
* @brief PageListView::onUserInserted
* @param parent
* @param begin
* @param end
* 有用户增加
*/
void PageListView::onUserInserted(const QModelIndex& parent, int begin, int end)
{
Q_UNUSED(parent)
for(int i = begin; i <= end; i++)
{
qDebug() << "User added:" << m_model->index(i, 0).data().toString();
m_itemList.insert(i, createEntry(i));
}
m_itemCount = m_model->rowCount();
m_curItem = begin;
if(m_end >= begin || m_itemCount <= 5) {
m_lastend = m_end;
if(m_itemCount <= 5)
m_end = m_itemCount - 1;
drawPage();
} else {
pageDown();
}
}
/**
* @brief PageListView::onUserRemoved
* @param parent
* @param begin
* @param end
* 有用户删除
*/
void PageListView::onUserRemoved(const QModelIndex & parent, int begin, int end)
{
Q_UNUSED(parent)
for(int i = begin; i<=end; i++) {
if(m_itemList[i])
delete(m_itemList[i]);
m_itemList.remove(i);
}
if(m_end == m_itemCount-1) {
m_end -= (end-begin+1);
m_lastend = m_end;
}
if(m_curItem >= m_end) {
m_curItem = m_end;
}
m_itemCount = m_model->rowCount();
drawPage();
}
/**
* @brief PageListView::onUserChanged
* @param topLeft
* @param bottomRight
* 用户信息发生变化
*/
void PageListView::onUserChanged(const QModelIndex & topLeft,
const QModelIndex& bottomRight)
{
int begin = topLeft.row();
int end = bottomRight.row();
for(int i = begin; i <= end; i++) {
if(m_itemList[i]) {
QModelIndex index = m_model->index(i, 0);
m_itemList[i]->setUserName(index.data().toString());
m_itemList[i]->setFace(index.data(QLightDM::UsersModel::ImagePathRole).toString());
m_itemList[i]->setLogin(index.data(QLightDM::UsersModel::LoggedInRole).toBool());
qDebug() << "user " << index.data().toString() <<"changed";
}
}
}
void PageListView::moveFocus()
{
if(m_lastItem >= 0 && m_lastItem < m_itemCount && m_itemList[m_lastItem] != NULL)
m_itemList[m_lastItem]->setSelected(false);
m_itemList[m_curItem]->setSelected();
m_lastItem = m_curItem;
}
ukui-greeter/ukui-greeter/greeter/language.cpp 0000644 0001750 0001750 00000007606 13632370235 020457 0 ustar feng feng /**
* Copyright (C) 2018 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
**/
#include "language.h"
#include
#include
#include
#include
QString getLocaleName(const QString &code)
{
static QStringList locales;
QString language;
int at;
if((at = code.indexOf('@')) != -1)
language = code.left(at);
else
language = code;
if(locales.isEmpty())
{
QProcess process;
QString command = "locale -a";
process.start(command);
process.waitForFinished(3000);
QString result = process.readAll();
locales = result.split("\n");
}
for(auto locale : locales)
{
if(locale.lastIndexOf(".utf8") == -1)
continue;
if(!locale.isEmpty() && locale.indexOf(language) != -1)
return locale;
}
return "";
}
QString getName(const QString &code)
{
QString name;
QString locale = getLocaleName(code);
if(!locale.isEmpty())
{
char *currentLocale = setlocale(LC_ALL, NULL);
setlocale(LC_IDENTIFICATION, locale.toUtf8().data());
setlocale(LC_MESSAGES, "");
char *language = nl_langinfo(_NL_IDENTIFICATION_LANGUAGE);
if(language && strlen(language) > 0)
{
name = QString(dgettext("iso_639_3", language));
}
setlocale(LC_ALL, currentLocale);
}
return name;
}
QString getTerritory(const QString &code)
{
if(code.indexOf('_') == -1)
return "";
QString territory;
QString locale = getLocaleName(code);
if(!locale.isEmpty())
{
char *currentLocale = setlocale(LC_ALL, NULL);
setlocale(LC_IDENTIFICATION, locale.toUtf8().data());
setlocale(LC_MESSAGES, "");
char *country = nl_langinfo(_NL_IDENTIFICATION_TERRITORY);
if(country && strlen(country) > 0 && strcmp(country, "ISO") != 0)
{
territory = QString(dgettext("iso_3166", country));
}
setlocale(LC_ALL, currentLocale);
}
return territory;
}
LanguagesVector& getLanguages()
{
static LanguagesVector languagesVector;
if(!languagesVector.isEmpty())
return languagesVector;
QProcess process;
QString command = "/usr/share/language-tools/language-options";
process.start(command);
process.waitForFinished(3000);
QString result = process.readAll();
QStringList langs = result.split("\n");
if(result.isEmpty())
return languagesVector;
for(auto lang : langs)
{
QString name = getName(lang);
QString territory = getTerritory(lang);
Language language{lang, name, territory};
languagesVector.push_back(language);
}
return languagesVector;
}
Language getLanguage(const QString &lang)
{
LanguagesVector &languages = getLanguages();
QString code = lang;
if(code.toLower().lastIndexOf(".utf-8") != -1)
{
code = code.left(code.length() - 6);
}
for(int i=0;i