repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/Channel.h
|
#ifndef NLIB_CHANNEL_H
#define NLIB_CHANNEL_H
#include "header.h"
#include "TimeStamp.h"
#include "EventLoop.h"
class EventLoop;
// 1.一个事件循环loop时占据一个线程
// 线程不停处理的就是阻塞等待描述符集合中每个描述符上事件是否发生
// 每个描述符要等待哪些事件/事件发生时各类回调指定/等待事件更新
// Channel负责处理上述事宜
// 2.Channel对象本身无互斥/同步处理.
// 存在多线程操作共享Channel对象情况时,使用者负责处理互斥/同步
// 描述符--Channel--EPoll
//
class Channel
{
public:
typedef std::function<void()> EventCallback;
typedef std::function<void(TimeStamp)> ReadEventCallback;
// 传入loop负责fd的事件监听及回调
Channel(
EventLoop* loop,
int fd);
~Channel();
void handleEvent(
TimeStamp receiveTime);
void setReadCallback(
ReadEventCallback cb)
{
m_nReadCallback = std::move(cb);
}
void setWriteCallback(
EventCallback cb)
{
m_nWriteCallback = std::move(cb);
}
void setCloseCallback(
EventCallback cb)
{
m_nCloseCallback = std::move(cb);
}
void setErrorCallback(
EventCallback cb)
{
m_nErrorCallback = std::move(cb);
}
void tie(const std::shared_ptr<void>&);
int fd() const
{
return m_nFd;
}
int events() const
{
return m_nEvents;
}
// 描述符要求Poll监听一个事件集合
// 事件发生时Poll告知发生的事件集合[监听事件的子集]
void set_revents(int revt)
{
m_nRevents = revt;
}
bool isNoneEvent() const
{
return m_nEvents == s_nNoneEvent;
}
void enableReading()
{
m_nEvents |= s_nReadEvent;
update();
}
void disableReading()
{
m_nEvents &= ~s_nReadEvent;
update();
}
void enableWriting()
{
m_nEvents |= s_nWriteEvent;
update();
}
void disableWriting()
{
m_nEvents &= ~s_nWriteEvent;
update();
}
void disableAll()
{
m_nEvents = s_nNoneEvent;
update();
}
bool isWriting() const
{
return m_nEvents & s_nWriteEvent;
}
bool isReading() const
{
return m_nEvents & s_nReadEvent;
}
int index()
{
return m_nIndex;
}
void set_index(int idx)
{
m_nIndex = idx;
}
string reventsToString() const;
string eventsToString() const;
void doNotLogHup()
{
m_bLogHup = false;
}
EventLoop* ownerLoop()
{
return m_pLoop;
}
void remove();
static string eventsToString(int fd, int ev);
private:
void update();
void handleEventWithGuard(TimeStamp receiveTime);
private:
static const int s_nNoneEvent;
static const int s_nReadEvent;
static const int s_nWriteEvent;
private:
EventLoop* m_pLoop;
const int m_nFd;
int m_nEvents;
int m_nRevents;
// 用于标识
// 本Channel负责的描述符针对关联的事件循环的Poll
// 是尚未监听/已经监听/...
int m_nIndex;
// 挂起时记录日志
bool m_bLogHup;
// weak_ptr<void>可存储任何weak_ptr<T>类型对象
std::weak_ptr<void> m_pTie;
bool m_bTied;
bool m_bEventHandling;
bool m_bAddedToLoop;
ReadEventCallback m_nReadCallback;
EventCallback m_nWriteCallback;
EventCallback m_nCloseCallback;
EventCallback m_nErrorCallback;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/Poller.h
|
<gh_stars>1-10
#ifndef NLIB_POLLER_H
#define NLIB_POLLER_H
#include "header.h"
#include "TimeStamp.h"
#include "EventLoop.h"
class Channel;
class Poller
{
public:
typedef std::vector<Channel*> ChannelList;
Poller(
EventLoop* loop);
virtual ~Poller();
virtual TimeStamp poll(
int timeoutMs,
ChannelList* activeChannels) = 0;
virtual void updateChannel(
Channel* channel) = 0;
virtual void removeChannel(
Channel* channel) = 0;
virtual bool hasChannel(
Channel* channel) const;
void assertInLoopThread() const
{
m_pOwnerLoop->assertInLoopThread();
}
static Poller* newDefaultPoller(
EventLoop* loop);
protected:
typedef std::map<int, Channel*> ChannelMap;
ChannelMap m_nChannels;
private:
EventLoop* m_pOwnerLoop;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoServer/DataStruct/fixqueue.h
|
// Author : XuBenHao
// Version : 1.0.0
// Mail : <EMAIL>
// Copyright : XuBenHao 2020 - 2030
#ifndef DATA_STRUCT_FIXQUEUE_H
#define DATA_STRUCT_FIXQUEUE_H
#include "header.h"
#include "doublelist.h"
namespace NDataStruct
{
template <typename T, int N>
class FixQueue
{
public:
FixQueue();
virtual ~FixQueue();
FixQueue(const FixQueue& dqA_);
FixQueue& operator=(const FixQueue& dqA_);
void In(const T& nValue_);
T Out();
T Peek() const;
bool IsEmpty() const;
int Size() const;
DoubleList<T> GetList() const
{
return m_List;
}
private:
DoubleList<T> m_List;
};
template <typename T, int N>
FixQueue<T,N>::FixQueue()
{
}
template <typename T, int N>
FixQueue<T,N>::~FixQueue()
{
}
template <typename T, int N>
FixQueue<T,N>::FixQueue(const FixQueue& dqA_)
{
m_List = dqA_.m_List;
}
template <typename T, int N>
FixQueue<T,N>& FixQueue<T,N>::operator=(const FixQueue& dqA_)
{
if (this == &dqA_)
{
return *this;
}
m_List = dqA_.m_List;
return *this;
}
template <typename T, int N>
void FixQueue<T,N>::In(const T& nValue_)
{
if(Size() >= N)
{
return;
}
m_List.InsertLast(nValue_);
}
template <typename T, int N>
T FixQueue<T,N>::Out()
{
if (IsEmpty())
{
throw "queue is empty";
}
typename DoubleList<T>::Node* _pFirst = m_List.GetFirst();
T _nValue = _pFirst->GetValue();
m_List.DeleteFirst();
return _nValue;
}
template <typename T, int N>
T FixQueue<T,N>::Peek() const
{
if (IsEmpty())
{
throw "queue is empty";
}
typename DoubleList<T>::Node* _pFirst = m_List.GetFirst();
return _pFirst->GetValue();
}
template <typename T, int N>
bool FixQueue<T,N>::IsEmpty() const
{
return m_List.IsEmpty();
}
template <typename T, int N>
int FixQueue<T,N>::Size() const
{
return m_List.GetSize();
}
}
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/ThreadLocal.h
|
#ifndef NLIB_THREADLOCAL_H
#define NLIB_THREADLOCAL_H
#include "Mutex.h"
// 一个模板类对象
// 包含的m_nKey提供了所有线程共享的一个索引
// 包含的value,可供所有可访问此对象的线程调用,以得到调用线程自己的一个T对象
// 对每个T
// 提供一个所有线程共享的全局ThreadLocal<T>对象即可
template<typename T>
class ThreadLocal
{
public:
ThreadLocal()
{
pthread_key_create(
&m_nKey,
&ThreadLocal::destructor);
}
~ThreadLocal()
{
pthread_key_delete(m_nKey);
}
T& value()
{
T* perThreadValue = (T*)(pthread_getspecific(m_nKey));
if (!perThreadValue)
{
T* newObj = new T();
pthread_setspecific(m_nKey, newObj);
perThreadValue = newObj;
}
return *perThreadValue;
}
private:
static void destructor(void *x)
{
T* obj = (T*)(x);
delete obj;
}
private:
pthread_key_t m_nKey;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoServer/MuduoApp/muduoclient.h
|
<gh_stars>1-10
// Author : XuBenHao
// Version : 1.0.0
// Mail : <EMAIL>
// Copyright : XuBenHao 2020 - 2030
//
#ifndef MUDUO_APP_MUDUOCLIENT_H
#define MUDUO_APP_MUDUOCLIENT_H
#include "header.h"
#include "codec.h"
void LogOutput(const char* msg, int len);
class MuduoClient
{
public:
static MuduoClient* instance(EventLoop* loop, const InetAddress& serverAddr);
void connect();
void disconnect();
void write(const StringPiece& message);
private:
void onConnection(const TcpConnectionPtr& conn);
void onStringMessage(
const TcpConnectionPtr&,
const string& message,
TimeStamp);
private:
MuduoClient(EventLoop* loop, const InetAddress& serverAddr);
private:
static MuduoClient* __instance;
private:
TcpClient m_nClient;
LengthHeaderCodec m_nCodec;
MutexLock m_nMutex;
TcpConnectionPtr m_nConnection;
};
#endif // MUDUOCLIENT_H
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/TimeZone.h
|
#ifndef NLIB_TIMEZONE_H
#define NLIB_TIMEZONE_H
#include "header.h"
class TimeZone
{
public:
explicit TimeZone(
const char* zonefile);
TimeZone(
int eastOfUtc,
const char* tzname);
TimeZone() = default;
bool valid() const
{
return (bool)(m_pData);
}
struct tm toLocalTime(
time_t secondsSinceEpoch) const;
time_t fromLocalTime(
const struct tm&) const;
static struct tm toUtcTime(
time_t secondsSinceEpoch,
bool yday = false);
static time_t fromUtcTime(
const struct tm&);
static time_t fromUtcTime(
int year,
int month,
int day,
int hour,
int minute,
int seconds);
struct Data;
private:
std::shared_ptr<Data> m_pData;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoServer/MuduoApp/muduoserver.h
|
<gh_stars>1-10
// Author : XuBenHao
// Version : 1.0.0
// Mail : <EMAIL>
// Copyright : XuBenHao 2020 - 2030
//
#ifndef MUDUO_APP_MUDUOSERVER_H
#define MUDUO_APP_MUDUOSERVER_H
#include "header.h"
#include "codec.h"
// TcpServer的用户通过TcpServer提供的接口来使用TcpServer的功能
// 内部的高效运作,正确性管理属于网络库的责任
//
// 提供的接口包含:
// 1.开启服务器的监听
// 2.设置收到已经连接套接字信息时的回调
// 3.设置服务器的属性
// 4.关闭服务器
// 与客户端一样
// 因为一般TCP的
// 消息接收需要解码再交给应用
// 消息发送需要编码再交给TcpConnection
// 所以可TcpClient一样,TcpServer没有提供给TcpConnection发消息接口
// 应用层需要自己实现
// 原始消息--编码--发给TcpConnection
class Message
{
public:
Message()
{
m_bDirection = true;
}
~Message()
{
}
public:
QByteArray m_nContent;
bool m_bDirection;
TimeStamp m_nTimeStamp;
};
class MuduoServer
{
public:
// for client to server direction
enum MessageType
{
REGISTER = 0,
LOGIN = 1,
ADD = 2,
UPDATE_FRIEND_LIST = 3,
OFF_LINE = 4,
NEED_TO_PROCESS_USER_LIST = 5,
CHAT = 6,
GET_NEED_TO_PROCESS_MESSAGES = 7,
};
// for server to client direction
enum ResMessageType
{
REGISTER_RES = 0,
LOGIN_RES = 1,
ADD_RES = 2,
UPDATE_FRIEND_LIST_RES = 3,
NEED_TO_PROCESS_USER_LIST_RES = 4,
CHAT_RES = 5,
NEW_MESSAGE_NOTIFICATION = 6,
GET_NEED_TO_PROCESS_MESSAGES_RES = 7,
};
public:
MuduoServer(
EventLoop* loop,
const InetAddress& listenAddr,
char* pStrHost_,
int nHostLen_,
char* pStrUser_,
int nUserLen_,
char* pStrPassword_,
int nPasswordLen_);
// tcp server with multiple threads consisting of thread pool
void setThreadNum(int numThreads);
// create socket and start listen, at the same starting watching the event of readable
void start();
private:
void threadInit(EventLoop* loop);
// 不论连接回调由服务器端那个线程触发
// 执行的回调函数都是这个
// 且由于成员函数性质,所有线程执行回调时,
// 均可获得一个多个线程共享的回调语境---一个共享的MuduoServer对象
// the time of one client connection build and destroy
void onConnection(const TcpConnectionPtr& conn);
void onMessage(
const TcpConnectionPtr& conn,
Buffer* buf,
TimeStamp receiveTime);
// a place to decode the client's message
// and dispatch the decoded message to process it
void onStringMessage(
const TcpConnectionPtr&,
void* strMessage_,
int nLength_,
TimeStamp);
bool ResForRegister(
const TcpConnectionPtr& pTcpConnection_,
int nRetCode_);
bool PackRegisterResMessage(
int nRetCode_,
Buffer& nBuf_);
bool ResForLogin(
const TcpConnectionPtr& pTcpConnection_,
int nRetCode_,
TimeStamp nTimeStamp_ = TimeStamp());
bool PackLoginResMessage(
int nRetCode_,
TimeStamp nTimeStamp_,
Buffer& nBuf_);
bool ResForAdd(
const TcpConnectionPtr& pTcpConnection_,
int nRetCode_);
bool PackAddResMessage(
int nRetCode_,
Buffer& nBuf_);
bool ResForUpdateFriendList(
const TcpConnectionPtr& pTcpConnection_,
const NDataStruct::DynArray<QByteArray>& arrUserIds_);
bool PackUpdateFriendListResMessage(
const NDataStruct::DynArray<QByteArray>& arrUserIds_,
Buffer& nBuf_);
bool ResForNeedToProcessUserList(
const TcpConnectionPtr& pTcpConnection_,
const NDataStruct::DynArray<QByteArray>& arrUserIds_);
bool PackNeedToProcessUserListResMessage(
const NDataStruct::DynArray<QByteArray>& arrUserIds_,
Buffer& nBuf_);
bool ResForGetNeedToProcessMessagesMessage(
const TcpConnectionPtr& pTcpConnection_,
const NDataStruct::DynArray<Message>& arrMessages_);
bool PackGetNeedToProcessMessagesMessage(
const NDataStruct::DynArray<Message>& arrMessages_,
Buffer& nBuf_);
bool ResForChatMessage(
const TcpConnectionPtr& pTcpConnection_);
bool PackChatResMessage(
Buffer& nBuf_);
bool ResForNewMessageNotification(
const TcpConnectionPtr& pTcpConnection_,
const QByteArray& nByteSender_);
bool PackNewResMessageNotification(
const QByteArray& nByteSender_,
Buffer& nBuf_);
// a place to pack message and sending to client
// void PackAndSend(
// int nType_,
// );
//void
typedef std::set<TcpConnectionPtr> ConnectionList;
typedef std::map<QByteArray, std::set<TcpConnectionWeakPtr>> ConnectionMapping;
typedef NDataStruct::DynArray<std::pair<TimeStamp, TcpConnectionWeakPtr>> ComplexConnections;
typedef std::shared_ptr<ComplexConnections> ComplexConnectionsPtr;
typedef std::map<QByteArray, ComplexConnectionsPtr> ComplexConnectionsMapping;
void distributeMessage(
const string& message);
private:
bool ProcessRegister(
const TcpConnectionPtr& pTcpConnection_,
char* pUserId_,
int nUserIdLen_,
char* pPassword_,
int nPasswordLen_);
bool ProcessLogin(
const TcpConnectionPtr& pTcpConnection_,
char* pUserId_,
int nUserIdLen_,
char* pPassword_,
int nPasswordLen_);
bool ProcessAdd(
const TcpConnectionPtr& pTcpConnection_,
char* pMasterUserId_,
int nMasterUserIdLen_,
char* pUserId_,
int nUserIdLen_);
bool ProcessUpdateFriendList(
const TcpConnectionPtr& pTcpConnection_,
char* pUserId_,
int nUserIdLen_);
bool ProcessNeedToProcessUserList(
const TcpConnectionPtr& pTcpConnection_,
char* pUserId_,
int nUserIdLen_);
bool ProcessChatMessage(
const TcpConnectionPtr& pTcpConnection_,
char* pSenderUserId_,
int nSenderUserIdLen_,
char* pReceiverUserId_,
int nReceiverUserIdLen_,
char* pChatContent_,
int nChatContentLen_);
bool ProcessGetNeedToProcessMessagesMessage(
const TcpConnectionPtr& pTcpConnection_,
char* pSenderUserId_,
int nSenderUserIdLen_,
char* pReceiverUserId_,
int nReceiverUserIdLen_);
bool ProcessOffLine(
const TcpConnectionPtr& pTcpConnection_,
char* pUserId_,
int nUserIdLen_,
const TimeStamp& nTimeStamp_);
private:
TcpServer m_nServer;
MySqlAgent m_nSqlAgent;
//LengthHeaderCodec m_nCodec;
// every thread in the thread pool has a ConnectionList object
typedef ThreadLocalSingleton<ConnectionList> LocalConnections;
MutexLock m_nMutex;
// every thread in the thread pool has a EventLoop object
std::set<EventLoop*> m_nLoops;
MutexLock m_nMutexForMapping;
ComplexConnectionsMapping m_mapComplexConnectionsMapping;
};
#endif // MUDUOSERVER_H
|
Fragrant-Yang/git-test-copy
|
MuduoClient/Ui/addfrienddialog.h
|
<filename>MuduoClient/Ui/addfrienddialog.h
// Author : XuBenHao
// Version : 1.0.0
// Mail : <EMAIL>
// Copyright : XuBenHao 2020 - 2030
//
#ifndef APP_UI_ADDFRIENDDIALOG_H
#define APP_UI_ADDFRIENDDIALOG_H
#include "header.h"
namespace Ui {
class AddFriendDialog;
}
class AddFriendDialog : public QDialog
{
Q_OBJECT
public:
explicit AddFriendDialog(QWidget *parent = nullptr);
~AddFriendDialog();
void Initialize();
void SetMasterUserId(const QByteArray& arrUserId_){m_arrMasterUserId = arrUserId_;}
//private:
// void UpdateFriendCallback(NDataStruct::DynArray<QByteArray> arrUserIds_);
private slots:
void AddClicked(bool checked_);
void ExitClicked(bool checked_);
private:
void AddCallback(int nType_);
void ErrorCallback(const TcpConnectionPtr&);
private:
mutable MutexLock m_nMutex;
Condition m_nCondition;
int m_nAddRet;
bool m_bError;
QByteArray m_arrMasterUserId;
private:
Ui::AddFriendDialog *ui;
};
#endif // ADDFRIENDDIALOG_H
|
Fragrant-Yang/git-test-copy
|
MuduoServer/MuduoApp/lib.h
|
<filename>MuduoServer/MuduoApp/lib.h<gh_stars>1-10
#ifndef MUDUO_APP_LIB_H
#define MUDUO_APP_LIB_H
#include "muduoclient.h"
#include "muduoserver.h"
#endif // LIB_H
|
Fragrant-Yang/git-test-copy
|
MuduoClient/Ui/registerandloginwidget.h
|
<filename>MuduoClient/Ui/registerandloginwidget.h
// Author : XuBenHao
// Version : 1.0.0
// Mail : <EMAIL>
// Copyright : XuBenHao 2020 - 2030
//
#ifndef APP_UI_REGISTERANDLOGINWIDGET_H
#define APP_UI_REGISTERANDLOGINWIDGET_H
#include "header.h"
namespace Ui {
class RegisterAndLoginWidget;
}
class RegisterAndLoginWidget : public QWidget
{
Q_OBJECT
public:
explicit RegisterAndLoginWidget(QWidget *parent = nullptr);
~RegisterAndLoginWidget();
void Initialize();
private slots:
void OnLoginClicked(bool bFlag_);
void OnRegisterClicked(bool bFlag_);
private:
void RegisterCallback(int nType_);
void ErrorCallback(const TcpConnectionPtr&);
void LoginCallback(int nType_, TimeStamp nTimeStamp_);
Q_SIGNALS:
//void ShowDataStruct(const QString& strName_);
void ShowMainChatWidget(const QByteArray& strUserId_, const TimeStamp& nTimeStamp_);
private:
Ui::RegisterAndLoginWidget *ui;
mutable MutexLock m_nMutex;
Condition m_nCondition;
int m_nRegisterRet;
int m_nLoginRet;
TimeStamp m_nTimeStamp;
bool m_bError;
};
#endif // REGISTERANDLOGINWIDGET_H
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/PollPoller.h
|
#ifndef NLIB_POLLER_POLLPOLLER_H
#define NLIB_POLLER_POLLPOLLER_H
#include "header.h"
#include "Poller.h"
struct pollfd;
class PollPoller : public Poller
{
public:
PollPoller(
EventLoop* loop);
~PollPoller() override;
TimeStamp poll(
int timeoutMs,
ChannelList* activeChannels) override;
void updateChannel(Channel* channel) override;
void removeChannel(Channel* channel) override;
private:
void fillActiveChannels(
int numEvents,
ChannelList* activeChannels) const;
typedef std::vector<struct pollfd> PollFdList;
PollFdList m_nPollFds;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/WeakCallback.h
|
<reponame>Fragrant-Yang/git-test-copy
#ifndef NLIB_WEAKCALLBACK_H
#define NLIB_WEAKCALLBACK_H
template<typename CLASS, typename... ARGS>
class WeakCallback
{
public:
WeakCallback(
const std::weak_ptr<CLASS>& object,
const std::function<void (CLASS*, ARGS...)>& function)
: m_nObject(object), m_nFunction(function)
{
}
void operator()(ARGS&&... args) const
{
std::shared_ptr<CLASS> ptr(m_nObject.lock());
if (ptr)
{
m_nFunction(
ptr.get(),
std::forward<ARGS>(args)...);
}
}
private:
std::weak_ptr<CLASS> m_nObject;
std::function<void (CLASS*, ARGS...)> m_nFunction;
};
template<typename CLASS, typename... ARGS>
WeakCallback<CLASS, ARGS...> makeWeakCallback(
const std::shared_ptr<CLASS>& object,
void (CLASS::*function)(ARGS...))
{
return WeakCallback<CLASS, ARGS...>(object, function);
}
template<typename CLASS, typename... ARGS>
WeakCallback<CLASS, ARGS...> makeWeakCallback(
const std::shared_ptr<CLASS>& object,
void (CLASS::*function)(ARGS...) const)
{
return WeakCallback<CLASS, ARGS...>(object, function);
}
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/FileUtil.h
|
<gh_stars>1-10
#ifndef NLIB_FILEUTIL_H
#define NLIB_FILEUTIL_H
#include "header.h"
#include "StringPiece.h"
// 通过类的接口来实现将文件内容读入缓冲区
class ReadSmallFile
{
public:
ReadSmallFile(
StringArg filename);
~ReadSmallFile();
template<typename T>
int readToString(
int maxSize,
T* content,
int64_t* fileSize,
int64_t* modifyTime,
int64_t* createTime);
int readToBuffer(
int* size);
const char* buffer() const
{
return m_strBuf;
}
static const int s_nBufferSize = 64*1024;
private:
int m_nFd;
int m_nErr;
char m_strBuf[s_nBufferSize];
};
template<typename T>
int readFile(
StringArg filename,
int maxSize,
T* content,
int64_t* fileSize = NULL,
int64_t* modifyTime = NULL,
int64_t* createTime = NULL)
{
ReadSmallFile file(filename);
return file.readToString(
maxSize,
content,
fileSize,
modifyTime,
createTime);
}
// 通过类接口,可以不断以追加方式向文件写入内容
class AppendFile
{
public:
explicit AppendFile(
StringArg filename);
~AppendFile();
void append(
const char* logline,
size_t len);
void flush();
off_t writtenBytes() const
{
return m_nWrittenBytes;
}
private:
size_t write(
const char* logline,
size_t len);
private:
FILE* m_pFp;
char m_strBuffer[64*1024];
off_t m_nWrittenBytes;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/CountDownLatch.h
|
#ifndef NLIB_COUNTDOWNLATCH_H
#define NLIB_COUNTDOWNLATCH_H
#include "header.h"
#include "Condition.h"
#include "Mutex.h"
// 一个内部支持
// 多线程间互斥/同步访问的对象类型
// 内部处理的是一个计数
class CountDownLatch
{
public:
explicit CountDownLatch(int count);
void wait();
void countDown();
int getCount() const;
private:
// mutable数据成员意义是
// 以const CountDownLatch执行对该成员访问时,
// 该成员是可修改的
mutable MutexLock m_nMutex;
Condition m_nCondition;
int m_nCount;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/Endian.h
|
#ifndef NLIB_ENDIAN_H
#define NLIB_ENDIAN_H
#include "header.h"
inline uint64_t hostToNetwork64(uint64_t host64)
{
// 以主机字节序存储的整数值变为大端存储的整数值
return htobe64(host64);
}
inline uint32_t hostToNetwork32(uint32_t host32)
{
return htobe32(host32);
}
inline uint16_t hostToNetwork16(uint16_t host16)
{
return htobe16(host16);
}
inline uint64_t networkToHost64(uint64_t net64)
{
// 以大端存储的整数值变为主机字节序存储的整数值
return be64toh(net64);
}
inline uint32_t networkToHost32(uint32_t net32)
{
return be32toh(net32);
}
inline uint16_t networkToHost16(uint16_t net16)
{
return be16toh(net16);
}
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/StringPiece.h
|
<gh_stars>1-10
#ifndef NLIB_STRINGPIECE_H
#define NLIB_STRINGPIECE_H
#include "header.h"
class StringArg
{
public:
StringArg(const char* str_)
: m_str(str_)
{
}
StringArg(const string& str_)
: m_str(str_.c_str())
{
}
const char* c_str() const
{
return m_str;
}
private:
const char* m_str;
};
class StringPiece
{
private:
const char* m_ptr;
int m_length;
public:
StringPiece()
: m_ptr(NULL), m_length(0)
{
}
StringPiece(const char* str_)
: m_ptr(str_)
{
m_length = strlen(m_ptr);
}
StringPiece(const unsigned char* str_)
{
m_ptr = (const char*)str_;
m_length = strlen(m_ptr);
}
StringPiece(const string& str_)
: m_ptr(str_.data()),
m_length((int)(str_.size()))
{
}
StringPiece(const char* offset_, int len_)
: m_ptr(offset_), m_length(len_)
{
}
const char* data() const
{
return m_ptr;
}
int size() const
{
return m_length;
}
bool empty() const
{
return m_length == 0;
}
const char* begin() const
{
return m_ptr;
}
const char* end() const
{
return m_ptr + m_length;
}
void clear()
{
m_ptr = NULL;
m_length = 0;
}
void set(const char* buffer_, int len_)
{
m_ptr = buffer_;
m_length = len_;
}
void set(const char* str_)
{
m_ptr = str_;
m_length = strlen(str_);
}
void set(const void* buffer_, int len_)
{
m_ptr = (const char*)(buffer_);
m_length = len_;
}
char operator[](int i) const
{
return m_ptr[i];
}
void remove_prefix(int n)
{
m_ptr += n;
m_length -= n;
}
void remove_suffix(int n)
{
m_length -= n;
}
bool operator==(const StringPiece& x) const
{
return ((m_length == x.m_length)
&& (memcmp(m_ptr, x.m_ptr, m_length) == 0));
}
bool operator!=(const StringPiece& x) const
{
return !(*this == x);
}
int compare(const StringPiece& x) const
{
int r = memcmp(
m_ptr,
x.m_ptr,
m_length < x.m_length ? m_length : x.m_length);
if (r == 0)
{
if (m_length < x.m_length)
r = -1;
else if (m_length > x.m_length)
r = +1;
}
return r;
}
string as_string() const
{
return string(data(), size());
}
void CopyToString(string* target) const
{
target->assign(m_ptr, m_length);
}
bool starts_with(const StringPiece& x) const
{
return ((m_length >= x.m_length) && (memcmp(m_ptr, x.m_ptr, x.m_length) == 0));
}
};
std::ostream& operator<<(
std::ostream& o,
const StringPiece& piece);
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/EventLoopThread.h
|
#ifndef NLIB_EVENTLOOPTHREAD_H
#define NLIB_EVENTLOOPTHREAD_H
#include "header.h"
#include "Condition.h"
#include "Mutex.h"
#include "Thread.h"
// 从一个类型得到新类型
// 1.继承
// 2.组合
class EventLoop;
class EventLoopThread
{
public:
typedef std::function<void(EventLoop*)>
ThreadInitCallback;
EventLoopThread(
const ThreadInitCallback& cb = ThreadInitCallback(),
const string& name = string());
~EventLoopThread();
EventLoop* startLoop();
private:
void threadFunc();
private:
bool m_bExiting;
Thread m_nThread;
MutexLock m_nMutex;
Condition m_nCond;
EventLoop* m_pLoop;
ThreadInitCallback m_nCallBack;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/EventLoop.h
|
#ifndef NLIB_EVENTLOOP_H
#define NLIB_EVENTLOOP_H
#include "header.h"
#include "CallBacks.h"
#include "TimerId.h"
#include "Mutex.h"
class Channel;
class Poller;
class TimerQueue;
class EventLoop
{
public:
typedef std::function<void()> Functor;
EventLoop();
~EventLoop();
void loop();
void quit();
TimeStamp pollReturnTime() const
{
return m_nPollReturnTime;
}
int64_t iteration() const
{
return m_nIteration;
}
void runInLoop(
Functor cb);
void queueInLoop(
Functor cb);
size_t queueSize() const;
TimerId runAt(
TimeStamp time,
TimerCallback cb);
TimerId runAfter(
double delay,
TimerCallback cb);
TimerId runEvery(
double interval,
TimerCallback cb);
void cancel(
TimerId timerId);
void wakeup();
void updateChannel(
Channel* channel);
void removeChannel(
Channel* channel);
bool hasChannel(
Channel* channel);
void assertInLoopThread()
{
if (!isInLoopThread())
{
abortNotInLoopThread();
}
}
bool isInLoopThread() const
{
return m_nThreadId == tid();
}
bool eventHandling() const
{
return m_bEventHandling;
}
// boost::any可用于保存任意类型
// boost::any::type()用于返回对象实际类型信息
// boost::any_cast<xxx>()
// 用于将一个boost::any对象强制转换为指定类型
void setContext(const boost::any& context)
{
m_nContext = context;
}
const boost::any& getContext() const
{
return m_nContext;
}
boost::any* getMutableContext()
{
return &m_nContext;
}
static EventLoop* getEventLoopOfCurrentThread();
private:
void abortNotInLoopThread();
void handleRead();
void doPendingFunctors();
void printActiveChannels() const;
typedef std::vector<Channel*> ChannelList;
private:
bool m_bLooping;
std::atomic<bool> m_nQuit;
bool m_bEventHandling;
bool m_bCallingPendingFunctors;
int64_t m_nIteration;
const pid_t m_nThreadId;
TimeStamp m_nPollReturnTime;
std::unique_ptr<Poller> m_pPoller;
std::unique_ptr<TimerQueue> m_pTimerQueue;
int m_nWakeupFd;
std::unique_ptr<Channel> m_pWakeupChannel;
boost::any m_nContext;
ChannelList m_nActiveChannels;
Channel* m_pCurrentActiveChannel;
std::vector<Functor> m_vecPendingFunctors;
mutable MutexLock m_nMutex;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoServer/MuduoApp/header.h
|
<filename>MuduoServer/MuduoApp/header.h
#ifndef MUDUO_APP_HEADER_H
#define MUDUO_APP_HEADER_H
#include "../MyMuduo/Tcp/lib.h"
#include "../MyMuduo/Tcp/lib.h"
#include "MySqlAgent/lib.h"
#include "DataStruct/lib.h"
#endif // HEADER_H
|
Fragrant-Yang/git-test-copy
|
MuduoServer/DataStruct/header.h
|
<filename>MuduoServer/DataStruct/header.h
#ifndef DATASTRUCT_HEADER_H
#define DATASTRUCT_HEADER_H
#include "Global/lib.h"
#endif // HEADER_H
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Tcp/TcpServer.h
|
<reponame>Fragrant-Yang/git-test-copy
#ifndef NLIB_TCPSERVER_H
#define NLIB_TCPSERVER_H
#include "../Lib/lib.h"
#include "TcpConnection.h"
#include "Acceptor.h"
class Acceptor;
class EventLoop;
class EventLoopThreadPool;
class TcpServer
{
public:
typedef std::function<void(EventLoop*)> ThreadInitCallback;
enum Option
{
s_nNoReusePort,
s_nReusePort,
};
TcpServer(
EventLoop* loop,
const InetAddress& listenAddr,
const string& nameArg,
Option option = s_nNoReusePort);
~TcpServer();
const string& ipPort() const
{
return m_strIpPort;
}
const string& name() const
{
return m_strName;
}
EventLoop* getLoop() const
{
return m_pLoop;
}
void setThreadNum(int numThreads);
void setThreadInitCallback(
const ThreadInitCallback& cb)
{
m_nThreadInitCallback = cb;
}
std::shared_ptr<EventLoopThreadPool> threadPool()
{
return m_pThreadPool;
}
void start();
void setConnectionCallback(
const ConnectionCallback& cb)
{
m_nConnectionCallback = cb;
}
void setMessageCallback(
const MessageCallback& cb)
{
m_nMessageCallback = cb;
}
void setWriteCompleteCallback(
const WriteCompleteCallback& cb)
{
m_nWriteCompleteCallback = cb;
}
private:
void newConnection(
int sockfd,
const InetAddress& peerAddr);
void removeConnection(
const TcpConnectionPtr& conn);
void removeConnectionInLoop(
const TcpConnectionPtr& conn);
private:
typedef std::map<string, TcpConnectionPtr> ConnectionMap;
EventLoop* m_pLoop;
const string m_strIpPort;
const string m_strName;
std::unique_ptr<Acceptor> m_pAcceptor;
std::shared_ptr<EventLoopThreadPool> m_pThreadPool;
ConnectionCallback m_nConnectionCallback;
MessageCallback m_nMessageCallback;
WriteCompleteCallback m_nWriteCompleteCallback;
ThreadInitCallback m_nThreadInitCallback;
AtomicInt32 m_nStarted;
int m_nNextConnId;
ConnectionMap m_nConnections;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Tcp/Acceptor.h
|
#ifndef NLIB_ACCEPTOR_H
#define NLIB_ACCEPTOR_H
#include "../Lib/lib.h"
class EventLoop;
class InetAddress;
class Acceptor
{
public:
typedef std::function<void (
int sockfd,
const InetAddress&)> NewConnectionCallback;
Acceptor(
EventLoop* loop,
const InetAddress& listenAddr,
bool reuseport);
~Acceptor();
void setNewConnectionCallback(const NewConnectionCallback& cb)
{
m_nNewConnectionCallback = cb;
}
bool listenning() const
{
return m_bListenning;
}
void listen();
private:
void handleRead();
EventLoop* m_pLoop;
Socket m_nAcceptSocket;
Channel m_nAcceptChannel;
NewConnectionCallback m_nNewConnectionCallback;
bool m_bListenning;
int m_nIdleFd;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoServer/DataStruct/datastruct.h
|
#ifndef DATA_STRUCT_DATASTRUCT_H
#define DATA_STRUCT_DATASTRUCT_H
#endif // DATASTRUCT_H
|
Fragrant-Yang/git-test-copy
|
MuduoClient/Global/header.h
|
#ifndef GLOBAL_HEADER_H
#define GLOBAL_HEADER_H
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include <iostream>
#include <bitset>
#include <time.h>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <math.h>
#include <vector>
#include <functional>
#include <exception>
#include <QObject>
#include <QWidget>
#include <QPoint>
#include <QPainter>
#include <QPen>
#include <QImage>
#include <QFile>
#include <QDir>
#include <QApplication>
#include <QLayout>
#include <QStackedLayout>
#include <QMainWindow>
#include <QStandardItemModel>
#include <QDebug>
#include <QMap>
#include <QThread>
#include <QSemaphore>
#include <QMutex>
#include <QMutexLocker>
#include <QDialog>
#endif // HEADER_H
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/ProcessInfo.h
|
#ifndef NLIB_PROCESSINFO_H
#define NLIB_PROCESSINFO_H
#include "header.h"
#include "StringPiece.h"
#include "TimeStamp.h"
pid_t pid();
string pidString();
uid_t uid();
string username();
uid_t euid();
TimeStamp startTime();
int clockTicksPerSecond();
int pageSize();
bool isDebugBuild();
string hostname();
string procname();
StringPiece procname(const string& stat);
string procStatus();
string procStat();
string threadStat();
string exePath();
int openedFiles();
int maxOpenFiles();
struct CpuTime
{
double userSeconds;
double systemSeconds;
CpuTime()
: userSeconds(0.0),
systemSeconds(0.0)
{ }
double total() const
{
return userSeconds
+ systemSeconds;
}
};
CpuTime cpuTime();
int numThreads();
std::vector<pid_t> threads();
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/Buffer.h
|
<reponame>Fragrant-Yang/git-test-copy
#ifndef NLIB_BUFFER_H
#define NLIB_BUFFER_H
#include "header.h"
#include "StringPiece.h"
#include "Endian.h"
#include "Logging.h"
// Buffer的设计:
// 1.容量动态变化
// 2.默认无锁/同步
// 3.锁定区+已经处理区+尚未处理区+可操作区
//
class Buffer
{
public:
static const size_t s_nCheapPrepend = 8;
static const size_t s_nInitialSize = 1024;
explicit Buffer(
size_t initialSize = s_nInitialSize)
: m_nBuffer(s_nCheapPrepend + initialSize),
m_nReaderIndex(s_nCheapPrepend),
m_nWriterIndex(s_nCheapPrepend)
{
assert(readableBytes() == 0);
assert(writableBytes() == initialSize);
assert(prependableBytes() == s_nCheapPrepend);
}
void swap(Buffer& rhs)
{
m_nBuffer.swap(rhs.m_nBuffer);
std::swap(m_nReaderIndex, rhs.m_nReaderIndex);
std::swap(m_nWriterIndex, rhs.m_nWriterIndex);
}
size_t readableBytes() const
{
return m_nWriterIndex - m_nReaderIndex;
}
size_t writableBytes() const
{
return m_nBuffer.size() - m_nWriterIndex;
}
size_t prependableBytes() const
{
return m_nReaderIndex;
}
const char* peek() const
{
return begin() + m_nReaderIndex;
}
// 从首个可读到首个可写范围区间内搜索s_nCRLF
const char* findCRLF() const
{
const char* crlf = std::search(
peek(),
beginWrite(),
s_nCRLF,
s_nCRLF+2);
return crlf == beginWrite() ? NULL : crlf;
}
// 指定一个首个可读到首个可写中间某字节位置为起始查找位置
const char* findCRLF(
const char* start) const
{
assert(peek() <= start);
assert(start <= beginWrite());
const char* crlf = std::search(
start,
beginWrite(),
s_nCRLF,
s_nCRLF+2);
return crlf == beginWrite() ? NULL : crlf;
}
// 从首个可读位置开始,针对可读部分,查找\n
const char* findEOL() const
{
const void* eol = memchr(
peek(),
'\n',
readableBytes());
return static_cast<const char*>(eol);
}
// 从指定的首个可读位置到首个可写位置间某个位置,针对可读部分
const char* findEOL(
const char* start) const
{
assert(peek() <= start);
assert(start <= beginWrite());
const void* eol = memchr(
start,
'\n',
beginWrite() - start);
return static_cast<const char*>(eol);
}
// 使可读部分指定长度标记为已经读取
void retrieve(size_t len)
{
assert(len <= readableBytes());
if (len < readableBytes())
{
m_nReaderIndex += len;
}
else
{
retrieveAll();
}
}
// 指定首个可读到首个可写之间某个字节为中止字节
// 将该中止字节前可读部分,全部标记为已经读取.
void retrieveUntil(const char* end)
{
assert(peek() <= end);
assert(end <= beginWrite());
retrieve(end - peek());
}
void retrieveInt64()
{
retrieve(sizeof(int64_t));
}
void retrieveInt32()
{
retrieve(sizeof(int32_t));
}
void retrieveInt16()
{
retrieve(sizeof(int16_t));
}
void retrieveInt8()
{
retrieve(sizeof(int8_t));
}
void retrieveAll()
{
m_nReaderIndex = s_nCheapPrepend;
m_nWriterIndex = s_nCheapPrepend;
}
// 将可读部分全部读取
// 读取内容以一个string对象返回
string retrieveAllAsString()
{
return retrieveAsString(readableBytes());
}
string retrieveAsString(size_t len)
{
assert(len <= readableBytes());
string result(peek(), len);
retrieve(len);
return result;
}
// 将可读部分全部读取
// 读取内容以一个StringPiece对象返回
StringPiece toStringPiece() const
{
return StringPiece(
peek(),
static_cast<int>(readableBytes()));
}
void append(const StringPiece& str)
{
append(
str.data(),
str.size());
}
void append(
const char* /*restrict*/ data,
size_t len)
{
ensureWritableBytes(len);
std::copy(
data,
data+len,
beginWrite());
hasWritten(len);
}
// 往缓冲区写入一个指定长度对象
void append(
const void* data,
size_t len)
{
append(static_cast<const char*>(data), len);
}
void ensureWritableBytes(size_t len)
{
// 如果缓冲区可写字节数少于要求数量
if (writableBytes() < len)
{
// 想办法扩大缓冲区可写字节数量
makeSpace(len);
}
assert(writableBytes() >= len);
}
char* beginWrite()
{
return begin() + m_nWriterIndex;
}
const char* beginWrite() const
{
return begin() + m_nWriterIndex;
}
// 将可写部分指定长度内容标记为已经写入
void hasWritten(size_t len)
{
assert(len <= writableBytes());
m_nWriterIndex += len;
}
// 撤销对最近某个指定字节长度的写入
// 将首个可写字节前指定长度部分标记为未写入
// 更新首个可写字节位置索引
void unwrite(size_t len)
{
assert(len <= readableBytes());
m_nWriterIndex -= len;
}
void appendInt64(int64_t x)
{
int64_t be64 = hostToNetwork64(x);
append(&be64, sizeof be64);
}
void appendInt32(int32_t x)
{
int32_t be32 = hostToNetwork32(x);
append(&be32, sizeof be32);
}
void appendInt16(int16_t x)
{
int16_t be16 = hostToNetwork16(x);
append(&be16, sizeof be16);
}
void appendInt8(int8_t x)
{
append(&x, sizeof x);
}
int64_t readInt64()
{
int64_t result = peekInt64();
retrieveInt64();
return result;
}
int32_t readInt32()
{
int32_t result = peekInt32();
retrieveInt32();
return result;
}
int16_t readInt16()
{
int16_t result = peekInt16();
retrieveInt16();
return result;
}
int8_t readInt8()
{
int8_t result = peekInt8();
retrieveInt8();
return result;
}
// 从缓冲区读出一个Int64对象
// 但读出部分未被标记为已经读取
int64_t peekInt64() const
{
assert(readableBytes() >= sizeof(int64_t));
int64_t be64 = 0;
::memcpy(
&be64,
peek(),
sizeof be64);
return networkToHost64(be64);
}
int32_t peekInt32() const
{
assert(readableBytes() >= sizeof(int32_t));
int32_t be32 = 0;
::memcpy(&be32, peek(), sizeof be32);
return networkToHost32(be32);
}
int16_t peekInt16() const
{
assert(readableBytes() >= sizeof(int16_t));
int16_t be16 = 0;
::memcpy(&be16, peek(), sizeof be16);
return networkToHost16(be16);
}
int8_t peekInt8() const
{
assert(readableBytes() >= sizeof(int8_t));
int8_t x = *peek();
return x;
}
void prependInt64(int64_t x)
{
int64_t be64 = hostToNetwork64(x);
prepend(&be64, sizeof be64);
}
void prependInt32(int32_t x)
{
int32_t be32 = hostToNetwork32(x);
prepend(&be32, sizeof be32);
}
void prependInt16(int16_t x)
{
int16_t be16 = hostToNetwork16(x);
prepend(&be16, sizeof be16);
}
void prependInt8(int8_t x)
{
prepend(&x, sizeof x);
}
// 在已经读取区间内末尾len大小重新设置为未被读取
// 并将此部分用一个指定长度为len的对象填充
// 更新首个可读字节位置索引
void prepend(
const void* /*restrict*/ data,
size_t len)
{
assert(len <= prependableBytes());
m_nReaderIndex -= len;
const char* d =
static_cast<const char*>(data);
// 往可读位置放入指定len大小的由
// data指向的对象内容
std::copy(
d,
d+len,
begin()+m_nReaderIndex);
}
void shrink(size_t reserve)
{
Buffer other;
other.ensureWritableBytes(readableBytes()+reserve);
other.append(toStringPiece());
swap(other);
}
size_t internalCapacity() const
{
return m_nBuffer.capacity();
}
ssize_t readFd(
int fd,
int* savedErrno);
private:
char* begin()
{
return &*m_nBuffer.begin();
}
const char* begin() const
{
return &*m_nBuffer.begin();
}
// 空间扩展的方法:
// 一个是将已经读取部分腾出来
// 一个是分配一个更大的缓冲区
// 空间扩展
// 缓冲区
// 预留部分+已经读取部分+可读取部分+可写入部分
void makeSpace(size_t len)
{
// 可写部分+已经读取部分
if (writableBytes() + prependableBytes() <
len + s_nCheapPrepend)
{
// 申请新空间
// 保持已经读取部分+可读部分不变下
// 让可写部分长度变为len
m_nBuffer.resize(m_nWriterIndex+len);
}
else
{
// 去掉预留部分来腾出额外可写空间
assert(s_nCheapPrepend < m_nReaderIndex);
// 可读部分
size_t readable = readableBytes();
// 将可读部分往已经读取部分挪动
// 这样空出来的部分将变为可写
// 进而扩大了可写空间
// 前面s_nCheapPrepend一般固定预留
std::copy(begin()+m_nReaderIndex,
begin()+m_nWriterIndex,
begin()+s_nCheapPrepend);
// 更新首个可读字节位置索引
m_nReaderIndex = s_nCheapPrepend;
// 更新首个可写字节位置索引
m_nWriterIndex = m_nReaderIndex + readable;
assert(readable == readableBytes());
}
}
private:
// 此Buffer对象自身不提供多线程互斥/同步
// 需要时,在多线程共享同一Buffer对象访问时自行添加
std::vector<char> m_nBuffer;
size_t m_nReaderIndex;
size_t m_nWriterIndex;
static const char s_nCRLF[];
};
#endif
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/LogFile.h
|
#ifndef NLIB_LOGFILE_H
#define NLIB_LOGFILE_H
#include "Mutex.h"
class AppendFile;
class LogFile
{
public:
// 单个日志文件不能太大
// 一段时间后自动将缓存刷新到磁盘文件
// 每天一个日志
LogFile(
const string& basename,
off_t rollSize,
bool threadSafe = true,
int flushInterval = 3,
int checkEveryN = 1024);
~LogFile();
void append(
const char* logline,
int len);
void flush();
bool rollFile();
private:
void append_unlocked(
const char* logline,
int len);
static string getLogFileName(
const string& basename,
time_t* now);
private:
const string m_strBaseName;
const off_t m_nRollSize;
const int m_nFlushInterval;
const int m_nCheckEveryN;
int m_nCount;
std::unique_ptr<MutexLock> m_nMutex;
time_t m_nStartOfPeriod;
time_t m_nLastRoll;
time_t m_nLastFlush;
std::unique_ptr<AppendFile> m_nFile;
const static int s_nRollPerSeconds = 60*60*24;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoServer/MySqlAgent/mysqlagent.h
|
<gh_stars>1-10
// Author : XuBenHao
// Version : 1.0.0
// Mail : <EMAIL>
// Copyright : XuBenHao 2020 - 2030
//
#ifndef MYSQL_AGENT_MYSQLAGENT_H
#define MYSQL_AGENT_MYSQLAGENT_H
#include "header.h"
class MySqlAgent
{
public:
public:
MySqlAgent(
char* pStrHost_,
int nHostLen_,
char* pStrUser_,
int nUserLen_,
char* pStrPassword_,
int nPasswordLen_);
void Connect();
~MySqlAgent();
// no use parameter bind to set sql and get result
// for no parameter bind and no returning result sql
bool Query(
char* pContent_);
bool StoreResult(MYSQL_RES** ppRes_);
void FieldSeek(MYSQL_RES* pRes_, int nIndex_);
int NumFields(MYSQL_RES* pRes_);
MYSQL_FIELD* FetchField(MYSQL_RES* pRes_);
MYSQL_ROW FetchRow(MYSQL_RES* pRes_);
int NumRows(MYSQL_RES* pRes_);
void FreeResult(MYSQL_RES* pRes_);
// use parameter bind to set parameter and get result
// 1.prepare
// 2.bind parameter
// 3.execute
// 4.bind_result
// 5.store result
// 6.fetch
// 7.free result
bool Prepare(
char* pContent_,
int nLength_);
bool BindParameter(MYSQL_BIND* pBinds_);
bool Execute();
bool BindResult(MYSQL_BIND* pBinds_);
bool StoreResult();
int Fetch();
void FreeResult();
private:
char m_strHost[100];
char m_strUser[100];
char m_strPassword[100];
MYSQL *m_pConnection;
MYSQL_STMT *m_pStmt;
};
#endif // MYSQLAGENT_H
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Tcp/lib.h
|
#ifndef TCP_LIB_H
#define TCP_LIB_H
#include "Acceptor.h"
#include "Connector.h"
#include "TcpClient.h"
#include "TcpConnection.h"
#include "TcpServer.h"
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoClient/Ui/header.h
|
#ifndef APP_UI_HEADER_H
#define APP_UI_HEADER_H
#include "Global/lib.h"
#include "DataStruct/lib.h"
#include "MuduoApp/lib.h"
#endif // HEADER_H
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/Atomic.h
|
<filename>MyMuduo/Lib/Atomic.h
#ifndef NLIB_ATOMIC_H
#define NLIB_ATOMIC_H
#include "header.h"
template<typename T>
class AtomicIntegerT
{
public:
AtomicIntegerT()
: m_nValue(0)
{
}
T get()
{
return __sync_val_compare_and_swap(&m_nValue, 0, 0);
}
T getAndAdd(T x)
{
return __sync_fetch_and_add(&m_nValue, x);
}
T addAndGet(T x)
{
return getAndAdd(x) + x;
}
T incrementAndGet()
{
return addAndGet(1);
}
T decrementAndGet()
{
return addAndGet(-1);
}
void add(T x)
{
getAndAdd(x);
}
void increment()
{
incrementAndGet();
}
void decrement()
{
decrementAndGet();
}
T getAndSet(T newValue)
{
return __sync_lock_test_and_set(&m_nValue, newValue);
}
private:
volatile T m_nValue;
};
typedef AtomicIntegerT<int32_t> AtomicInt32;
typedef AtomicIntegerT<int64_t> AtomicInt64;
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoServer/Application/lib.h
|
#ifndef APPLICATION_LIB_H
#define APPLICATION_LIB_H
#include "main.h"
#endif // LIB_H
|
Fragrant-Yang/git-test-copy
|
MuduoServer/DataStruct/lib.h
|
#ifndef DATASTRUCT__LIB_H
#define DATASTRUCT__LIB_H
#include "dynarray.h"
#include "dynqueue.h"
#include "fixqueue.h"
#include "doublelist.h"
#include "KeyAllocator.h"
#include "RedBlackTree.h"
#endif // LIB_H
|
Fragrant-Yang/git-test-copy
|
MyMuduo/Lib/TimerId.h
|
#ifndef LIB_TIMERID_H
#define LIB_TIMERID_H
#include "CallBacks.h"
class Timer;
// 标识一个定时器
class TimerId
{
public:
TimerId()
: m_pTimer(NULL),
m_nSequence(0)
{
}
TimerId(Timer* timer, int64_t seq)
: m_pTimer(timer),
m_nSequence(seq)
{
}
friend class TimerQueue;
private:
Timer* m_pTimer;
int64_t m_nSequence;
};
#endif
|
Fragrant-Yang/git-test-copy
|
MuduoClient/MuduoApp/muduoclient.h
|
<filename>MuduoClient/MuduoApp/muduoclient.h
// Author : XuBenHao
// Version : 1.0.0
// Mail : <EMAIL>
// Copyright : XuBenHao 2020 - 2030
//
#ifndef MUDUO_APP_MUDUOCLIENT_H
#define MUDUO_APP_MUDUOCLIENT_H
#include "header.h"
#include "codec.h"
class Message
{
public:
Message()
{
m_bDirection = true;
}
~Message()
{
}
public:
QByteArray m_nContent;
bool m_bDirection;
TimeStamp m_nTimeStamp;
};
void LogOutput(const char* msg, int len);
class MuduoClient
{
public:
// for client to server direction
enum MessageType
{
REGISTER = 0,
LOGIN = 1,
ADD = 2,
UPDATE_FRIEND_LIST = 3,
OFF_LINE = 4,
NEED_TO_PROCESS_USER_LIST = 5,
CHAT = 6,
GET_NEED_TO_PROCESS_MESSAGES = 7,
};
// for server to client direction
enum ResMessageType
{
REGISTER_RES = 0,
LOGIN_RES = 1,
ADD_RES = 2,
UPDATE_FRIEND_LIST_RES = 3,
NEED_TO_PROCESS_USER_LIST_RES = 4,
CHAT_RES = 5,
NEW_MESSAGE_NOTIFICATION = 6,
GET_NEED_TO_PROCESS_MESSAGES_RES = 7,
};
public:
// For Error
void setErrorCallback(std::function<void(const TcpConnectionPtr&)> nFun_)
{
if(m_nConnection)
{
m_nConnection.get()->setErrCallback(nFun_);
}
}
private:
std::function<void()> m_nErrorCallback;
public:
// For Register
bool sendRegisterMessage(const QString& strUserId_, const QString& strPassword_);
void setRegisterCallback(std::function<void(int nType_)> nFun_)
{
m_nRegisterCallback = nFun_;
}
private:
bool PackRegisterMessage(const QString& strUserId_, const QString& strPassword_, Buffer& nBuf_);
private:
std::function<void(int nType_)> m_nRegisterCallback;
public:
// For get-need-to-process-messages
bool sendGetNeedToProcessMessagesMessage(const QString& strSourceUserId_, const QString& strDestUserId_);
void setGetNeedToProcessMessagesCallback(std::function<void(const NDataStruct::DynArray<Message>&)> nFun_)
{
m_nGetNeedToProcessMessagesCallback = nFun_;
}
private:
bool PackGetNeedToProcessMessagesMessage(const QString& strUserId_, const QString& strPassword_, Buffer& nBuf_);
private:
std::function<void(const NDataStruct::DynArray<Message>&)> m_nGetNeedToProcessMessagesCallback;
public:
// For Chat
bool sendChatMessage(
const QString& nByteSender_,
const QString& nByteReceiver,
const QString& strChatText_);
void setChatCallback(std::function<void(int nType_)> nFun_)
{
m_nChatCallback = nFun_;
}
private:
bool PackChatMessage(
const QString& nByteSender_,
const QString& nByteReceiver,
const QString& strChatText_,
Buffer& nBuf_);
private:
std::function<void(int nType_)> m_nChatCallback;
public:
// for update friend list
bool sendUpdateFriendListMessage(const QString& strUserId_);
void setUpdateFriendListCallback(std::function<void(const NDataStruct::DynArray<QByteArray>&)> nFun_)
{
m_nUpdateFriendListCallback = nFun_;
}
private:
bool PackUpdateFriendListMessage(const QString& strUserId_, Buffer& nBuf_);
private:
std::function<void(const NDataStruct::DynArray<QByteArray>&)> m_nUpdateFriendListCallback;
public:
// for need-to-process-user list
bool sendNeedToProcessUserListMessage(const QString& strUserId_);
void setNeedToProcessUserListCallback(std::function<void(const NDataStruct::DynArray<QByteArray>&)> nFun_)
{
m_nNeedToProcessUserListCallback = nFun_;
}
private:
bool PackNeedToProcessUserListMessage(const QString& strUserId_, Buffer& nBuf_);
private:
std::function<void(const NDataStruct::DynArray<QByteArray>&)> m_nNeedToProcessUserListCallback;
public:
void setNewMessageCallback(std::function<void(const QByteArray&)> nFun_)
{
m_nNewMessageCallback = nFun_;
}
private:
std::function<void(const QByteArray&)> m_nNewMessageCallback;
public:
// for off-line notification
bool sendOffLineMessage(const QString& strUserId_, const TimeStamp& nTimeStamp_);
private:
bool PackOffLineMessage(const QString& strUserId_, const TimeStamp& nTimeStamp_, Buffer& nBuf_);
public:
// For Login
bool sendLoginMessage(const QString& strUserId_, const QString& strPassword_);
void setLoginCallback(std::function<void(int nType_, TimeStamp nTimeStamp_)> nFun_)
{
m_nLoginCallback = nFun_;
}
private:
bool PackLoginMessage(const QString& strUserId_, const QString& strPassword_, Buffer& nBuf_);
private:
std::function<void(int nType_, TimeStamp nTimeStamp_)> m_nLoginCallback;
public:
// For Add
bool sendAddMessage(const QString& strMasterUserId_, const QString& strUserId_);
void setAddCallback(std::function<void(int nType_)> nFun_)
{
m_nAddCallback = nFun_;
}
private:
bool PackAddMessage(const QString& strMasterUserId_, const QString& strUserId_, Buffer& nBuf_);
private:
std::function<void(int nType_)> m_nAddCallback;
public:
static MuduoClient* instance(EventLoop* loop, const InetAddress& serverAddr);
void connect();
void disconnect();
//void write(const StringPiece& message);
private:
void onConnection(const TcpConnectionPtr& conn);
void onStringMessage(
const TcpConnectionPtr&,
const string& message,
TimeStamp);
void onMessage(
const TcpConnectionPtr& conn,
Buffer* buf,
TimeStamp receiveTime);
void onStringMessage(
const TcpConnectionPtr&,
char* strMessage_,
int nLength_,
TimeStamp);
private:
MuduoClient(EventLoop* loop, const InetAddress& serverAddr);
private:
static MuduoClient* __instance;
private:
TcpClient m_nClient;
//LengthHeaderCodec m_nCodec;
MutexLock m_nMutex;
TcpConnectionPtr m_nConnection;
};
#endif // MUDUOCLIENT_H
|
lxkain/multi-isoreg
|
mir/mir_c.h
|
double isotonic_regression(double const* const, double const* const, unsigned, int);
|
lxkain/multi-isoreg
|
mir/mir_c.c
|
#include "mir_c.h"
double isotonic_regression(double const* const inp, double const* const out, unsigned n, int direction) {
unsigned j, k, i;
char pooled;
double const* pinp;
double* pout;
double err = 0;
if (n > 1) {
pinp = inp;
pout = out;
for (i = 0; i < n; i++)
*pout++ = *pinp++ * direction;
n -= 1;
while (1) {
pooled = i = 0;
while (i < n) {
k = i;
while ((k < n) & (out[k] >= out[k + 1]))
k++;
pout = &out[i];
if (*pout != out[k]) {
double acc = 0.0;
for(j = i; j < k + 1; j++)
acc += *pout++;
acc /= k - i + 1;
for(j = i; j < k + 1; j++)
*--pout = acc;
pooled = 1;
}
i = k + 1;
}
if (!pooled)
break;
}
}
pinp = inp;
pout = out;
for (i = 0; i < n; i++) {
*pout *= direction;
err += (*pinp - *pout) * (*pinp++ - *pout++);
}
return err;
}
|
ranjak/opengl-sample
|
src/config.c
|
<gh_stars>0
#include "config.h"
#include "log.h"
#include "controls.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
static char* configFileName = "config.cfg";
static int ConfigLog = 0;
Eg_configSection Sections[1];
int sectionCount = 1;
static bool init = false;
static int readEntries(Eg_configSection*);
int writeCfgSection(const Eg_configSection* conf, FILE*);
void eg_loadConfig()
{
ConfigLog = eg_createLog("config.log");
if(ConfigLog == 0)
fprintf(stderr, "[Config] Could not create config log.\n");
eg_getControlCfgDesc(&Sections[0]);
eg_readConfigFile(Sections, 1);
init = true;
}
/*
* Lecture du fichier de configuration
* Remplit la liste des configs.
* Cette fonction devrait être appelée au début du programme,
* chaque section de configuration ainsi générée étant ensuite
* demandée par les modules en ayant besoin.
* RETOURNE:
Nombre de sections récupérées
*/
int eg_readConfigFile(Eg_configSection* cfg, int numSections)
{
int sectionCount = 0, i;
char currentName[EG_MAX_IDENT_LG];
if(!lex_openFile(configFileName, ConfigLog))
{
fprintf(stderr, "[Config] Could not open config file %s. Default settings will be used.\n", configFileName);
return 0;
}
//Lecture du fichier : 1 passage dans le while = 1 section
while(lex_EtatOK)
{
lex_readWhites();
//On doit trouver un début de section bien formé.
while(lex_CurrentChar != '[' && lex_EtatOK)
{
//erreur : test à la ligne suivante.
eg_strToLog(ConfigLog, "[Config] Error at line %d, expected section entry.", lex_LineCount);
lex_errorLoop();
}
//soit on a trouvé une section, soit on est à EOF !
if(lex_EtatOK)
{
lex_readChar();
if(lex_readIdent(currentName) && lex_CurrentChar==']')
{
//passer le ']'
lex_readChar();
//recherche d'une section de nom correspondant
for(i=0 ; i<numSections ; i++)
if(strcmp(cfg[i].name, currentName) == 0) break;
if(i < numSections)
{
//il faut un saut de ligne après le nom de section
if(!lex_readToNewline() && lex_EtatOK)
{
eg_strToLog(ConfigLog, "[Config] Error at line %d, Section entry must be followed by newline", lex_LineCount);
lex_errorLoop();
}
//récup des paramètres de la section
if(readEntries(&cfg[i]) > 0)
sectionCount++;
else
eg_strToLog(ConfigLog, "[Config] Section [%s] held no valid value.", currentName);
}
else
{
eg_strToLog(ConfigLog, "[Config] Line %d : unknown section : %s.", lex_LineCount, currentName);
lex_errorLoop();
}
}
else
{
eg_strToLog(ConfigLog, "[Config] Line %d : error in section name format", lex_LineCount);
lex_errorLoop();
}
}
else
eg_strToLog(ConfigLog, "[Config] unexpected end of file");
}
eg_strToLog(ConfigLog, "[Config] End of file, loaded %d valid sections.\n", sectionCount);
lex_closeFile();
return sectionCount;
}
int readEntries(Eg_configSection* cfg)
{
char entryLabel[EG_MAX_IDENT_LG];
int i;
int entryCount = 0;
do
{
if(!lex_readWhites())
continue;
//Lecture d'un label d'entrée :
//(blancs)label(blancs)=(blancs)valeur(blancs)\n
//....
if(!lex_readIdent(entryLabel))
{
eg_strToLog(ConfigLog, "[Config] Error at line %d : invalid parameter label.", lex_LineCount);
lex_errorLoop();
continue;
}
lex_readWhites();
if(lex_CurrentChar != '=')
{
eg_strToLog(ConfigLog, "[Config] Error at line %d : expected '=', read '%c'.", lex_LineCount, lex_CurrentChar);
lex_errorLoop();
continue;
}
//On est arrivé à label=
//parcours des descripteurs de paramètres à la recherche du label
lex_readChar();
i = 0;
while(i < cfg->paramCount
&& strcmp(cfg->entries[i].label, entryLabel) != 0)
i++;
if(i == cfg->paramCount)
{
eg_strToLog(ConfigLog, "[Config] Error at line %d : no parameter %s in section %s.", lex_LineCount, entryLabel, cfg->name);
lex_errorLoop();
continue;
}
//Récupération de la valeur
lex_readWhites();
if(cfg->entries[i].valueFromStream(&cfg->entries[i]))
entryCount++;
else
{
eg_strToLog(ConfigLog, "[Config] Error at line %d : incorrect value for parameter %s.", lex_LineCount, entryLabel);
lex_errorLoop();
continue;
}
//1 entrée max par ligne
if(!lex_readToNewline() && lex_EtatOK)
{
eg_strToLog(ConfigLog, "[Config] Error at line %d : unexpected characters found after parameter affectation.", lex_LineCount);
lex_errorLoop();
}
lex_readWhites();
} while(lex_CurrentChar != '[' && lex_EtatOK);
//fin de lecture de la section
cfg->wasRead = 1;
eg_strToLog(ConfigLog, "[Config] End of section %s, loaded %d parameter(s) out of %d.", cfg->name, entryCount, cfg->paramCount);
return entryCount;
}
void eg_writeConfig()
{
int i;
if(init == false)
{
fprintf(stderr, "[Config] Warning : configuration was not initialized. Cannot save config file.\n");
return;
}
FILE* cfg = fopen(configFileName, "w");
if(cfg == NULL)
{
eg_strToLog(ConfigLog, "[Config] Could not open config file for writing. Changes in options will not be saved.");
return;
}
for(i=0 ; i < sectionCount ; i++)
writeCfgSection(&Sections[i], cfg);
eg_strToLog(ConfigLog, "[Config] Wrote cofiguration to file %s.\n", configFileName);
fclose(cfg);
}
int writeCfgSection(const Eg_configSection* conf, FILE* stream)
{
int i;
Eg_cfgEntry* entries = conf->entries;
//début section
fprintf(stream, "[%s]\n\n", conf->name);
//écriture de chaque couple paramètre=valeur
for(i=0 ; i<conf->paramCount ; i++)
{
fprintf(stream,
"%s = %s\n", entries[i].label, entries[i].valToStr(&entries[i]));
}
fputc('\n', stream);
return 0;
}
bool cfg_setInt(Eg_cfgEntry* entry, void* newval)
{
if(newval == NULL)
{
fprintf(stderr, "[Config] Warning : tried to set NULL value for parameter %s", entry->label);
return false;
}
if(entry->min_val != NULL && *(int*)newval < *(int*)entry->min_val)
{
eg_strToLog(ConfigLog, "[Config] Error : value %d out of bounds for parameter %s, "\
"expects a value of at least %d", *(int*)newval, entry->label, *(int*)entry->min_val);
return 0;
}
if(entry->max_val != NULL && *(int*)newval > *(int*)entry->max_val)
{
eg_strToLog(ConfigLog, "[Config] Error : read value %d out of bounds for parameter %s, "\
"expects a value of at most %d", *(int*)newval, entry->label, *(int*)entry->max_val);
return 0;
}
//allouer la mémoire si elle ne l'est pas !
if(entry->alloc == EG_NOT_ALLOCED)
{
entry->value = malloc(sizeof(int));
entry->alloc = EG_DYN_ALLOCED;
}
//on a passé tous les tests, affectation !
*(int*)entry->value = *(int*)newval;
return 1;
}
bool cfg_setFloat(Eg_cfgEntry* entry, void* newval)
{
if(newval == NULL)
{
fprintf(stderr, "[Config] Warning : tried to set NULL value for parameter %s", entry->label);
return false;
}
if(entry->min_val != NULL && *(float*)newval < *(float*)entry->min_val)
{
eg_strToLog(ConfigLog, "[Config] Error : value %f out of bounds for parameter %s, "\
"expects a value of at least %f", *(float*)newval, entry->label, *(float*)entry->min_val);
return false;
}
if(entry->max_val != NULL && *(float*)newval > *(float*)entry->max_val)
{
eg_strToLog(ConfigLog, "[Config] Error : value %f out of bounds for parameter %s, "\
"expects a value of at most %f", *(float*)newval, entry->label, *(float*)entry->max_val);
return false;
}
//allouer la mémoire si elle ne l'est pas !
if(entry->alloc == EG_NOT_ALLOCED)
{
entry->value = malloc(sizeof(float));
entry->alloc = EG_DYN_ALLOCED;
}
*(float*)entry->value = *(float*)newval;
return true;
}
bool cfg_setString(Eg_cfgEntry* entry, void* newval)
{
if(newval == NULL)
{
fprintf(stderr, "[Config] Warning : tried to set NULL value for parameter %s", entry->label);
return false;
}
int size = strlen((char*)newval);
//min et max sont ici des entiers restreignant la taille de la chaîne.
if(entry->min_val != NULL && size < *(int*)entry->min_val)
{
eg_strToLog(ConfigLog, "[Config] Error : string : \n%s\n is too short for parameter %s, "\
"expects a string of at least %d characters", (char*)newval, entry->label, *(int*)entry->min_val);
return false;
}
if(entry->max_val != NULL && size > *(int*)entry->max_val)
{
eg_strToLog(ConfigLog, "[Config] Error : string : \n%s\n is too long for parameter %s, "\
"expects a string of at most %d characters", (char*)newval, entry->label, *(int*)entry->max_val);
return false;
}
//s'il y avait déjà une chaîne allouée dynamiquement, on la libère.
if(entry->alloc == EG_DYN_ALLOCED)
free(entry->value);
entry->value = malloc(sizeof(char)*(size+1));
memcpy(entry->value, newval, size+1);
entry->alloc = EG_DYN_ALLOCED;
return true;
}
bool cfg_setBool(Eg_cfgEntry* entry, void* newval)
{
if(newval == NULL)
{
fprintf(stderr, "[Config] Warning : tried to set NULL value for parameter %s", entry->label);
return false;
}
if(*(bool*)newval != true && *(bool*)newval != false)
{
fprintf(stderr, "[Config] Warning : tried to affect a non-bool value to bool parameter %s", entry->label);
return false;
}
if(entry->alloc == EG_NOT_ALLOCED)
{
entry->value = malloc(sizeof(bool));
entry->alloc = EG_DYN_ALLOCED;
}
*(bool*)entry->value = *(bool*)newval;
return true;
}
bool cfg_readInt(Eg_cfgEntry* entry)
{
int temp;
if(!lex_readInt(&temp))
return 0;
if(entry->setValue(entry, &temp))
return true;
else
return false;
}
bool cfg_readFloat(Eg_cfgEntry* entry)
{
float temp;
if(!lex_readFloat(&temp))
return false;
if(entry->setValue(entry, &temp))
return true;
else
return false;
}
bool cfg_readString(Eg_cfgEntry* entry)
{
char* temp;
bool res;
if(lex_readString(&temp) < 0)
return false;
if(entry->setValue(entry, &temp))
res = true;
else
res = false;
free(temp);
return res;
}
bool cfg_readBool(Eg_cfgEntry* entry)
{
bool temp;
if(!lex_readBool(&temp))
return false;
if(entry->setValue(entry, &temp))
return true;
else
return false;
}
|
ranjak/opengl-sample
|
src/main.c
|
#include "scene.h"
#include "config.h"
int main(int argc, char* argv[])
{
eg_loadConfig();
Scene* scene = scene_create("Ma scène", 600, 600);
if(scene == NULL)
{
fprintf(stderr, "Erreur : impossible de créer la scène.\n");
return 1;
}
printf("Version : %s\n", glGetString(GL_VERSION));
//boucle ppale
scene_runMainLoop(scene);
//fin du programme
eg_writeConfig();
scene_destroy(scene);
return 0;
}
|
ranjak/opengl-sample
|
src/log.c
|
<gh_stars>0
#include "log.h"
#include <stdio.h>
#include <stdlib.h>
/*Liste des logs ouverts*/
typedef struct log {
FILE* lf;
struct log* next;
}logList;
static logList *logs = NULL,
**nextLog = &logs;
/*Nombre de logs ouverts*/
static int logCount = 0;
int eg_createLog(char* name)
{
logList* newLog = malloc(sizeof(logList));
if(newLog == NULL)
{
fprintf(stderr, "Log : Erreur : impossible d'allouer de la mémoire\n");
return 0;
}
newLog->lf = fopen(name, "w");
if(newLog->lf == NULL)
{
fprintf(stderr, "Log : Erreur : impossible de créer le fichier %s\n", name);
return 0;
}
//En-tête du log
fprintf(newLog->lf, "[Log : %s]\n\n", name);
newLog->next = NULL;
//ajout du log dans la liste
*nextLog = newLog;
logCount++;
nextLog = &(newLog->next);
return logCount;
}
int eg_bufToLog(int logId, char* data, size_t nbBytes)
{
if(logId <= 0 || logCount < logId)
{
fprintf(stderr, "Log : Erreur : le log %d n'existe pas\n", logId);
return -1;
}
//récupération du log d'ID logId
logList* p = logs;
int i = 1;
while(i < logId)
{
i++;
p = p->next;
}
//écriture dans le log récupéré
if(fwrite(data, sizeof(char), nbBytes, p->lf) != nbBytes)
{
fprintf(stderr, "Log : Erreur : toutes les données n'ont pas pu être écrites dans le log %d\n", logId);
return -1;
}
fputc('\n', p->lf);
return 0;
}
int eg_strToLog(int logId, char* fmt, ...)
{
if(logId <= 0 || logCount < logId)
{
fprintf(stderr, "Log : Erreur : le log %d n'existe pas\n", logId);
return -1;
}
//récupération du log d'ID logId
logList* p = logs;
int i = 1;
while(i < logId)
{
i++;
p = p->next;
}
//écriture de la chaine
va_list fmt_args;
va_start(fmt_args, fmt);
if(vfprintf(p->lf, fmt, fmt_args) < 0)
{
fprintf(stderr, "Log : Erreur lors de l'écriture d'une chaîne dans le log %d\n", logId);
return -1;
}
va_end(fmt_args);
fputc('\n', p->lf);
return 0;
}
int eg_closeLog(int logId)
{
if(logId <= 0 || logCount < logId)
{
fprintf(stderr, "Log : Erreur : le log %d n'existe pas\n", logId);
return -1;
}
//variables de parcours de la liste
logList* p = logs;
FILE* pf = NULL;
//cas du premier élément
if(logId == 1)
{
pf = logs->lf;
logs = logs->next;
free(p);
if(logCount == 1)
nextLog = &logs;
}
else
{
//se positionner sur le log d'avant logId
int i = 1;
while(i < logId-1)
{
i++;
p = p->next;
}
logList* q = p->next;
pf = q->lf;
p->next = q->next;
free(q);
if(logId == logCount)
nextLog = &(p->next);
}
fclose(pf);
logCount--;
return 0;
}
int eg_closeAllLogs()
{
if(logCount == 0)
{
fprintf(stderr, "Log : Warning : aucun log à fermer\n");
return -1;
}
logList *curr = logs, *prec = NULL;
while(curr != NULL)
{
fclose(curr->lf);
prec = curr;
curr = curr->next;
free(prec);
}
logs = NULL;
nextLog = &logs;
return 0;
}
|
ranjak/opengl-sample
|
include/lexutil.h
|
#ifndef LEXUTIL_H
#define LEXUTIL_H
#include <stdbool.h>
#define EG_MAX_IDENT_LG 48
/*
* Analyseur lexical, conçu pour l'analyse de fichiers de configuration.
* Cet analyseur travaille sur un fichier à la fois, son but est d'être
* utilisé par d'autres modules qui se chargeront de l'analyse syntaxique.
*/
/*****************************************************************************
*********Variables maintenues au cours de l'analyse par l'analyseur***********
******************************************************************************/
/*Caractère actuel lu avec la fonction lex_readChar.*/
extern char lex_CurrentChar;
/*Ligne actuelle de l'analyse lexicale dans le fichier*/
extern int lex_LineCount;
/*Si on est arrivé à la fin du fichier ou s'il y a une erreur, ceci vaudra 0.*/
extern int lex_EtatOK;
/*****************************************************************************
************************FONCTIONS D'ANALYSE LEXICALE**************************
******************************************************************************/
/*Tente d'ouvrir le fichier indiqué.
* Le fichier est ouvert en vue d'une analyse lexicale,
* c'est à lui que feront référence les appels aux fonctions de ce module.
* PARAM:
fichier au format texte à ouvrir.
id de log où écrire les messages (0 = aucun).
* RETOURNE:
true(1) si succès, false(0) si échec.
*/
bool lex_openFile(char*, int);
/*Ferme le fichier actuellement lu par l'analyseur.
* RETOURNE:
1 si OK, 0 sinon.
renvoie aussi 1 si aucun fichier n'était ouvert par l'analyseur.
*/
bool lex_closeFile();
/*lire un caractère. Augmente le compteur de lignes si saut détecté.
* Retourne la valeur de etatOK*/
int lex_readChar();
/*lire des caractères blancs jusqu'à un non-blanc (1) ou EOF (0).
* lit aussi les commentaires (précédés par #) jusqu'à newline.*/
int lex_readWhites();
/*sauter une ligne, s'arrêter si on tombe sur un caractère non commenté.
* Retourne 1 si saut OK, 0 si caractère rencontré.*/
int lex_readToNewline();
/*Lire jusqu'à rencontrer le caractère sépcifié (ne le passe pas).
* Retourne 1 si caractère atteint, 0 sinon (EOF)*/
int lex_readUntil(char);
//En cas d'erreur syntaxique, saute au moins une ligne.
void lex_errorLoop();
//tente de lire un identificateur, stocké dans la chaîne passée si OK.
//retourne 0 si erreur, 1 si OK.
bool lex_readIdent(char*);
//lit une chaîne comprenant n'importe quel caractère, ALLOUE LA MEMOIRE.
//retourne la taille de la chaîne, -1 si erreur.
int lex_readString(char**);
//lit un nombre. 1 si succès, 0 si erreur. Pas d'allocation.
bool lex_readInt(int*);
//lit un flottant. Requiert la présence d'un '.' dans le nombre.
bool lex_readFloat(float*);
//lit un booléen. 0 ou 1, true ou false (insensible à la casse)
bool lex_readBool(bool*);
#endif
|
ranjak/opengl-sample
|
include/log.h
|
#ifndef LOG_H
#define LOG_H
#include <stddef.h>
#include <stdarg.h>
/*
Gestion des logs et des erreurs du moteur
*/
/* Ouverture d'un fichier de log en écriture.
PARAM : nom du fichier.
RETOURNE : un numéro de log >= 1. 0 si erreur.
*/
int eg_createLog(char[]);
/* Ecrire dans le log spécifié.
PARAMS: n° de log
buffer de données à écrire
nombre d'octets à écrire
RETOURNE: 0 si succès
-1 si erreur.
*/
int eg_bufToLog(int, char[], size_t);
/* Ecrire une chaine dans un log.
Wrapper pour fprintf.
PARAMS: n° de log
format de la chaine
paramètres format
RETOURNE: 0 si succès
-1 si échec
*/
int eg_strToLog(int, char[], ...);
/* Fermer le log spécifié.
PARAM: n° de log.
RETOURNE: 0 si succès
-1 si erreur.
*/
int eg_closeLog(int);
/* Fermer tous les logs précédemment ouverts.
RETOURNE: 0 si succès
-1 si erreur
*/
int eg_closeAllLogs();
#endif
|
ranjak/opengl-sample
|
src/scene.c
|
#include "scene.h"
#include "log.h"
#include "renderer.h"
#include "controls.h"
#include <math.h>
//Calcule les FPS et les affiche dans la console
//le void* est un pointeur vers une scène.
static Uint32 updateFps(Uint32, void*);
//MAJ de la scène (déplacement de l'objet). Prend la durée d'une frame en secondes.
static void scene_update(Scene*, double);
//Effectue une action en fonction de la pression d'une touche.
static void scene_performAction(Eg_KeyAction, Scene*);
//Si une touche est relâchée, arrête l'action lui correspondant.
static void scene_stopAction(Eg_KeyAction, Scene*);
Scene* scene_create(char* wdowName, int width, int height)
{
SDL_Window* wdow = NULL;
SDL_GLContext ctxt = NULL;
//Initialisation SDL
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
{
fprintf(stderr, "Erreur SDL : %s\n", SDL_GetError());
SDL_Quit();
return NULL;
}
//opengl version 3.3
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
if(SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE) < 0) printf("Erreur : %s\n", SDL_GetError());
//création fenêtre et contexte
wdow = SDL_CreateWindow(wdowName, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
ctxt = SDL_GL_CreateContext(wdow);
//Chargement des fonctions OpenGL avec GLEW
GLenum ginit = glewInit();
if(ginit != GLEW_OK)
{
fprintf(stderr, "Erreur GLEW : %s\n", glewGetErrorString(ginit));
SDL_DestroyWindow(wdow);
SDL_Quit();
return NULL;
}
//GLEW provoque une erreur GL, on la consomme ici.
glGetError();
if(ctxt == NULL)
{
fprintf(stderr, "Erreur de création du contexte : %s\n", SDL_GetError());
SDL_DestroyWindow(wdow);
SDL_Quit();
return NULL;
}
//attribution des valeurs à la scène
Scene* scene = (Scene*)malloc(sizeof(Scene));
if(scene != NULL)
{
scene->wdow = wdow;
scene->ctxt = ctxt;
scene->wdowTitle = wdowName;
scene->open = 1;
scene->movement = 0.f;
scene->scale = 0.f;
scene->rotation = 0.f;
//chargement de la matrice identité ds la matrice de trans
scene->transMtx = IdMat4;
scene->wireframe = false;
}
if(eg_initRenderer(scene) < 0)
{
scene_destroy(scene);
return NULL;
}
return scene;
}
void scene_destroy(Scene* scene)
{
eg_destroyRenderer();
SDL_GL_DeleteContext(scene->ctxt);
SDL_DestroyWindow(scene->wdow);
eg_closeAllLogs();
free(scene);
SDL_Quit();
}
void scene_runMainLoop(Scene* scene)
{
//calcul du temps de la frame. prev et cur en ms, mais frame en s.
double prevTime, curTime, frameTime;
scene->frameCount=0.f;
//affichage des FPS toutes les 250ms.
SDL_TimerID fpsCounter = SDL_AddTimer(250, updateFps, scene);
//valeur initiale du temps
prevTime = (double)SDL_GetTicks();
while(scene->open)
{
//gestion des événements et du rendu
scene_handleInput(scene);
scene_update(scene, frameTime);
eg_render();
//gestion du temps
scene->frameCount++;
curTime = (double)SDL_GetTicks();
frameTime = (curTime - prevTime)/1000.d;
prevTime = curTime;
}
SDL_RemoveTimer(fpsCounter);
}
void scene_handleInput(Scene* scene)
{
SDL_Event evt;
Eg_KeyAction act;
while(SDL_PollEvent(&evt))
{
switch(evt.type)
{
case SDL_QUIT:
scene->open = 0;
return;
case SDL_KEYDOWN:
act = eg_getActionFromKey(evt.key.keysym.sym);
if(act != EG_KEY_NOACTION && !evt.key.repeat)
scene_performAction(act, scene);
break;
case SDL_KEYUP:
act = eg_getActionFromKey(evt.key.keysym.sym);
if(act != EG_KEY_NOACTION)
scene_stopAction(act, scene);
break;
default:
break;
}
}
}
void scene_performAction(Eg_KeyAction act, Scene* scene)
{
switch(act)
{
case EG_KEY_CHANGESHAPE:
printf("Changement de forme !\n");
break;
case EG_KEY_EXIT:
scene->open = 0;
break;
case EG_KEY_MOVELEFT:
scene->movement -= 0.5;
break;
case EG_KEY_MOVERIGHT:
scene->movement += 0.5;
break;
case EG_KEY_TGWFRENDER:
if(scene->wireframe)
{
scene->wireframe = false;
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
else
{
scene->wireframe = true;
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
break;
case EG_KEY_SCALEUP:
scene->scale += 0.3;
break;
case EG_KEY_SCALEDOWN:
scene->scale -= 0.3;
break;
case EG_KEY_ROTZL:
scene->rotation += PI/2.f;
break;
case EG_KEY_ROTZR:
scene->rotation -= PI/2.f;
break;
default:
break;
}
}
void scene_stopAction(Eg_KeyAction act, Scene* scene)
{
switch(act)
{
case EG_KEY_MOVELEFT:
scene->movement += 0.5;
break;
case EG_KEY_MOVERIGHT:
scene->movement -= 0.5;
break;
case EG_KEY_SCALEUP:
scene->scale -= 0.3;
break;
case EG_KEY_SCALEDOWN:
scene->scale += 0.3;
break;
case EG_KEY_ROTZL:
scene->rotation -= PI/2.f;
break;
case EG_KEY_ROTZR:
scene->rotation += PI/2.f;
break;
default:
break;
}
}
void scene_update(Scene* scene, double dt)
{
float scaleFactor = 1.0 + scene->scale*dt;
//changement de la position en X.
scene->transMtx = egm_mat4Translate(&scene->transMtx, dt*scene->movement, 0., 0.);
//scaling X, Y, Z
scene->transMtx = egm_mat4Scale(&scene->transMtx, scaleFactor, scaleFactor, 1.0);
//rotation
scene->transMtx = egm_mat4RotZ(&scene->transMtx, dt*scene->rotation);
}
Uint32 updateFps(Uint32 interval, void* scene)
{
float itvSec = (float)interval / 1000.f;
Scene* sc = (Scene*)scene;
char title[SCENE_MAX_TITLE_LG];
//calcul et affichage du framerate dans la barre de titre.
snprintf(title, SCENE_MAX_TITLE_LG, "%s | %d FPS", sc->wdowTitle, (int)(sc->frameCount / itvSec));
SDL_SetWindowTitle(sc->wdow, title);
//réinitialisation du compteur
sc->frameCount = 0.f;
return interval;
}
char* getGLerrorString(GLenum errCode)
{
switch(errCode)
{
case GL_NO_ERROR:
return "Pas d'erreur.";
case GL_INVALID_ENUM:
return "Argument énuméré incorrect.";
case GL_INVALID_VALUE:
return "Argument numérique incorrect.";
case GL_INVALID_OPERATION:
return "Opération illégale dans l'état actuel.";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "Framebuffer Object incomplet.";
case GL_OUT_OF_MEMORY:
return "Plus assez de mémoire pour exécuter la commande.";
case GL_STACK_UNDERFLOW:
return "L'opération demandée causerait un stack underflow.";
case GL_STACK_OVERFLOW:
return "L'opération demandée causerait un stack overflow.";
default:
return "Valeur d'erreur invalide.";
}
}
|
ranjak/opengl-sample
|
src/lexutil.c
|
<gh_stars>0
#include "lexutil.h"
#include "log.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <float.h>
#include <math.h>
//Définition des variables externes
char lex_CurrentChar = EOF;
int lex_LineCount = 0;
int lex_EtatOK = 0;
static int anaLog = 0;
static FILE* filePtr = NULL;
bool lex_openFile(char* filename, int log)
{
filePtr = fopen(filename, "r");
if(filePtr == NULL)
{
fprintf(stderr, "[Lex] Couldn't open file %s\n", filename);
return false;
}
lex_EtatOK = 1;
lex_LineCount = 1;
//Lecture du premier caractère, on voit si le fichier est vide ou non
lex_readChar();
if(!lex_EtatOK)
{
fprintf(stderr, "[Lex] File %s appears to be empty. Closing.\n", filename);
lex_LineCount = 0;
fclose(filePtr);
return false;
}
//sinon, OK pour commencer l'analyse !
anaLog = log;
eg_strToLog(anaLog, "[Lex] File %s opened successfully, ready for lexical analysis.\n", filename);
return true;
}
bool lex_closeFile()
{
if(filePtr == NULL)
return true;
if(fclose(filePtr) != EOF)
{
eg_strToLog(anaLog, "[Lex] Analysis terminated, file closed successfully.\n");
return true;
}
else
{
eg_strToLog(anaLog, "[Lex] Analysis terminated, but error closing the file.\n");
return false;
}
}
int lex_readChar()
{
int c = fgetc(filePtr);
if(c == EOF) lex_EtatOK=0;
lex_CurrentChar = (char)c;
if(lex_CurrentChar == '\n') lex_LineCount++;
return lex_CurrentChar;
}
int lex_readWhites()
{
while(isspace(lex_CurrentChar) || lex_CurrentChar=='#')
{
//saut de ligne si commentaires.
if(lex_CurrentChar=='#')
lex_readUntil('\n');
lex_readChar();
}
return lex_EtatOK;
}
int lex_readToNewline()
{
while(isblank(lex_CurrentChar))
lex_readChar();
if(lex_CurrentChar=='#')
lex_readUntil('\n');
if(lex_CurrentChar == '\n')
{
lex_readChar();
return 1;
}
else
return 0;
}
int lex_readUntil(char c)
{
while(lex_EtatOK && lex_CurrentChar != c)
lex_readChar();
return lex_EtatOK;
}
void lex_errorLoop()
{
while(lex_EtatOK && lex_CurrentChar != '\n')
{
//on saute les strings
if(lex_CurrentChar=='"')
{
lex_readChar();
lex_readUntil('"');
lex_readChar();
}
else if(lex_CurrentChar=='#')
lex_readUntil('\n');
else
lex_readChar();
}
lex_readWhites();
}
/*
* Tente de lire un identificateur dans le fichier de config.
* Les identificateurs sont composés de lettres (min ou MAJ),
* de chiffres, d'underscores et comportent au maximum EG_MAX_IDENT_LG
* caractères.
* PARAM:
chaîne qui recevra l'ident. Doit pointer une location valide.
* RETOURNE:
1 si ident lu sans erreur, 0 sinon.
*/
bool lex_readIdent(char* ident)
{
char temp[EG_MAX_IDENT_LG];
int length = 0, done = 0;
if(!isalpha(lex_CurrentChar))
{
eg_strToLog(anaLog, "[Lex] Line %d : error : expected identificator, read %c. Identificators must start with a letter.", lex_LineCount, lex_CurrentChar);
return 0;
}
while(!done && length < EG_MAX_IDENT_LG-1)
{
//le caractère lu est-il autorisé ?
if(isalnum(lex_CurrentChar) || lex_CurrentChar=='_')
{
temp[length] = lex_CurrentChar;
length++;
lex_readChar();
}
//sinon, on considère que l'ident s'arrête là
else
done = 1;
}
//si done est faux, on a dépassé la limite de taille.
if(!done)
{
eg_strToLog(anaLog, "[Lex] Error at line %d : max identificator size (%d) overrun, discarding value.", lex_LineCount, EG_MAX_IDENT_LG-1);
return 0;
}
//ident valide si on a lu au moins 1 caractère.
if(length > 0)
{
temp[length] = '\0';
memcpy(ident, temp, length+1);
return 1;
}
//sinon, aucun caractère valide lu.
return 0;
}
/*
* Lit une chaîne de caractères dans le fichier de config.
* Une chaîne est une valeur qui doit être de forme "chaîne".
* Pas de limite de longueur. La chaîne sera null-terminée.
* PARAM:
destination pour la chaîne. DOIT ETRE LIBEREE PAR LE CALLER
* RETOURNE:
nombre de caractères dans la chaîne (vide acceptée).
-1 si chaîne incorrecte.
*/
int lex_readString(char** str)
{
int length = 0, i = 0;
int debutLine;
fpos_t debutPos;
if(lex_CurrentChar != '"')
return -1;
fgetpos(filePtr, &debutPos);
debutLine = lex_LineCount;
lex_readChar();
while(lex_EtatOK && lex_CurrentChar != '"')
{
length++;
lex_readChar();
}
lex_LineCount = debutLine;
//Si fin de fichier sans trouver de fin de chaîne, échec.
if(!lex_EtatOK)
{
eg_strToLog(anaLog, "[Lex] Error : string beginning at line %d has no end.", debutLine);
return -1;
}
//Sinon -> ok, récupération de la chaîne.
*str = malloc((length+1)*sizeof(char));
fsetpos(filePtr, &debutPos);
while(i < length)
(*str)[i++] = lex_readChar();
(*str)[length] = '\0';
//On doit reprendre un caractère d'avance.
lex_readChar();
lex_readChar();
return length;
}
bool lex_readInt(int* val)
{
int res = 0, limitCheck = 0, isNeg = 0;
if(lex_CurrentChar=='-')
{
isNeg = 1;
lex_readChar();
}
//lecture digit par digit
if(isdigit(lex_CurrentChar))
{
do {
//limitCheck = res avec un digit de moins. S'il n'est plus derrière res -> limite atteinte.
//il faut l'utiliser seulement quand res vaut + que 0, sinon fausse alerte (par ex. avec res = 02).
if(res > 0)
limitCheck = res;
res = res*10 + (lex_CurrentChar-'0');
lex_readChar();
} while(isdigit(lex_CurrentChar) && limitCheck < res);
//si on a un point juste après le nombre, c'est qu'on voulait faire passer un float : pas bien.
if(lex_CurrentChar=='.')
{
eg_strToLog(anaLog, "[Lex] Line %d : expected int, read float.", lex_LineCount);
return 0;
}
//si res n'est pas plus grand que limitCheck, il a atteint la limite d'int.
if(limitCheck != 0 && limitCheck >= res)
{
eg_strToLog(anaLog, "[Lex] Int representation limit overrun at line %d, discarding value.", lex_LineCount);
return 0;
}
//sinon, succès : enregistrement de la valeur.
if(isNeg) res = -res;
*val = res;
return 1;
}
eg_strToLog(anaLog, "[Lex] Error at line %d : expected int, read %c", lex_LineCount, lex_CurrentChar);
return 0;
}
bool lex_readFloat(float* val)
{
float res=0.f, limitCheck=0.f;
int decDigitNb = 0;
bool isNeg = false;
if(lex_CurrentChar=='-')
{
isNeg = true;
lex_readChar();
}
if(isdigit(lex_CurrentChar))
{
do {
if(res > 0.f)
limitCheck = res;
res = res*10.f + (float)(lex_CurrentChar-'0');
lex_readChar();
} while(isdigit(lex_CurrentChar) && limitCheck < res);
}
if(lex_CurrentChar == '.')
{
lex_readChar();
while(isdigit(lex_CurrentChar) && decDigitNb <= FLT_DIG)
{
decDigitNb++;
res = res + (float)(lex_CurrentChar-'0') / (float)pow(10.d, (double)decDigitNb);
lex_readChar();
}
}
else
{
eg_strToLog(anaLog, "[Lex] Error at line %d : expected floating point number", lex_LineCount);
return false;
}
if((limitCheck != 0.f && limitCheck >= res) || decDigitNb > FLT_DIG)
{
eg_strToLog(anaLog, "[Lex] Error at line %d : floating point number limit overrun", lex_LineCount);
return false;
}
//succès
if(isNeg) res = -res;
*val = res;
return true;
}
bool lex_readBool(bool* val)
{
int strsize;
bool res = 0;
char temp, tempstr[EG_MAX_IDENT_LG];
//on lit soit 0 ou 1, soit true or false
temp = lex_CurrentChar;
if(temp=='0' || temp=='1')
{
if(isspace(lex_readChar()) || !lex_EtatOK)
{
*val = temp - '0';
res = 1;
}
}
else if(lex_readIdent(tempstr))
{
//on tente de lire true ou false
strsize = strlen(tempstr);
if(strsize==4 || strsize==5)
{
//on ne veut pas de sensibilité à la casse
strsize--;
for(;strsize >= 0 ; strsize--)
tempstr[strsize] = tolower(tempstr[strsize]);
if(strcmp("true", tempstr) == 0)
{
*val = true;
res = 1;
}
else if(strcmp("false", tempstr) == 0)
{
*val = false;
res = 1;
}
}
}
if(res == 0)
eg_strToLog(anaLog, "[Lex] Error line %d : expected boolean value.", lex_LineCount);
return res;
}
|
ranjak/opengl-sample
|
src/controls.c
|
<reponame>ranjak/opengl-sample
#include "controls.h"
static bool cfg_readKey(Eg_cfgEntry* entry);
static const char* cfg_keyToStr(Eg_cfgEntry* entry);
//sert à stocker le résultat de keyToStr. Est remplacé à chaque appel de la fonction.
static char* tempStr = NULL;
/*
* Liste des valeurs associées aux actions
* Valeurs par défaut pouvant être changées
* pendant l'exécution ou au chargement de l'ini
*/
SDL_Keycode Eg_KeyBindings[EG_KEY_NOACTION] = {
SDLK_t, //CHANGESHAPE
SDLK_ESCAPE, //EXIT
SDLK_LEFT, //MOVELEFT
SDLK_RIGHT, //MOVERIGHT
SDLK_w, //TGWFRENDER
SDLK_UP, //SCALEUP
SDLK_DOWN, //SCALEDOWN
SDLK_b, //ROTZL
SDLK_n //ROTZR
};
Eg_cfgEntry keyDesc[EG_KEY_NOACTION] = {
{
"ChangeShape",
&Eg_KeyBindings[0],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"Exit",
&Eg_KeyBindings[1],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"MoveLeft",
&Eg_KeyBindings[2],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"MoveRight",
&Eg_KeyBindings[3],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"ToggleWireframe",
&Eg_KeyBindings[4],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"ScaleUp",
&Eg_KeyBindings[5],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"ScaleDown",
&Eg_KeyBindings[6],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"RotateZleft",
&Eg_KeyBindings[7],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
},{
"RotateZright",
&Eg_KeyBindings[8],
NULL, NULL,
EG_STA_ALLOCED,
NULL, cfg_readKey, cfg_keyToStr
}
};
void eg_getControlCfgDesc(Eg_configSection* cs)
{
if(cs != NULL)
{
cs->name = "Controls";
cs->paramCount = EG_KEY_NOACTION;
cs->wasRead = 0;
cs->entries = keyDesc;
}
}
Eg_KeyAction eg_getActionFromKey(SDL_Keycode key)
{
int i=0;
while(key != Eg_KeyBindings[i] && i < EG_KEY_NOACTION)
i++;
return i;
}
void eg_bindKey(Eg_KeyAction act, SDL_Keycode key)
{
if(act < EG_KEY_NOACTION)
Eg_KeyBindings[act] = key;
}
bool cfg_readKey(Eg_cfgEntry* entry)
{
char* temp;
SDL_Keycode res;
int strsize = lex_readString(&temp);
if(strsize < 0)
return false;
res = SDL_GetKeyFromName(temp);
//chaîne vide = pas de binding, chaîne non vide mais touche inconnue = erreur !
if(res == SDLK_UNKNOWN && strsize > 0)
{
fprintf(stderr, "[Config] Error setting key for parameter %s : unknown key : '%s'\n", entry->label, temp);
free(temp);
return false;
}
*(SDL_Keycode*)entry->value = res;
free(temp);
return true;
}
const char* cfg_keyToStr(Eg_cfgEntry* entry)
{
const char* sdlval;
int size;
sdlval = SDL_GetKeyName(*(SDL_Keycode*)entry->value);
size = strlen(sdlval)+3;
free(tempStr);
//la chaîne à renvoyer doit être bornée de guillemets.
tempStr = malloc(sizeof(char)*size);
snprintf(tempStr, size, "\"%s\"", sdlval);
return tempStr;
}
|
ranjak/opengl-sample
|
include/scene.h
|
<reponame>ranjak/opengl-sample
#ifndef SCENEOPENGL_H
#define SCENEOPENGL_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//#define GL_GLEXT_PROTOTYPES
//#include <GL/glcorearb.h>
#include <GL/glew.h>
#include "SDL.h"
#include "mathutil.h"
#define SCENE_MAX_TITLE_LG 50
/*Structure de scène : contient une fenêtre SDL
et un contexte opengl.*/
struct Scene
{
SDL_Window* wdow;
SDL_GLContext ctxt;
char* wdowTitle;
//la fenêtre est-elle ouverte ?
char open;
float frameCount;
double movement;
float scale;
float rotation;
Mat4 transMtx;
bool wireframe;
};
typedef struct Scene Scene;
/*Création d'une fenêtre SDL et d'un contexte opengl
PARAMS: nom de la fenetre
largeur
hauteur
RETOURNE: scène créée, NULL si erreur
*/
Scene* scene_create(char[], int, int);
/*Suppression d'une scène (fenêtre + contexte)
précédemment créée.
PARAM: Scène.
*/
void scene_destroy(Scene*);
/*Gestion de l'entrée utilisateur
PARAM: Scène où recevoir l'info.
*/
void scene_handleInput(Scene*);
void scene_runMainLoop(Scene*);
//message correspondant à un code d'erreur de GL
char* getGLerrorString(GLenum errCode);
#endif
|
ranjak/opengl-sample
|
include/mathutil.h
|
<filename>include/mathutil.h
#ifndef MATHUTIL_H
#define MATHUTIL_H
#include <stddef.h>
#include <stdbool.h>
#define PI 3.14159265
/*Utilitaires de calcul pour maths analytiques (fonctions)*/
/*
* Vecteur à 3 composantes flottantes
*/
typedef struct Vec3
{
float x, y, z;
} Vec3;
typedef struct Vec4
{
float v[4];
} Vec4;
typedef struct Mat4
{
float m[16];
} Mat4;
/*Matrice nulle (pleine de 0)*/
extern const Mat4 ZeroMat4;
/*Matrice identité*/
extern const Mat4 IdMat4;
/*
* Produit matriciel de matrices carrées 4.
* PARAMS:
matrices à multiplier (gauche et droite)
* RETOURNE:
matrice résultat
*/
Mat4 egm_mat4Mult(const Mat4* ml, const Mat4* mr);
/*
* Déterminant d'une matrice 4.
* PARAM:
matrice dont calculer le déterminant
* RETOURNE:
déterminant de la matrice.
*/
float egm_mat4Det(const Mat4* m);
/*
* Appliquer une translation sur une matrice.
* PARAMS:
matrice sur laquelle appliquer la translation.
3 composantes de la translation.
* RETOURNE:
Nouvelle matrice correspondant à celle passée translatée.
*/
Mat4 egm_mat4Translate(const Mat4* m, float x, float y, float z);
/*
* Appliquer une échelle sur une matrice.
* PARAMS:
matrice à scaler
3 composantes d'échelle.
* RETOURNE:
matrice dupliquée scalée.
*/
Mat4 egm_mat4Scale(const Mat4* m, float x, float y, float z);
/*
* Applique une rotation à une matrice.
* PARAMS:
matrice à faire pivoter
angle de rotation
* RETOURNE:
nouvelle matrice = rotation * m.
*/
Mat4 egm_mat4RotX(const Mat4* m, float angle);
Mat4 egm_mat4RotY(const Mat4* m, float angle);
Mat4 egm_mat4RotZ(const Mat4* m, float angle);
/*
* Multiplier 2 matrices carrées 4x4 de floats.
* En ordre par colonne.
* PARAMS:
matrice gauche
matrice droite
matrice pour contenir gauche*droite
(chacune un tableau de 16 floats alloué par l'appelant)
* RETOURNE:
true si OK,
false si échec (un paramètre NULL)
*/
bool egm_mat4Multold(float ma[], float mb[], float mres[]);
/*
* Polynôme : décrit par un degré et des coefficients réels.
* Le nombre de coefficients doit être égal à deg+1.
* Ils sont rangés par exposant croissant.
* Ex : 2x² + 3x - 5 :
deg = 2
coefs = {-5, 3, 2}
*/
typedef struct polynom
{
int deg;
float coefs[];
} Egm_polynom;
/*
* Calculer "count" valeurs de la fonction "evalf" sur l'intervalle [fnIntvStart, fnIntvEnd],
* stocker ces valeurs dans "results", avec un espacement de "stride" octets entre chaque valeur.
* PARAMS:
Fonction à évaluer. Le void* représente des paramètres spécifiques à cette fonction,
ex. des coefficients pour un polynôme.
Paramètres spécifiques en question, qui seront passés à la fonction.
Bornes inférieure et supérieure (inclues) de l'intervalle de calcul.
Nombre de valeurs à calculer dans l'intervalle, le pas de calcul est fixé en fonction.
Tableau dans lequel seront stocké les "count" valeurs résultantes, il doit pouvoir contenir ces valeurs.
Nombres d'octets à sauter dans le tableau entre chaque valeur (si <=4, valeurs contigües).
*/
void egm_sampleFunction (
float (*evalf)(void*, float),
void* fparams,
float fnIntvStart, float fnIntvEnd,
size_t count,
float* result, size_t stride
);
/*
* Calcule la valeur polyStruct(x).
* PARAMS:
Structure de type Egm_polynom
Valeur dont l'image doit être évaluée
* RETOURNE:
Image de x.
*/
float egm_evalPoly(void* polyStruct, float x);
/*calcule les images de count valeurs par le poly spécifié par son degré et ses coefs.
results doit être déjà alloué. stride marche à la fois pour invalues et results.*/
void egm_makePolynom(int deg, float coefs[], int count, float* inValues, float* results, size_t stride);
#endif
|
ranjak/opengl-sample
|
include/renderer.h
|
#ifndef RENDERER_H
#define RENDERER_H
#include "scene.h"
/*
Définit le programme de rendu, ses étapes, spécifie les éléments à dessiner.
*/
/*
* crée le programme de rendu.
* PARAM: scène sur laquelle le renderer opère
* RETOURNE: 0 si succès, -1 si échec
*/
int eg_initRenderer(Scene*);
/*
* efface et redessine la scène.
*/
void eg_render();
/*
* Détruit le programme de rendu.
* RETOURNE: 0 si succès, -1 si échec
*/
int eg_destroyRenderer();
#endif
|
ranjak/opengl-sample
|
include/controls.h
|
<gh_stars>0
#ifndef CONTROLS_H
#define CONTROLS_H
#include "SDL.h"
#include "config.h"
/*Controles au clavier/souris ou autres.
* Liste des actions possibles.
* Gère le chargement des bindings et leur valeur par défaut.
*/
/*
* Liste des actions devant être affectées à une touche.
* EG_KEY_NOACTION est toujours à la fin de l'énumération,
* il représente à la fois l'action nulle
* et le nombre d'actions non-nulles (toutes les valeurs sauf lui).
*/
typedef enum Eg_KeyAction
{
EG_KEY_CHANGESHAPE,
EG_KEY_EXIT,
EG_KEY_MOVELEFT,
EG_KEY_MOVERIGHT,
EG_KEY_TGWFRENDER,
EG_KEY_SCALEUP,
EG_KEY_SCALEDOWN,
EG_KEY_ROTZL,
EG_KEY_ROTZR,
EG_KEY_NOACTION
}Eg_KeyAction;
/*
* Liste des bindings : associe une touche à chaque action.
* Ce module fournit des valeurs par défaut
* si aucune configuration n'est spécifiée.
*/
extern SDL_Keycode Eg_KeyBindings[];
/*
* Associe une action à une touche.
* PARAM:
code SDL de la touche
* RETOURNE:
action liée à la touche,
EG_KEY_NOACTION si touche non liée.
*/
Eg_KeyAction eg_getActionFromKey(SDL_Keycode);
/*
* Change un key binding.
* PARAMS:
action à rebinder
touche à associer.
*/
void eg_bindKey(Eg_KeyAction, SDL_Keycode);
/*
* Fournit la structure correspondant à la section
* de configuration des contrôles.
* PARAM:
structure configSection vide mais allouée.
*/
void eg_getControlCfgDesc(Eg_configSection* cs);
#endif
|
ranjak/opengl-sample
|
src/renderer.c
|
#include "renderer.h"
#include "log.h"
#include "mathutil.h"
/*
* Structure définissant un vertex :
* Coordonnées X, Y, Z, W
* Couleur R, G, B, A
*/
typedef struct
{
GLfloat XYZW[4];
GLfloat RGBA[4];
} Vertex;
static Scene* target;
static int renderLog;
static GLuint VAO,
VBO,
IBO,
vtxShader,
fragShader,
program,
mtxUnifLoc;
static GLsizei vtCount,
idCount;
const GLchar* VertexShader =
{
"#version 330\n"\
"layout(location=0) in vec3 in_Position;\n"\
/*"layout(location=1) in vec4 in_Color;\n"\*/
"uniform mat4 matrix;\n"\
"out vec4 ex_Color;\n"\
"void main(void)\n"\
"{\n"\
" gl_Position = matrix * vec4(in_Position, 1.0);\n"\
" ex_Color = vec4(0.0, 0.5, 1.0, 1.0);\n"\
"}\n"
};
const GLchar* FragmentShader =
{
"#version 330\n"\
"in vec4 ex_Color;\n"\
"out vec4 out_Color;\n"\
"void main(void)\n"\
"{\n"\
" out_Color = ex_Color;\n"\
"}\n"
};
static GLuint makeShader(GLenum type, const GLchar** source);
static int createProgram();
static int makeRenderData();
int eg_initRenderer(Scene* targetScene)
{
target = targetScene;
renderLog = eg_createLog("Renderer.log");
if(createProgram() < 0)
{
fprintf(stderr, "Renderer : impossible de créer le programme de rendu.\n");
return -1;
}
if(makeRenderData() < 0)
{
fprintf(stderr, "Renderer : impossible de créer les données de rendu.\n");
return -1;
}
eg_strToLog(renderLog, "Renderer initialisé avec succès.");
return 0;
}
void eg_render()
{
glUniformMatrix4fv(mtxUnifLoc, 1, GL_FALSE, target->transMtx.m);
glClear(GL_COLOR_BUFFER_BIT);
//glDrawArrays(GL_LINE_STRIP, 0, vtCount);
glDrawElements(GL_TRIANGLE_FAN, idCount, GL_UNSIGNED_BYTE, (GLvoid*)0);
SDL_GL_SwapWindow(target->wdow);
}
int eg_destroyRenderer()
{
GLenum errCode;
glGetError();
//1. suppression des shaders et du programme
glDeleteShader(vtxShader);
glDeleteShader(fragShader);
glUseProgram(0);
glDeleteProgram(program);
//2. suppression des données de vertices
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &IBO);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &VBO);
glBindVertexArray(0);
glDeleteVertexArrays(1, &VAO);
errCode = glGetError();
if(errCode != GL_NO_ERROR)
{
fprintf(stderr, "Erreur destruction du renderer : %s\n", getGLerrorString(errCode));
return -1;
}
eg_strToLog(renderLog, "Renderer détruit avec succès");
return 0;
}
int createProgram()
{
GLenum errCode;
glGetError();
program = glCreateProgram();
vtxShader = makeShader(GL_VERTEX_SHADER, &VertexShader);
fragShader = makeShader(GL_FRAGMENT_SHADER, &FragmentShader);
if(vtxShader < 0 || fragShader < 0)
return -1;
glAttachShader(program, vtxShader);
glAttachShader(program, fragShader);
glLinkProgram(program);
//spécification de la matrice de transformation en uniform du vertex shader
mtxUnifLoc = glGetUniformLocation(program, "matrix");
glUseProgram(program);
glUniformMatrix4fv(mtxUnifLoc, 1, GL_FALSE, target->transMtx.m);
glDetachShader(program, vtxShader);
glDetachShader(program, fragShader);
errCode = glGetError();
if(errCode != GL_NO_ERROR)
{
fprintf(stderr, "Erreur de création du programme de rendu : %s\n", getGLerrorString(errCode));
return -1;
}
eg_strToLog(renderLog, "Programme de rendu créé avec succès.");
return 0;
}
void mirrorY(Vec3* dest, Vec3* source, int count)
{
for(int i=0 ; i<count ; i++)
{
dest[i].x = -source[count-1-i].x;
dest[i].y = source[count-1-i].y;
}
}
int makeRenderData()
{
//pas entre 2 valeurs = précision du dessin, absc = abscisse actuelle (de 0 à 1)
float step = 0.3f;
float absc = 1.f;
//x^exp, x=1->y=h, x=0->y=c
int exp = 2, i;
float coefs[] = {-0.1, 0., -0.3};
//conteneur des vertices
Vec3* vertices;
//nb de vertices qu'on va calculer entre 0 et 1.
int cvCount = (int)(1.f / step);
//nb de vertices total = combien de steps entre -1 et 1 + extrémités sup. du pont
vtCount = cvCount*2 + 3;
idCount = vtCount+3; //nombre d'indices nécessaires : double passage sur 2 vertices + restart
GLubyte* indices = malloc(idCount*sizeof(GLubyte));
vertices = calloc(vtCount, sizeof(Vec3));
vertices[vtCount-2].x = -1.;
vertices[vtCount-2].y = 0.;
vertices[vtCount-2].z = 0.;
vertices[vtCount-1].x = 1.;
vertices[vtCount-1].y = 0.;
vertices[vtCount-1].z = 0.;
indices[0] = vtCount-1;
//génération de la courbe
for(i=0 ; i<cvCount ; i++)
{
indices[i+1] = i;
vertices[i].x = absc;
absc -= step;
}
egm_makePolynom(exp, coefs, cvCount, &vertices[0].x, &vertices[0].y, 3);
//ajout du 0 au bout de la courbe
indices[++i] = cvCount;
vertices[cvCount].x = 0.;
vertices[cvCount].y = coefs[0];
vertices[cvCount].z = 0.;
indices[++i] = vtCount-2;
indices[++i] = 255; //max ubyte
//2e fan
indices[++i] = vtCount-2;
int j = 3;
for(i=i+1 ; i<idCount ; i++)
{
indices[i] = vtCount - j;
j++;
}
//miroir de la courbe pour compléter le pont
mirrorY(&vertices[cvCount+1], vertices, cvCount);
GLenum errCode = glGetError();
const size_t BufferSize = vtCount*sizeof(Vec3);
/*const size_t VertexSize = sizeof(Vertices[0]);
const size_t RgbOffset = sizeof(Vertices[0].XYZW);*/
//création du VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
//création du VBO contenant les vertices
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, BufferSize, vertices, GL_STATIC_DRAW);
free(vertices);
/*Pour chaque sommet, l'attribut coordonnées a l'index 0,
* et la couleur l'index 1.
* --------------------------VertexSize---------------------|
* ----Coordonnées : 4 floats----|----Couleur : 4 floats----|
* XYZW RGBA
*/
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
//glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, VertexSize, (void*)RgbOffset);
glEnableVertexAttribArray(0);
//glEnableVertexAttribArray(1);
//Création de l'IBO qui contient les indices des vertices
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, idCount, indices, GL_STATIC_DRAW);
free(indices);
glPrimitiveRestartIndex(255);
glEnable(GL_PRIMITIVE_RESTART);
errCode = glGetError();
if(errCode != GL_NO_ERROR)
{
fprintf(stderr, "Erreur dans la spécification des vertices : %s\n", getGLerrorString(errCode));
return -1;
}
eg_strToLog(renderLog, "Spécification des données de rendu terminée avec succès.");
return 0;
}
GLuint makeShader(GLenum type, const GLchar** source)
{
GLint cmplInfo;
GLuint shader;
glGetError();
//---------------création et compilation du vertex shader-------------------------
shader = glCreateShader(type);
//le shader a-t-il été créé ?
if(shader < 1)
{
fprintf(stderr, "Erreur shader : %s\n", getGLerrorString(glGetError()));
return -1;
}
glShaderSource(shader, 1, source, NULL);
glCompileShader(shader);
//vérification du succès de la compilation
//DEBUG
//récup du log s'il existe et envoi dans notre log
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &cmplInfo);
if(cmplInfo > 0)
{
char* shaderLog = malloc(cmplInfo*sizeof(char));
glGetShaderInfoLog(shader, cmplInfo, NULL, shaderLog);
eg_strToLog(renderLog, shaderLog);
free(shaderLog);
}
glGetShaderiv(shader, GL_COMPILE_STATUS, &cmplInfo);
if(cmplInfo == GL_FALSE)
{
fprintf(stderr, "Erreur de compilation du shader. Voir log.\n");
return -1;
}
//FINDEBUG
eg_strToLog(renderLog, "Shader %d compilé avec succès.", shader);
return shader;
}
|
ranjak/opengl-sample
|
include/config.h
|
#ifndef CONFIG_H
#define CONFIG_H
#include "SDL.h"
#include <stdio.h>
#include "lexutil.h"
//longueur maximale d'un indentificateur, en comptant le \0
#define EG_MAX_IDENT_LG 48
/*
*Fichier de configuration
*Format :
*[Section]
*paramètre=valeur
*/
/*typedef enum Eg_Type
{
EG_CHAR,
EG_STRING,
EG_INT,
EG_FLOAT,
EG_BOOL
}Eg_Type;*/
enum allocation
{
EG_NOT_ALLOCED,
EG_STA_ALLOCED,
EG_DYN_ALLOCED
};
/*Liste de
* couples paramètre=valeur
* (name=value).
* Contient des pointeurs de fonction pour gérer la valeur du paramètre.
*/
typedef struct Eg_cfgEntry {
char* label;
void* value;
void *min_val,
*max_val;
enum allocation alloc;
bool (*setValue)(struct Eg_cfgEntry*, void*);
bool (*valueFromStream)(struct Eg_cfgEntry*);
const char* (*valToStr)(struct Eg_cfgEntry*);
}Eg_cfgEntry;
/*
* Définit une section de configuration.
* Contient un nom de section,
* le tableau de descripteurs de paramètres,
* le nombre de ces paramètres,
* un booléen indiquant si la section a été lue dans le fichier de config.
*/
typedef struct configSection
{
char* name;
int paramCount;
int wasRead;
Eg_cfgEntry* entries;
}Eg_configSection;
void eg_loadConfig();
void eg_writeConfig();
int eg_readConfigFile(Eg_configSection*, int);
/**Ces fonctions doivent être utilisées dans des structures cfgEntry.
* Les fonctions "set" copient la valeur passée en paramètre,
* cette valeur peut donc être libérée à l'envi par l'appelant.
* Pour int et float, les champs min_val et max_val définissent les bornes.
* Pour bool, ils sont sans effet.
* Pour string, ils bornent la taille de la chaîne.
* Dans tous les cas, les mettre à NULL signifie ne pas imposer de limite.
* Ces fonctions allouent dynamiquement de la mémoire pour stocker la valeur lue
* si aucune n'a été allouée auparavant. (note : pour string, on alloue systématiquement,
* toute mémoire précédemment allouée est libérée).
*/
bool cfg_setInt(Eg_cfgEntry*, void*);
bool cfg_setFloat(Eg_cfgEntry*, void*);
bool cfg_setBool(Eg_cfgEntry*, void*);
bool cfg_setString(Eg_cfgEntry*, void*);
bool cfg_readInt(Eg_cfgEntry*);
bool cfg_readFloat(Eg_cfgEntry*);
bool cfg_readBool(Eg_cfgEntry*);
bool cfg_readString(Eg_cfgEntry*);
#endif
|
ranjak/opengl-sample
|
src/mathutil.c
|
<reponame>ranjak/opengl-sample<filename>src/mathutil.c
#include "mathutil.h"
#include <math.h>
#include <stdio.h>
const Mat4 ZeroMat4 = {{0., 0., 0., 0.,
0., 0., 0., 0.,
0., 0., 0., 0.,
0., 0., 0., 0.}};
const Mat4 IdMat4 = { { 1., 0., 0., 0.,
0., 1., 0., 0.,
0., 0., 1., 0.,
0., 0., 0., 1.}};
Mat4 egm_mat4Mult(const Mat4* ml, const Mat4* mr)
{
Mat4 mres = ZeroMat4;
for(int i=0 ; i<4 ; i++)
{
for(int j=0 ; j<16 ; j+=4)
{
int idx = i+j;
for(int k=0 ; k<4 ; k++)
mres.m[idx] += ml->m[4*k+i] * mr->m[j+k];
}
}
return mres;
}
float egm_mat4Det(const Mat4* m)
{
float det = 0.f;
const float* mt = m->m;
//développement selon la colonne 0
//0
/*déterminant (5, 9, 13,
6, 10, 14,
7, 11, 15)*/
det = mt[0]*((mt[5]*mt[10]*mt[15] + mt[6]*mt[11]*mt[13] + mt[7]*mt[9]*mt[14]) -
(mt[7]*mt[10]*mt[13] + mt[5]*mt[11]*mt[14] + mt[6]*mt[9]*mt[15]));
//1
/*déterminant (4, 8, 12,
6, 10, 14,
7, 11, 15)*/
det -= mt[1]*((mt[4]*mt[10]*mt[15] + mt[6]*mt[11]*mt[12] + mt[7]*mt[8]*mt[14]) -
(mt[7]*mt[10]*mt[12] + mt[4]*mt[11]*mt[14] + mt[6]*mt[8]*mt[15]));
//2
/*déterminant (4, 8, 12,
5, 9, 13,
7, 11, 15)*/
det += mt[2]*((mt[4]*mt[9]*mt[15] + mt[5]*mt[11]*mt[12] + mt[7]*mt[8]*mt[13]) -
(mt[7]*mt[9]*mt[12] + mt[4]*mt[11]*mt[13] + mt[5]*mt[8]*mt[15]));
//3
/*déterminant (4, 8, 12,
5, 9, 13,
6, 10, 14)*/
det -= mt[3]*((mt[4]*mt[9]*mt[14] + mt[5]*mt[10]*mt[12] + mt[6]*mt[8]*mt[13]) -
(mt[6]*mt[9]*mt[12] + mt[4]*mt[10]*mt[13] + mt[5]*mt[8]*mt[14]));
return det;
}
Mat4 egm_mat4Translate(const Mat4* m, float x, float y, float z)
{
//indices de translation : 12, 13, 14
Mat4 mt = IdMat4;
mt.m[12] = x;
mt.m[13] = y;
mt.m[14] = z;
return egm_mat4Mult(&mt, m);
}
Mat4 egm_mat4Scale(const Mat4* m, float x, float y, float z)
{
Mat4 ms = IdMat4;
ms.m[0] = x;
ms.m[5] = y;
ms.m[10] = z;
return egm_mat4Mult(&ms, m);
}
Mat4 egm_mat4RotX(const Mat4* m, float angle)
{
float cosx = (float)cos(angle),
sinx = (float)sin(angle);
Mat4 mx = IdMat4;
mx.m[5] = cosx;
mx.m[6] = sinx;
mx.m[9] = (-sinx);
mx.m[10] = cosx;
return egm_mat4Mult(&mx, m);
}
Mat4 egm_mat4RotY(const Mat4* m, float angle)
{
float cosy = (float)cos(angle),
siny = (float)sin(angle);
Mat4 my = IdMat4;
my.m[0] = cosy;
my.m[2] = (-siny);
my.m[8] = siny;
my.m[10] = cosy;
return egm_mat4Mult(&my, m);
}
Mat4 egm_mat4RotZ(const Mat4* m, float angle)
{
float cosz = (float)cos(angle),
sinz = (float)sin(angle);
Mat4 mz = IdMat4;
mz.m[0] = cosz;
mz.m[1] = sinz;
mz.m[4] = (-sinz);
mz.m[5] = cosz;
return egm_mat4Mult(&mz, m);
}
bool egm_mat4Multold(float ma[], float mb[], float mres[])
{
if(ma == NULL || mb == NULL || mres == NULL)
{
fprintf(stderr, "[Mathutil][mat4Mult] Error : all arguments must point to valid locations.\n");
return false;
}
//mres = ma * mb
//boucle 1 : ligne
for(int i=0 ; i<4 ; i++)
{
//boucle 2 : colonne
for(int j=0 ; j<4 ; j++)
{
//boucle 3 : valeur [i, j].
int resId = 4*j + i;
mres[resId] = 0.f;
for(int k=0 ; k<4 ; k++)
mres[resId] += ma[4*k+i] * mb[4*j+k];
}
}
return true;
}
void egm_sampleFunction (
float (*evalf)(void*, float),
void* fparams,
float fnIntvStart, float fnIntvEnd,
size_t count,
float* result, size_t stride
)
{
//pas entre chaque valeur à évaluer
float step = (fnIntvEnd - fnIntvStart) / (float)count;
//abscisse actuelle, qui augmentera de "step" à chaque calcul de valeur
float x = fnIntvStart;
//le stride doit être au moins de la taille d'un float
if(stride == 0) stride = sizeof(float);
if(stride < sizeof(float))
{
fprintf(stderr, "[Mathutil][sampleFunction] Error : stride parameter must be at least the size of a float (%ld) or 0 for contiguous values, but given %ld\n", sizeof(float), stride);
return;
}
//calcul des valeurs jusqu'à itvEnd-step :
//du fait de l'imprécision de float, le dernier x pourrait être différent de intvEnd
for(int i=0 ; i<count-1 ; i++)
{
*result = evalf(fparams, x);
result = (float*)((char*)result + stride);
x += step;
}
//calcul de la dernière valeur
*result = evalf(fparams, fnIntvEnd);
}
float egm_evalPoly(void* polyStruct, float x)
{
Egm_polynom* poly = (Egm_polynom*)polyStruct;
float result = 0.f;
int exp = poly->deg;
while(exp >= 0)
{
result += poly->coefs[exp] * pow(x, exp);
exp--;
}
return result;
}
void egm_makePolynom(int deg, float coefs[], int count, float* inValues, float* results, size_t stride)
{
//sert pour l'évaluation d'une valeur individuelle du polynôme
int calcExp;
for(int i=0 ; i<count ; i++)
{
*results = 0.f;
calcExp = deg;
while(calcExp >= 0)
{
*results += coefs[calcExp]*pow(*inValues, calcExp);
calcExp--;
}
if(stride > 0)
{
results += stride;
inValues += stride;
}
else
{
results++;
inValues++;
}
}
}
|
CJBuchel/UDP_TransferNT
|
UDP_TransferNT/include/Network.h
|
<reponame>CJBuchel/UDP_TransferNT<gh_stars>0
#ifndef NETWORK_H
#define NETWORK_H
#include "Serializer.h"
#include "Socket.h"
namespace UDP_TransferNT {
class Network : public Serializer {
public:
/**
* Network Type
*/
enum class Type {
SERVER = 0,
CLIENT
};
/**
* Connection type
* Meant for client connection to either a specific ip address or any ip address on the same port
*/
enum class ConnectionType {
ANY = 0,
IP_SPECIFIC
};
/**
* Connection Status
*/
enum class ConnectionStatus {
DISCONNECTED = 0,
CONNECTING,
CONNECTED
};
/**
* Network state
*/
enum class State {
UN_INITIALIZED = 0,
IDLE,
RUNNING
};
/**
* Main network, initialize as either server or client with optional override values
*/
Network(Type type, ConnectionType connType, int port = DEFAULT_NT_PORT, const char *ip = DEFAULT_NT_IP) : _type(type), _connType(connType) {
// Set the socket vals
_socket.setPort(port);
_socket.setIP(ip);
DEFAULT_NT_LOGGER("Network Constructed");
}
~Network() {
_socket.killSocket();
DEFAULT_NT_LOGGER("Network Destroyed");
}
Socket &getSocket() {
return _socket;
}
/**
* Initialize connection using defined socket value set by user and constructed network instance
*/
void init() {
while (_connStat != ConnectionStatus::CONNECTED) {
int programValue = 0;
if (_connStat == ConnectionStatus::CONNECTING) {
DEFAULT_NT_LOGGER("Closing Socket, reconnecting...");
_socket.killSocket();
}
_connStat = ConnectionStatus::CONNECTING;
DEFAULT_NT_LOGGER("Opening socket...");
switch (_type) {
case Type::SERVER: // SERVER
if (programValue + _socket.createSocket() != 0) {
DEFAULT_NT_LOGGER("Error creating socket");
} else {
DEFAULT_NT_LOGGER("Created socket");
}
if (_connType == ConnectionType::ANY) {
_socket.prepSocketStructure();
} else if (_connType == ConnectionType::IP_SPECIFIC) {
_socket.prepSocketStructure(false, true);
}
if (programValue + _socket.bindSocket() != 0) {
DEFAULT_NT_LOGGER("Error binding socket");
} else {
DEFAULT_NT_LOGGER("Socket Binded");
}
break; // SERVER END
case Type::CLIENT: // CLIENT
if (programValue + _socket.createSocket(true) != 0) {
DEFAULT_NT_LOGGER("Error creating socket");
} else {
DEFAULT_NT_LOGGER("Socket created");
}
if (_connType == ConnectionType::ANY) {
_socket.prepSocketStructure(true);
} else if (_connType == ConnectionType::IP_SPECIFIC) {
_socket.prepSocketStructure(true, true);
_socket.connectSocket(true);
}
break; // CLIENT END
}
#ifdef NT_UDP_PLATFORM_WINDOWS
DWORD timeout = _socket.getRecvTimeout();
setsockopt(_socket.getSocket(), SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout));
#elif defined(NT_UDP_PLATFORM_UNIX)
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = _socket.getRecvTimeout() * 1000;
setsockopt(_socket.getSocket(), SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv));
#endif
if (programValue == 0) {
// Display the vals
DEFAULT_NT_LOGGER("Network Initialized with values");
DEFAULT_NT_LOGGER("Type: " + std::to_string((int)_type));
DEFAULT_NT_LOGGER("Connection Type: " + std::to_string((int)_connType));
DEFAULT_NT_LOGGER("Port: " + std::to_string(_socket.getPort()));
DEFAULT_NT_LOGGER(_socket.getIP());
DEFAULT_NT_LOGGER("Buffer Size: " + std::to_string(DEFAULT_BUFFER_SIZE));
DEFAULT_NT_LOGGER("Packet size: " + std::to_string(PACKETSIZE));
_connStat = ConnectionStatus::CONNECTED;
_state = State::IDLE;
} else {
DEFAULT_NT_LOGGER("Init Issue, trying again...");
}
}
}
/**
* Reset network
* Closes socket and re-runs the connection process
*/
void reset() {
_state = State::UN_INITIALIZED;
_connStat = ConnectionStatus::CONNECTING;
init();
}
/**
* Raw send
* Send a buffer with max size of the bufferSize
*/
int raw_send(const char buffer[DEFAULT_BUFFER_SIZE], bool disablePrintError = false) {
int programValue = 0;
int sendVal = 0;
if (_connStat == ConnectionStatus::CONNECTED) {
_state = State::RUNNING;
switch (_type) {
case Type::SERVER:
#ifdef NT_UDP_PLATFORM_WINDOWS
if (sendto(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), *_socket.getOtherAddressLength()) == SOCKET_ERROR) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Server Send error windows: " + std::to_string(WSAGetLastError()));
}
programValue = 1;
}
#elif defined(NT_UDP_PLATFORM_UNIX)
if ((sendVal = sendto(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), *_socket.getOtherAddressLength())) < 0) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Server Send error unix: " + std::to_string(sendVal));
}
programValue = 1;
}
#endif
break;
case Type::CLIENT:
#ifdef NT_UDP_PLATFORM_WINDOWS
if (sendto(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), *_socket.getOtherAddressLength()) == SOCKET_ERROR) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Client Send error windows: " + std::to_string(WSAGetLastError()));
}
programValue = 1;
}
#elif defined(NT_UDP_PLATFORM_UNIX)
if ((sendVal = sendto(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), *_socket.getOtherAddressLength())) < 0) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Client Send error unix: " + std::to_string(sendVal));
}
programValue = 1;
}
#endif
break;
}
_state = State::IDLE;
} else {
programValue = 1;
}
return programValue;
}
/**
* Raw receive
* receive a raw buffer with a max buffersize
*/
int raw_recv(char *buffer, bool disablePrintError = false) {
int programValue = 0;
int recvVal = 0;
memset(buffer, 0, DEFAULT_BUFFER_SIZE);
if (_connStat == ConnectionStatus::CONNECTED) {
_state = State::RUNNING;
switch (_type) {
case Type::SERVER:
#ifdef NT_UDP_PLATFORM_WINDOWS
if (recvfrom(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), _socket.getOtherAddressLength()) == SOCKET_ERROR) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Server Recv error windows: " + std::to_string(WSAGetLastError()));
}
programValue = 1;
}
#elif defined(NT_UDP_PLATFORM_UNIX)
if ((recvVal = recvfrom(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), _socket.getOtherAddressLength())) < 0) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Server Recv error unix: " + std::to_string(recvVal));
}
programValue = 1;
}
#endif
break;
case Type::CLIENT:
#ifdef NT_UDP_PLATFORM_WINDOWS
if (recvfrom(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), _socket.getOtherAddressLength()) == SOCKET_ERROR) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Client Recv error windows: " + std::to_string(WSAGetLastError()));
}
programValue = 1;
}
#elif defined(NT_UDP_PLATFORM_UNIX)
if ((recvVal = recvfrom(_socket.getSocket(), buffer, DEFAULT_BUFFER_SIZE, 0, (struct sockaddr *)&_socket.getOtherAddress(), _socket.getOtherAddressLength())) < 0) {
if (!disablePrintError) {
DEFAULT_NT_LOGGER("Client Recv error unix: " + std::to_string(recvVal));
}
programValue = 1;
}
#endif
break;
}
_state = State::IDLE;
} else {
programValue = 1;
}
return programValue;
}
/**
* Send over a serialized datapacket
*/
void dpSend(DataPacket &dp, bool disablePrintError = false) {
if (_connStat == ConnectionStatus::CONNECTED) {
DataPacket dpBuff = dp;
char buffer[DEFAULT_BUFFER_SIZE];
serialize(dpBuff, buffer);
raw_send(buffer, disablePrintError);
}
}
/**
* receive a deserialized datapacket
* Use previously received datapacket as paramater to get streamline data.
* (Stops random zeroed out datapacket from being returned if no datapacket is received)
*/
DataPacket dpRecv(DataPacket dpPrevious = {}, bool disablePrintError = false) {
if (_connStat == ConnectionStatus::CONNECTED) {
DataPacket dpBuffer;
char *recvBuffer = (char *)malloc(DEFAULT_BUFFER_SIZE * sizeof(char));
if (raw_recv(recvBuffer, disablePrintError) == 0) {
deserialize(dpBuffer, recvBuffer);
free(recvBuffer);
return dpBuffer;
}
}
return dpPrevious;
}
private:
Type _type;
ConnectionType _connType{ ConnectionType::ANY };
// Socket
Socket _socket;
// connections and states
ConnectionStatus _connStat{ ConnectionStatus::DISCONNECTED };
State _state{ State::UN_INITIALIZED };
};
}
#endif // NETWORK_H
|
CJBuchel/UDP_TransferNT
|
UDP_TransferNT/include/nt_headers.h
|
#ifndef NT_HEADERS_H
#define NT_HEADERS_H
#include "nt_platform.h"
#include <string>
#include <iostream>
#include <typeinfo>
#ifdef DISABLE_NT_LOGGER
#define DEFAULT_NT_LOGGER(x)
#else
// override if you have a proper logger. E.g spdlog
#ifndef DEFAULT_NT_LOGGER
#define DEFAULT_NT_LOGGER(x) std::cout << x << std::endl
#endif
#endif
#ifndef DEFAULT_NT_IP
#define DEFAULT_NT_IP "127.0.0.1" // local ip address
#endif
#ifndef DEFAULT_NT_PORT
#define DEFAULT_NT_PORT 5801 // official allowed frc ports are 5800 to 5810
#endif
#ifndef DEFAULT_N_TYPEBLOCK
#define DEFAULT_N_TYPEBLOCK 4
#endif
#ifndef DEFAULT_BUFFER_SIZE
#define DEFAULT_BUFFER_SIZE 256 // must be devisable by typeblock size
#endif
#define DATAPACKET_TYPESIZE DEFAULT_BUFFER_SIZE/DEFAULT_N_TYPEBLOCK
// headers for windows socket
#ifdef NT_UDP_PLATFORM_WINDOWS
#include <stdio.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib,"Ws2_32.lib")
#elif defined(NT_UDP_PLATFORM_UNIX)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <tuple>
#endif // nt platform
#endif // NT_HEADERS_H
|
CJBuchel/UDP_TransferNT
|
UDP_TransferNT/include/UDP_TransferNT.h
|
<filename>UDP_TransferNT/include/UDP_TransferNT.h
#ifndef UDP_TRANSFER_NT_H
#define UDP_TRANSFER_NT_H
#include "Network.h"
#endif
|
CJBuchel/UDP_TransferNT
|
UDP_TransferNT/include/Socket.h
|
#ifndef SOCKET_H
#define SOCKET_H
#include "nt_headers.h"
namespace UDP_TransferNT {
/**
* Cross platform socket wrapper. Used as main socket for network.
*/
class Socket {
public:
/**
* Set the port of the socket
*/
void setPort(int port) {
_port = port;
}
/**
* Set the ip of the socket
*/
void setIP(const char *ip) {
_ip = ip;
}
/**
* Get the set port
*/
int getPort() {
return _port;
}
/**
* Get the set ip
*/
const char *getIP() {
return _ip;
}
/**
* Change the timeout value for the receiver (in milliseconds)
*/
void setRecvTimeout(int ms) {
_recvTimeout = ms;
}
/**
* Get the current timeout value for the receiver (in milliseconds)
*/
int getRecvTimeout() {
return _recvTimeout;
}
/**
* Get local address
*/
struct sockaddr_in &getLocalAddress() {
return _si_local;
}
/**
* Get other address
*/
struct sockaddr_in &getOtherAddress() {
return _si_other;
}
#ifdef NT_UDP_PLATFORM_WINDOWS
/**
* Get local address length
*/
int *getLocalAddressLength() { _si_local_len = sizeof(_si_local_len); return &_si_local_len; }
/**
* Get other address length
*/
int *getOtherAddressLength() { _si_other_len = sizeof(_si_other); return &_si_other_len; }
#elif defined(NT_UDP_PLATFORM_UNIX)
/**
* Get local address length
*/
socklen_t *getLocalAddressLength() { _si_local_len = sizeof(_si_local_len); return &_si_local_len; }
/**
* Get other address length
*/
socklen_t *getOtherAddressLength() { _si_other_len = sizeof(_si_other); return &_si_other_len; }
#endif
#ifdef NT_UDP_PLATFORM_WINDOWS
/**
* Get socket (winsock)
*/
SOCKET &getSocket() { return _socket; }
#elif defined(NT_UDP_PLATFORM_UNIX)
/**
* Get socket (int)
*/
int &getSocket() { return _socket; }
#endif
/**
* Create the socket with defined values. Returns 0 on success, 1 for fail
*/
int createSocket(bool client = false) {
_si_other_len = sizeof(_si_other);
// windows create socket
#ifdef NT_UDP_PLATFORM_WINDOWS
if (WSAStartup(MAKEWORD(2,2), &_wsa) != 0) {
DEFAULT_NT_LOGGER("WSA Startup Failed with error: " + std::to_string(WSAGetLastError()));
return 1;
}
if (client) {
if ((_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) {
DEFAULT_NT_LOGGER("Could not create client socket, error: " + std::to_string(WSAGetLastError()));
return 1;
}
} else {
std::cout << "Using server windows " << std::endl;
if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
DEFAULT_NT_LOGGER("Could not create server socket, error: " + std::to_string(WSAGetLastError()));
return 1;
}
}
// unix create socket
#elif defined(NT_UDP_PLATFORM_UNIX)
if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
DEFAULT_NT_LOGGER("Could not create client socket");
return 1;
}
#endif
return 0;
}
/**
* Prepare the socket structure using either client mode or server mode. Along with ip connection type (either specific or any)
*/
void prepSocketStructure(bool client = false, bool ipSpecific = false) {
// Resolve address
if (client) {
_si_other.sin_family = AF_INET;
_si_other.sin_port = htons(_port);
if (ipSpecific) {
#ifdef NT_UDP_PLATFORM_WINDOWS
inet_pton(AF_INET, _ip, &_si_other.sin_addr);
#elif defined(NT_UDP_PLATFORM_UNIX)
_host = (struct hostent *)gethostbyname((char *)_ip);
_si_other.sin_addr = *((struct in_addr *)_host->h_addr);
#endif
} else {
_si_other.sin_addr.s_addr = INADDR_ANY;
}
} else {
_si_local.sin_family = AF_INET;
_si_local.sin_port = htons(_port);
_si_local.sin_addr.s_addr = htonl(INADDR_ANY);
_si_other.sin_family = AF_INET;
_si_other.sin_port = htons(_port);
if (ipSpecific) {
#ifdef NT_UDP_PLATFORM_WINDOWS
inet_pton(AF_INET, _ip, &_si_other.sin_addr);
#elif defined(NT_UDP_PLATFORM_UNIX)
_host = (struct hostent *)gethostbyname((char *)_ip);
_si_other.sin_addr = *((struct in_addr *)_host->h_addr);
#endif
} else {
_si_other.sin_addr.s_addr = INADDR_ANY;
}
}
}
/**
* Bind the socket to the local address
*/
int bindSocket(bool client = false) {
#ifdef NT_UDP_PLATFORM_WINDOWS
if (bind(_socket, (struct sockaddr *)&_si_local, sizeof(_si_local)) == SOCKET_ERROR) {
DEFAULT_NT_LOGGER("Bind failed, error: " + std::to_string(WSAGetLastError()));
return 1;
}
#elif defined(NT_UDP_PLATFORM_UNIX)
if (bind(_socket, (struct sockaddr *)&_si_local, sizeof(_si_local)) < 0) {
DEFAULT_NT_LOGGER("Bind failed");
return 1;
}
#endif
return 0;
}
/**
* Connect to external address socket (for clients)
*/
int connectSocket(bool client = false) {
#ifdef NT_UDP_PLATFORM_WINDOWS
#elif defined(NT_UDP_PLATFORM_UNIX)
if (!_disableConnect) {
if (connect(_socket, (struct sockaddr *)&_si_other, sizeof(_si_other)) < 0) {
DEFAULT_NT_LOGGER("Socket Connect failed");
return 1;
}
}
#endif
return 0;
}
/**
* Disable the connect option for clients (Makes the UDP connection more open)
*/
void disableConnect(bool disable = true) {
_disableConnect = disable;
}
/**
* Kill the socket
* Closes socket and cleans up values
*/
void killSocket() {
#ifdef NT_UDP_PLATFORM_WINDOWS
closesocket(_socket);
WSACleanup();
#elif defined(NT_UDP_PLATFORM_UNIX)
close(_socket);
#endif
}
private:
bool _disableConnect = false;
int _port;
const char *_ip;
int _recvTimeout = 1000; // in ms
struct sockaddr_in _si_local, _si_other; // Server uses both socket addresses. Client uses si_other
#ifdef NT_UDP_PLATFORM_WINDOWS // windows
SOCKET _socket;
WSADATA _wsa;
int _si_local_len, _si_other_len;
#elif defined(NT_UDP_PLATFORM_UNIX) // unix
int _socket;
struct hostent *_host;
socklen_t _si_local_len, _si_other_len; // Server uses both socket addresses. Client uses si_other
#endif
};
}
#endif
|
CJBuchel/UDP_TransferNT
|
UDP_TransferNT/include/nt_platform.h
|
#ifndef NT_PLATFORM_H
#define NT_PLATFORM_H
#ifdef _WIN32
#define NT_UDP_PLATFORM_WINDOWS
#elif defined(__linux__)
#define NT_UDP_PLATFORM_LINUX
#elif defined (__APPLE__) || defined(__MACH__)
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR == 1
#error "IOS simulator is not supported!"
#elif TARGET_OS_IPHONE == 1
#define NT_UDP_PLATFORM_IOS
#error "IOS is not supported!"
#elif TARGET_OS_MAC == 1
#define NT_UDP_PLATFORM_MACOS
#else
#error "Unknown Apple platform!"
#endif
#else
#error "Unknown platform!"
#endif
#endif
#if defined(NT_UDP_PLATFORM_LINUX) || defined(NT_UDP_PLATFORM_MACOS)
#define NT_UDP_PLATFORM_UNIX
#endif
|
CJBuchel/UDP_TransferNT
|
UDP_TransferNT/include/Serializer.h
|
#ifndef SERIALIZER_H
#define SERIALIZER_H
#include "nt_headers.h"
#include "Datapacket.h"
namespace UDP_TransferNT {
class Serializer {
public:
/**
* Serial cycler. Serialize data type arrays [T] into byte stream [V]
*/
template <typename T, typename V>
static T *serialCycler(T *singleDT, V *data, bool reverse = false) {
T *dataType = (T *)data;
for (size_t i = 0; i < (DATAPACKET_TYPESIZE/sizeof(T)); i++) {
if (reverse) {
singleDT[i] = *dataType;
} else {
*dataType = singleDT[i];
}
dataType++;
}
return dataType;
}
/**
* Serialize datapacket into large byte array, returns compiled outdata
*/
static auto *serialize(DataPacket &dp, char *outData) {
auto *t1 = serialCycler(dp.dp.characters, outData, false);
auto *t2 = serialCycler(dp.dp.integers, t1, false);
auto *t3 = serialCycler(dp.dp.booleans, t2, false);
auto *t4 = serialCycler(dp.dp.decimals, t3, false);
return t4;
}
/**
* Deserialize data from large byte array into datapacket, returns completed outdata
*/
static auto *deserialize(DataPacket &dp, char *inData) {
auto *t1 = serialCycler(dp.dp.characters, inData, true);
auto *t2 = serialCycler(dp.dp.integers, t1, true);
auto *t3 = serialCycler(dp.dp.booleans, t2, true);
auto *t4 = serialCycler(dp.dp.decimals, t3, true);
return t4;
}
};
}
#endif
|
CJBuchel/UDP_TransferNT
|
UDP_TransferNT/include/Datapacket.h
|
#ifndef DATAPACKET_H
#define DATAPACKET_H
#include "nt_headers.h"
#define DP_CHECK_SCOPE(x, v, code) if (x > (DATAPACKET_TYPESIZE)/sizeof(v)) { DEFAULT_NT_LOGGER("INDEX OUT OF SCOPE, index: " + std::to_string(x) + ", max index: " + std::to_string((DATAPACKET_TYPESIZE)/sizeof(v))); } else { code }
namespace UDP_TransferNT {
/**
* Datapacket for user data
*/
struct DataPacket {
/**
* Raw datapacket arrays
*/
struct DP {
char characters[(DATAPACKET_TYPESIZE)/sizeof(char)]{0};
int integers[(DATAPACKET_TYPESIZE)/sizeof(int)]{0};
bool booleans[(DATAPACKET_TYPESIZE)/sizeof(bool)]{0};
float decimals[(DATAPACKET_TYPESIZE)/sizeof(float)]{0};
};
DP dp;
/**
* Set character in datapacket using index and value
*/
void setCharacters(unsigned int index, char value) { DP_CHECK_SCOPE(index, value, dp.characters[index] = (char)value;) }
/**
* Set integer in datapacket using index and value
*/
void setIntegers(unsigned int index, int value) { DP_CHECK_SCOPE(index, value, dp.integers[index] = (int)value;) }
/**
* Set boolean in datapacket using index and value
*/
void setBooleans(unsigned int index, bool value) { DP_CHECK_SCOPE(index, value, dp.booleans[index] = (int)value;) }
/**
* Set deceimal value in datapacket using index and value
*/
void setDecimals(unsigned int index, float value) { DP_CHECK_SCOPE(index, value, dp.decimals[index] = (float)value;) }
/**
* Get character from datapacket using index
*/
char getCharacters(int index) { return (char)dp.characters[index]; }
/**
* Get integer from datapacket using index
*/
int getIntegers(int index) { return (int)dp.integers[index]; }
/**
* Get boolean from datapacket using index
*/
bool getBooleans(int index) { return (bool)dp.booleans[index]; }
/**
* Get decimal value from datapacket using index
*/
float getDecimals(int index) { return (float)dp.decimals[index]; }
};
/**
* Complete size of datapacket (should match set buffersize)
*/
#define PACKETSIZE sizeof(DataPacket::DP::characters) + sizeof(DataPacket::DP::integers) + sizeof(DataPacket::DP::booleans) + sizeof(DataPacket::DP::booleans)
}
#endif // DATAPACKET_H
|
jj1bdx/exs64
|
c-example/xorshift64star.c
|
/* Written in 2014 by <NAME> (<EMAIL>)
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>. */
#include <stdint.h>
/* This is a good generator if you're short on memory, but otherwise we
rather suggest to use a xorshift128+ (for maximum speed) or
xorshift1024* (for speed and very long period) generator. */
uint64_t x; /* The state must be seeded with a nonzero value. */
uint64_t next() {
x ^= x >> 12; // a
x ^= x << 25; // b
x ^= x >> 27; // c
return x * 2685821657736338717LL;
}
|
jj1bdx/exs64
|
c-example/test.c
|
/*
* test sequence generator for xorshift64star.c
* Written by <NAME>
* License: CC0 / public domain
* NOTE: use C99 or later
*/
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
uint64_t next(void);
extern uint64_t x;
int main(void)
{
int i;
x = (uint64_t)1234567890123456789ULL;
for (i = 0; i < 1000; i ++) {
printf("next = %" PRIu64 "\n", next());
}
}
|
AIoT-IST/EVA_Show-Case
|
src/plugins/weardetection/gstweardetection.h
|
#ifndef _GST_weardetection_H_
#define _GST_weardetection_H_
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include <opencv2/opencv.hpp>
G_BEGIN_DECLS
#define GST_TYPE_weardetection (gst_weardetection_get_type())
#define GST_weardetection(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_weardetection,Gstweardetection))
#define GST_weardetection_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_weardetection,GstweardetectionClass))
#define GST_IS_weardetection(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_weardetection))
#define GST_IS_weardetection_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_weardetection))
typedef struct _Gstweardetection Gstweardetection;
typedef struct _GstweardetectionClass GstweardetectionClass;
typedef struct _GstweardetectionPrivate GstweardetectionPrivate;
struct _Gstweardetection
{
GstVideoFilter base_weardetection;
/*< private >*/
GstweardetectionPrivate *priv;
cv::Mat srcMat;
long eventTick;
long lastEventTick;
};
struct _GstweardetectionClass
{
GstVideoFilterClass base_weardetection_class;
};
GType gst_weardetection_get_type (void);
G_END_DECLS
#endif
|
AIoT-IST/EVA_Show-Case
|
src/plugins/geofence/gstgeofencebase.h
|
<filename>src/plugins/geofence/gstgeofencebase.h
#ifndef _GST_GEOFENCEBASE_H_
#define _GST_GEOFENCEBASE_H_
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include <opencv2/opencv.hpp>
G_BEGIN_DECLS
#define GST_TYPE_GEOFENCEBASE (gst_geofencebase_get_type())
#define GST_GEOFENCEBASE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_GEOFENCEBASE,GstGeofencebase))
#define GST_GEOFENCEBASE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_GEOFENCEBASE,GstGeofencebaseClass))
#define GST_IS_GEOFENCEBASE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_GEOFENCEBASE))
#define GST_IS_GEOFENCEBASE_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_GEOFENCEBASE))
typedef struct _GstGeofencebase GstGeofencebase;
typedef struct _GstGeofencebaseClass GstGeofencebaseClass;
typedef struct _GstGeoFenceBasePrivate GstGeofencebasePrivate;
struct _GstGeofencebase
{
GstVideoFilter base_geofencebase;
/*< private >*/
GstGeofencebasePrivate *priv;
cv::Mat srcMat;
long eventTick;
long lastEventTick;
};
struct _GstGeofencebaseClass
{
GstVideoFilterClass base_geofencebase_class;
};
GType gst_geofencebase_get_type (void);
G_END_DECLS
#endif
|
AIoT-IST/EVA_Show-Case
|
src/plugins/geofence/gstgeofencefoot.h
|
#ifndef _GST_GEOFENCEFOOT_H_
#define _GST_GEOFENCEFOOT_H_
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include <opencv2/opencv.hpp>
G_BEGIN_DECLS
#define GST_TYPE_GEOFENCEFOOT (gst_geofencefoot_get_type())
#define GST_GEOFENCEFOOT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_GEOFENCEFOOT,Gstgeofencefoot))
#define GST_GEOFENCEFOOT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_GEOFENCEFOOT,GstgeofencefootClass))
#define GST_IS_GEOFENCEFOOT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_GEOFENCEFOOT))
#define GST_IS_GEOFENCEFOOT_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_GEOFENCEFOOT))
typedef struct _Gstgeofencefoot Gstgeofencefoot;
typedef struct _GstgeofencefootClass GstgeofencefootClass;
typedef struct _GstgeofencefootPrivate GstgeofencefootPrivate;
struct _Gstgeofencefoot
{
GstVideoFilter base_geofencefoot;
/*< private >*/
GstgeofencefootPrivate *priv;
cv::Mat srcMat;
long eventTick;
long lastEventTick;
};
struct _GstgeofencefootClass
{
GstVideoFilterClass base_geofencefoot_class;
};
GType gst_geofencefoot_get_type (void);
G_END_DECLS
#endif
|
AIoT-IST/EVA_Show-Case
|
src/plugins/assembly/gstpartassembly.h
|
#ifndef _GST_PARTASSEMBLY_H_
#define _GST_PARTASSEMBLY_H_
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include "assembly_utils/Status.h"
using namespace BASIC_INFORMATION;
using namespace PROGRESS;
using namespace PREPARE;
G_BEGIN_DECLS
#define GST_TYPE_PARTASSEMBLY (gst_partassembly_get_type())
#define GST_PARTASSEMBLY(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PARTASSEMBLY,Gstpartassembly))
#define GST_PARTASSEMBLY_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PARTASSEMBLY,GstpartassemblyClass))
#define GST_IS_PARTASSEMBLY(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PARTASSEMBLY))
#define GST_IS_PARTASSEMBLY_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PARTASSEMBLY))
typedef struct _Gstpartassembly Gstpartassembly;
typedef struct _GstpartassemblyClass GstpartassemblyClass;
typedef struct _GstpartassemblyPrivate GstpartassemblyPrivate;
struct _Gstpartassembly
{
GstVideoFilter base_partassembly;
GstpartassemblyPrivate *priv;
cv::Mat srcMat;
BOM bom;
bool targetTypeChecked;
long startTick;
long alertTick;
double runningTime;
bool partContainerIsEmpty;
int lastTotalNumber;
};
struct _GstpartassemblyClass
{
GstVideoFilterClass base_partassembly_class;
};
GType gst_partassembly_get_type (void);
G_END_DECLS
#endif
|
AIoT-IST/EVA_Show-Case
|
src/plugins/assembly/assembly_utils/Status.h
|
<reponame>AIoT-IST/EVA_Show-Case
#ifndef __DEMO_STATUS_H__
#define __DEMO_STATUS_H__
#include <vector>
#include <opencv2/opencv.hpp>
namespace BASIC_INFORMATION
{
class BOM
{
public:
BOM(std::vector<std::string> nameVector, std::vector<int> NumberVector, std::vector<int> OrderVector);
~BOM();
public:
std::vector<std::string> NameVector;
std::vector<int> NumberVector;
std::vector<int> OrderVector;
};
}
namespace PROGRESS
{
enum class Prepare {Empty, NotReady, DisOrdered, Ready, Assembly};
enum class Assembly {Empty, Assembling, AssemblyOK};
class PrepareStatus
{
public:
static PrepareStatus* GetInstance();
void ReleaseInstance();
void SetStatus(Prepare s);
Prepare GetStatus();
const char* GetStatusString(Prepare value)
{
switch (value) {
case Prepare::Empty:
return "Empty";
case Prepare::NotReady:
return "NotReady";
case Prepare::DisOrdered:
return "DisOrdered";
case Prepare::Ready:
return "Ready";
case Prepare::Assembly:
return "Assembly";
}
return "Not Defined";
}
protected:
Prepare status;
private:
static PrepareStatus* singletonInstance;
PrepareStatus(): status(Prepare::NotReady){};
PrepareStatus(const PrepareStatus&);
PrepareStatus& operator=(const PrepareStatus&);
};
}
namespace PREPARE
{
class PartNumber
{
public:
PartNumber(int requiredNumber);
~PartNumber();
int GetCurrentNumber();
void SetNumber(int n);
void ClearStatus();
bool CheckNumber();
private:
int currentNumber;
int requiredNumber;
};
class PositionInBox
{
public:
PositionInBox(int requiredIndex);
~PositionInBox();
void ClearStatus();
void UpdateIndex(int currentIndex);
int GetCurrentIndex();
int GetRequiredIndex();
bool CheckPosition();
private:
int requiredIndex;
int currentIndex;
};
class Material
{
public:
Material(int requiredNumber, int requiredIndex);
~Material();
void Add(int x1, int y1, int x2, int y2, float score);
std::vector<int> GetPosition(int index);
std::vector<int> GetRectangle(int index);
std::vector<cv::Point> GetObjectPoints(int index);
int GetObjectNumber();
void SetPartNumber(int n);
void SetIndexInBox(int order);
int GetValidatePartCurrentNumber();
int GetValidatePartCurrentIndex();
int GetPartRequiredIndex();
int GetBestScoreObjectIndex();
void ClearStatus();
bool IsReady();
bool CheckNumber();
bool CheckOrder();
private:
PartNumber *partNumber;
PositionInBox *positionInBox;
std::vector<std::vector<int>> positions;
std::vector<float> scoreVector;
};
}
#endif /* __DEMO_STATUS_H__ */
|
AIoT-IST/EVA_Show-Case
|
src/utils/utils.h
|
std::vector<std::string> split(std::string inputString);
GstAdBatchMeta* gst_buffer_get_ad_batch_meta(GstBuffer* buffer);
std::string return_current_time_and_date();
std::string round2String(double d, int r);
|
AIoT-IST/EVA_Show-Case
|
src/plugins/assembly/gstpartpreparation.h
|
#ifndef _GST_PARTPREPARATION_H_
#define _GST_PARTPREPARATION_H_
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include "assembly_utils/Status.h"
using namespace BASIC_INFORMATION;
using namespace PROGRESS;
using namespace PREPARE;
G_BEGIN_DECLS
#define GST_TYPE_PARTPREPARATION (gst_partpreparation_get_type())
#define GST_PARTPREPARATION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PARTPREPARATION,GstPartpreparation))
#define GST_PARTPREPARATION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PARTPREPARATION,GstPartPreparationClass))
#define GST_IS_PARTPREPARATION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PARTPREPARATION))
#define GST_IS_PARTPREPARATION_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PARTPREPARATION))
typedef struct _GstPartpreparation GstPartpreparation;
typedef struct _GstPartpreparationClass GstPartpreparationClass;
typedef struct _GstPartPreparationPrivate GstPartpreparationPrivate;
struct _GstPartpreparation
{
GstVideoFilter base_partpreparation;
GstPartpreparationPrivate *priv;
cv::Mat srcMat;
BOM bom;
PrepareStatus* prepareStatus;
long baseTick;
double prepareStartTime;
double prepareEndTime;
double runningTime;
int emptyCounter;
};
struct _GstPartpreparationClass
{
GstVideoFilterClass base_partpreparation_class;
};
GType gst_partpreparation_get_type (void);
G_END_DECLS
#endif
|
systems-nuts/popcorn-compiler-with-modified-stackmaps
|
lib/musl-1.1.18/include/arch.h
|
/**
* Defines architectures used by multiple components in tools & supporting libraries.
*
* Author: <NAME> <<EMAIL>>
* Date: 12/12/2017
*/
#ifndef _ARCH_H
#define _ARCH_H
enum arch {
ARCH_UNKNOWN = -1,
ARCH_AARCH64,
ARCH_X86_64,
ARCH_POWERPC64,
NUM_ARCHES
};
#endif /* _ARCH_H */
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/Common/OMIdentityContext.h
|
<gh_stars>10-100
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMObject.h"
/**
* The IdentityContext class provides mechanism to collect Device specific
* claims, which can be sent to OIC during authentication flow to provide
* additional layer of security.
*/
@interface OMIdentityContext : NSObject
@property (nonatomic, strong) NSArray *identityContextClaims;
@property (nonatomic, strong) NSString *applicationID;
/**
* Returns true if the attributes collected from the device is compliant with
* the security policy configured in OIC for this application.
*
* @return true if the device is compliant with the configured policy;
false otherwise.
* @param policies The policies that need to be evaluated in the device.
*/
- (BOOL)evaluatePolicy:(NSDictionary*)policies;
/**
* Returns the requested claims collected from the device in a JSON format
* @return Claims collected from the device in JSON format.
* @param Claim attributes
*/
- (NSDictionary *)deviceClaims:(NSArray*) claimAttributes;
/**
* Refresh the claims information which are already collected
*/
- (void)refresh;
/**
* Returns claims in the format given below, which needs to be appended
* osType=type&osVer=ver&clientSDKVersion=1.0&serviceDomain=default
*/
- (NSString *)claimsURLForApplicationID: (NSString *)applicationID
serviceDomain: (NSString *)domain
oicURL: (NSString *)oicURL;
/**
* Returns claims in the format required by device registration and
* authentication service
*/
- (NSDictionary *)getJSONDictionaryForAuthentication:(NSDictionary *)jailBreakDetectionPolicy;
/**
* Returns the singleton instance of OMIdentityContext class
*/
+ (id)sharedInstance;
@end
///////////////////////////////////////////////////////////////////////////////
// End of OMIdentityContext Header File
///////////////////////////////////////////////////////////////////////////////
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2Library/IDMMobileSDKv2Library.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import "OMMobileSecurityService.h"
#import "OMMobileSecurityConfiguration.h"
#import "OMCredential.h"
#import "OMCredentialStore.h"
#import "OMCertInfo.h"
#import "OMCertService.h"
#import "OMAuthenticationContext.h"
#import "OMAuthenticationRequest.h"
#import "OMAuthenticationChallenge.h"
#import "OMObject.h"
#import "OMDefinitions.h"
#import "OMCryptoService.h"
#import "OMToken.h"
#import "OMOTPService.h"
#import "NSData+OMBase64.h"
#import "NSData+OMBase32.h"
#import "OMAuthenticator.h"
#import "OMPinAuthenticator.h"
#import "OMTouchIDAuthenticator.h"
#import "OMDefaultAuthenticator.h"
#import "OMAuthData.h"
#import "OMLocalAuthenticationManager.h"
#import "OMAuthenticationManager.h"
#import "OMErrorCodes.h"
#import "OMDataSerializationHelper.h"
#import "OMJailBrokenDetector.h"
#import "OMReachability.h"
#import "OMBiometricAuthenticator.h"
#import "OMClassicCredential.h"
@interface IDMMobileSDKv2Library : NSObject
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/Common/OMTimer/NSTimer+OMTimes.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
// Got this from: http://stackoverflow.com/questions/347219/how-can-i-programmatically-pause-an-nstimer
#import <Foundation/Foundation.h>
@interface NSTimer (OMTimes)
@property (nonatomic, readonly) NSDate *oldFireDate;
@property (nonatomic) NSNumber *timeDeltaNumber;
- (void)pauseOrResume;
- (BOOL)isPaused;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMOAMOAuthClientAssertionService.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMAuthenticationService.h"
#import "OMOAMOAuthConfiguration.h"
@interface OMOAMOAuthClientAssertionService : OMAuthenticationService
@property (nonatomic, weak) OMOAMOAuthConfiguration *config;
@property (nonatomic, strong) NSString *authCode;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/Common/NSData+OMBase32.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
void *OMBase32Decode(const char *inputBuffer,
size_t length,
size_t *outputLength);
char *OMBase32Encode(const void *inputBuffer,
size_t length,
bool separateLines,
size_t *outputLength);
@interface NSData (OMBase32)
{
}
+ (NSData *)dataFromBase32String:(NSString *)aString;
- (NSString *)base32EncodedString;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMLogoutService.h
|
<gh_stars>10-100
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMMobileSecurityService.h"
#import "OMAuthenticationManager.h"
#import "OMAuthenticationService.h"
#import "OMCredentialStore.h"
@interface OMLogoutService : NSObject
@property(nonatomic, weak) OMMobileSecurityService *mss;
@property(nonatomic, weak) NSThread *callerThread;
-(id)initWithMobileSecurityService:(OMMobileSecurityService *)mss;
-(void)performLogout:(BOOL)clearRegistrationHandles;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/SecureStorage/OMUtilities.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@interface OMUtilities : NSObject
+ (NSString *)keystoreDirectoryName;
+ (NSString *)localAuthDirectoryName;
+ (NSString *)omaDirectoryPath;
+ (NSString *)secureDirectoryName;
+ (NSString *)filePathForfile:(NSString*)fileName inDirectory:(NSString*)directory
error:(NSError **)error;
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
returningResponse:(__autoreleasing NSURLResponse **)responsePtr
error:(__autoreleasing NSError **)errorPtr;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMWKWebViewCookieHandler.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface OMWKWebViewCookieHandler : NSObject
+ (void)cookiesForVisitedHosts:(NSArray*)visitedHosts completionHandler:
(void (^)(NSArray<WKWebsiteDataRecord *> *))completionHandler;
+ (void)clearWkWebViewCashForUrls:(NSArray*)visitedUrls completionHandler:(void (^) (void))completionBlock;
+ (void)clearWkWebViewCookiesForUrls:(NSArray*)visitedUrls completionHandler:(void (^) (void))completionBlock;
+ (void)deleteCookieFromWKHTTPStore:(NSHTTPCookie*)cookie;
@end
NS_ASSUME_NONNULL_END
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/KeyManager/OMKeyStore.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@class OMKeyStore;
@interface OMKeyStore : NSObject
- (id)initWithKeyStoreId:(NSString *)storeId kek:(NSData*)kek;
- (NSData *)defaultKey;
- (NSData *)getKey:(NSString *)keyId;
- (void)createKey:(NSString*)keyId overwrite:(BOOL)overwrite error:(NSError **)error;
- (BOOL)isValidKek:(NSData*)kek;
- (void)updateKeyEncryptionKey:(NSData*)newKek;
- (void)copyKeysFromKeyStore:(OMKeyStore*)keyStore;
- (void)unloadKeys;
- (void)loadKeys;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/LocalAuthentication/OMTouchIDAuthenticator.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import "OMAuthenticator.h"
typedef void (^OMFallbackAuthenticationCompletionBlock)(BOOL authenticated);
__attribute__ ((deprecated))
__deprecated_msg("This Protocol is deprecated Use OMBiometricFallbackDelegate class instead.")
@protocol OMTouchIDFallbackDelegate <NSObject>
@required
- (void)didSelectFallbackAuthentication:(NSError *)fallBackReason completionHandler:
(OMFallbackAuthenticationCompletionBlock)handler;
@end
__attribute__ ((deprecated))
__deprecated_msg("This Class is deprecated Use OMBiometricAuthenticator class instead.")
@interface OMTouchIDAuthenticator : OMAuthenticator
@property (nonatomic, weak) id<OMTouchIDFallbackDelegate> delegate;
@property (nonatomic, copy) NSString *localizedFallbackTitle;
@property (nonatomic, copy) NSString *localizedTouchIdUsingReason NS_DEPRECATED_IOS(8.0, 11.0, "Use localizedBiometricUsingReason");;
@property (nonatomic, copy) NSString *localizedBiometricUsingReason;
+ (BOOL)canEnableTouchID:(NSError *__autoreleasing*)error NS_DEPRECATED_IOS(8.0, 11.0, "Use canEnableBiometricAuthentication");
+ (BOOL)canEnableBiometricAuthentication:(NSError **)error;
+ (BiometryType)biometricType;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMOpenIDCConfiguration.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMOAuthConfiguration.h"
typedef void (^OIDCDiscoveryCallback)(NSError *_Nullable discoveryError);
@interface OMOpenIDCConfiguration :OMOAuthConfiguration
@property (nonatomic, strong) NSDictionary *properties;
@property (nonatomic, strong) NSString *issuer;
@property (nonatomic, strong) NSSet *claims;
@property (nonatomic, strong) NSURL *revocationEndpoint;
@property (nonatomic, strong) NSURL *userInfoEndpoint;
@property (nonatomic, strong) NSURL *discoveryEndpoint;
@property (nonatomic, strong) NSString *discoveryJSON;
- (BOOL)needDiscovery;
- (void)startDiscoveryWithCompletion:(OIDCDiscoveryCallback _Null_unspecified)completion;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMOpenIDCAuthenticationService.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMOAuthAuthenticationService.h"
typedef void (^OMOpenIDCUserInfoCallback)(NSMutableDictionary *_Nullable userinfo,
NSError *_Nullable error);
@interface OMOpenIDCAuthenticationService : OMOAuthAuthenticationService
@property (nonatomic, strong) NSString *_Nullable idToken;
- (void)userInfoWithCompletion:(OMOpenIDCUserInfoCallback _Null_unspecified)completion;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/CredentialStoreService/OMCredentialStore.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@class OMCredential,OMAuthenticationContext;
@interface OMCredentialStore : NSObject
{
@private
CFTypeRef defaultKeychainAccessible;
}
/**
* @brief Returns the shared OMCredentialStore Object
*
* @return OMCredentialStore object
*/
+ (OMCredentialStore*)sharedCredentialStore;
/**
* @brief sets the keychain data protection type
*
* @param keychain data ProtectionType
*/
- (void)setKeychainDataProtectionType:(CFTypeRef )keychainDataProtection;
/**
* @brief Saves the credential
*
* @param credentail - OMCredentail Object to be saved
*
* @param key - Key of the KeyChainItem for savng
*
* @return Error object if there is error while saving credential otherwise nil
*/
- (NSError *)saveCredential:(OMCredential*)credential forKey:(NSString*)key;
/**
* @brief Returns the credential
*
* @param key - Key of the KeyChainItem to be retrieved
*
* @return OMCredential object
*/
- (OMCredential *)getCredential:(NSString*)key;
/**
* @brief Deletes an entry in KeyChainItem
*
* Delets all details stored in KeyChainItem against given key
*
* @param key - key using secure details are stored
* @return NSError object if the KeyChainItem key passed is nil
*/
- (NSError *)deleteCredential:(NSString*)key;
/**
* @brief sets the local authenticator instanceId
*
* @param instance id name
*/
- (void)setLocalAuthenticatorInstanceId:(NSString *)instanceId;
- (NSUInteger)deleteCredentialForProperties:(NSDictionary *)properties;
/**
* @brief Saves the OMAuthenticationContext
*
* @param context - OMAuthenticationContext Object to be saved
*
* @param key - Key for saving for data
*
* @return Error object if there is error while saving credential otherwise nil
*/
- (NSError *)saveAuthenticationContext:(OMAuthenticationContext*)context
forKey:(NSString*)key;
/**
* @brief Returns the OMAuthenticationContext
*
* @param key - Key of the data to be retrieved
*
* @return OMAuthenticationContext object
*/
- (OMAuthenticationContext *)retriveAuthenticationContext:(NSString*)key;
/**
* @brief Deletes an entry in secure store
*
* Delets all details stored in secure store against given key
*
* @param key - key using secure details are stored
* @return NSError object if the secure store key passed is nil
*/
- (NSError *)deleteAuthenticationContext:(NSString*)key;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMMobileSecurityConfiguration.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMDefinitions.h"
@interface OMMobileSecurityConfiguration : NSObject
@property (nonatomic) int idleTimeout;
@property (nonatomic) int sessionTimeout;
@property (nonatomic) int percentageToIdleTimeout;
@property (nonatomic) int authenticationRetryCount;
@property (nonatomic, strong) NSString *appName;
@property (nonatomic) BOOL rememberCredAllowed;
@property (nonatomic) BOOL rememberUsernameAllowed;
@property (nonatomic) BOOL autoLoginAllowed;
@property (nonatomic) BOOL autoLoginDefault;
@property (nonatomic) BOOL rememberCredDefault;
@property (nonatomic) BOOL rememberUsernameDefault;
@property (nonatomic, strong) NSString *identityDomain;
@property (nonatomic) BOOL identityDomainInHeader;
@property (nonatomic, strong) NSString *identityDomainHeaderName;
@property (nonatomic, strong) NSDictionary *customHeaders;
@property (nonatomic) BOOL provideIdentityDomainToMobileAgent;
@property (nonatomic) BOOL presentIdentityOnDemand;
@property (nonatomic) BOOL presentClientCertIdentityOnDemand;
@property (nonatomic) OMCryptoScheme cryptoScheme;
@property (nonatomic) BOOL sendCustomHeadersLogout;
@property (nonatomic) BOOL sendAuthHeaderLogout;
@property (nonatomic, strong) NSString *localAuthenticatorIntanceId;
@property (nonatomic, strong) NSString *authKey;
@property (nonatomic, strong) NSDictionary *mobileAgentCustomHeaders;
@property (nonatomic, assign) BOOL sessionActiveOnRestart;
+ (NSDictionary *)parseConfigurationURL: (NSURL *)configURL
persistInUserDefaults: (BOOL)persist
withKey: (NSString *)key;
+ (NSDictionary *)parseConfigurationURL: (NSURL *)configURL
persistInUserDefaults: (BOOL)persist
withKey: (NSString *)key
andFilters:(NSSet *) filters;
+ (NSDictionary *)parseConfigurationURLWithURLComponents: (NSURL *)configURL
persistInUserDefaults: (BOOL)persist
withKey: (NSString *)key
andFilters: (NSSet *) filters;
- (id)initWithProperties:(NSDictionary *)properties error:(NSError **)error;
- (BOOL)isValidString:(NSString*)str;
- (BOOL)isValidUrl:(NSString *)url;
+ (BOOL)isValidNumber:(id)object inRange:(NSRange)range;
+ (BOOL)isValidUnsignedNumber:(id)object;
+ (BOOL)boolValue:(id)object;
- (NSDictionary *)getIdentityClaims;
+ (BOOL)isWKWebViewAvailable;
+ (NSDictionary *)initializationConfigurationForKey:(NSString *)key;
+ (BOOL)deleteInitializationConfigurationForKey:(NSString *)key;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/JailBroken/OMJailBrokenDetector.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@interface OMJailBrokenDetector : NSObject
+ (BOOL)isDeviceJailBroken;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMOAuthConfiguration.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMMobileSecurityConfiguration.h"
#import "OMObject.h"
enum{
OMOAuthResourceOwner,
OMOAuthAuthorizationCode,
OMAOAuthClientCredential,
OMOAuthImplicit,
OMOAuthAssertion,
OMOAuthOAMCredential
};
typedef NSUInteger OMOAuthGrantType;
enum
{
OMBrowserModeEmbedded = 1,
OMBrowserModeExternal = 2,
OMBrowserModeSafariVC = 3
};
typedef NSUInteger OMBrowserMode;
@interface OMOAuthConfiguration : OMMobileSecurityConfiguration
@property (nonatomic) OMOAuthGrantType grantType;
@property (nonatomic, strong) NSURL *tokenEndpoint;
@property (nonatomic, strong) NSURL *authEndpoint;
@property (nonatomic, strong) NSString *clientSecret;
@property (nonatomic, strong) NSString *clientId;
@property (nonatomic, strong) NSSet *scope;
@property (nonatomic, strong) NSURL *redirectURI;
@property (nonatomic, strong) NSString *state;
@property (nonatomic, strong) NSString *clientAssertion;
@property (nonatomic, strong) NSString *clientAssertionType;
@property (nonatomic) BOOL includeClientHeader;
@property (nonatomic, strong) NSString *userAssertionType;
@property (nonatomic, strong) NSString *userAssertion;
@property (nonatomic, strong) NSURL *logoutURL;
@property (nonatomic,) BOOL offlineAuthAllowed;
@property (nonatomic) OMConnectivityMode connectivityMode;
@property (nonatomic) OMBrowserMode browserMode;
@property (nonatomic) BOOL enablePkce;
@property (nonatomic) BOOL isClientRegistrationRequired;
@property (nonatomic) NSURL *clientRegistrationEndpoint;
@property (nonatomic, strong) NSString *loginHint;
@property (nonatomic, strong) NSURL *discoverEndpoint;
- (NSInteger)setConfiguration:(NSDictionary *) properties;
-(void)parseConfigData:(NSDictionary *)json;
- (NSURL*)discoveryUrl;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMConnectionHandler.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@interface OMConnectionHandler : NSObject<NSURLSessionDataDelegate,
NSURLSessionDataDelegate>
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSMutableData *data;
- (void) invokeHTTPRequestAsynchronouslyForURL: (NSString *)url
withPayload: (NSString *)payload
header: (NSDictionary *)header
requestType: (NSString *)type
convertDataToJSON: (BOOL)convertToJSON
completionHandler:(void (^)(id data, NSURLResponse *response, NSError *error))completionHandler;
- (id)invokeHTTPRequestSynchronouslyForURL:(NSString *)url
withPayload:(NSString *)payload
header:(NSDictionary *)header
requestType:(NSString *)type
convertDataToJSON:(BOOL)convertToJSON
returningResponse:(NSURLResponse **)response
andError:(NSError **)error;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMClientCertAuthenticationService.h
|
<gh_stars>10-100
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMAuthenticationService.h"
@class OMAuthenticationService,OMClientCertConfiguration;
@interface OMClientCertAuthenticationService :
OMAuthenticationService<NSURLSessionDelegate>
@property(nonatomic, weak) OMClientCertConfiguration *configuration;
@property(nonatomic, assign) BOOL authChallengeReceived;
@property(nonatomic, strong) NSURLSessionDataTask *sessionDataTask;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMOAuthAuthenticationService.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMAuthenticationService.h"
#import "OMOAuthConfiguration.h"
@class OMAuthorizationGrant;
@interface OMOAuthAuthenticationService : OMAuthenticationService {
}
@property (nonatomic, strong) OMAuthorizationGrant *grantFlow;
@property (nonatomic, strong) NSString *accessToken;
@property (nonatomic) NSUInteger expiryTimeInSeconds;
@property (nonatomic, strong) NSString *refreshToken;
@property (nonatomic) NSUInteger nextStep;
@property (nonatomic) BOOL frontChannelRequestDone;
@property (nonatomic, strong) NSString *userName;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, weak) OMOAuthConfiguration *config;
@property (nonatomic) NSUInteger retryCount;
- (void)openURLInBrowser:(NSURL *)url;
- (void)processOAuthResponse:(NSDictionary *)urlQueryDict;
- (void)performAuthentication:(NSMutableDictionary *)authData
error:(NSError *__autoreleasing *)error;
- (void)performBackChannelRequest:(NSDictionary *)data;
- (void)setAuthContext;
- (void)sendFinishAuthentication:(id)object;
+ (NSError *)oauthErrorFromResponse:(NSDictionary *)response
andStatusCode:(NSInteger)code;
- (NSDictionary *)parseFrontChannelResponse:(NSURL *)url;
- (void)storeOfflineCredential:(OMAuthenticationContext *)ctx;
- (void)setGrantFlowManually;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/LocalAuthentication/OMPinAuthenticator.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import "OMAuthenticator.h"
@class OMSecureStorage, OMKeyStore;
@interface OMPinAuthenticator : OMAuthenticator
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/LocalAuthentication/OMBiometricAuthenticator.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import <LocalAuthentication/LocalAuthentication.h>
#import "OMAuthenticator.h"
NS_ASSUME_NONNULL_BEGIN
typedef void (^OMFallbackAuthenticationCompletionBlock)(BOOL authenticated);
@protocol OMBiometricFallbackDelegate <NSObject>
@required
- (void)didSelectFallbackAuthentication:(NSError *)fallBackReason completionHandler:
(OMFallbackAuthenticationCompletionBlock)handler;
@end
@interface OMBiometricAuthenticator : OMAuthenticator
@property (nonatomic, weak, nullable) id<OMBiometricFallbackDelegate> delegate;
@property (nonatomic, copy) NSString *localizedFallbackTitle;
@property (nonatomic, copy) NSString *localizedBiometricUsingReason;
+ (BOOL)canEnableBiometricAuthentication:(NSError **)error;
+ (BiometryType)biometricType;
@end
NS_ASSUME_NONNULL_END
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/Common/OMCryptoService.h
|
<filename>src/ios/sdk/IDMMobileSDKv2/Common/OMCryptoService.h
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
/*!
@enum OMCryptoAlgorithm
@discussion Hashing and symmetric key encryption algorithms supported
by OMCryptoService.
@constant OMAlgorithmMD5 Hashing MD5, without salt
@constant OMAlgorithmSHA1 Hashing SHA-1, without salt
@constant OMAlgorithmSHA224 Hashing SHA-224, without salt
@constant OMAlgorithmSHA256 Hashing SHA-256, without salt
@constant OMAlgorithmSHA384 Hashing SHA-384, without salt
@constant OMAlgorithmSHA512 Hashing SHA-512, without salt
@constant OMAlgorithmSMD5 Hashing MD5, with salt
@constant OMAlgorithmSSHA1 Hashing SHA-1, with salt
@constant OMAlgorithmSSHA224 Hashing SHA-224, with salt
@constant OMAlgorithmSSHA256 Hashing SHA-256, with salt
@constant OMAlgorithmSSHA384 Hashing SHA-384, with salt
@constant OMAlgorithmSSHA512 Hashing SHA-512, with salt
@constant OMAlgorithmAES128 Symmetric key encryption with Advanced
Encryption Standard 128 bit block. Supported
key sizes 16, 24, 32.
@constant OMAlgorithmDES Data Encryption Standard. Block size 8.
Key size 8.
@constant OMAlgorithm3DES Triple DES. Block size 8. Key size 24.
*/
enum
{
// Hashing
OMAlgorithmMD5,
OMAlgorithmSHA1,
OMAlgorithmSHA224,
OMAlgorithmSHA256,
OMAlgorithmSHA384,
OMAlgorithmSHA512,
// Salted Hashing
OMAlgorithmSMD5,
OMAlgorithmSSHA1,
OMAlgorithmSSHA224,
OMAlgorithmSSHA256,
OMAlgorithmSSHA384,
OMAlgorithmSSHA512,
// Symmetric key encryption
OMAlgorithmAES128,
OMAlgorithmDES,
OMAlgorithm3DES,
};
typedef NSUInteger OMCryptoAlgorithm;
/*!
@enum OMCryptoPadding
@discussion Padding for use in various symmetric and keypair crypto
algorithms.
@warning When an operation is tried with an unsupported padding scheme,
error code 33 - Unknown or unsupported padding is returned.
@constant OMPaddingNone Perform no padding. Can be used with
symmetric key algorithms when input is a
multiple of the algorithm's block size. For
keypair algorithms this padding scheme
specifies that data be processed as-is.
Can be used with all symmetric key and
keypair algorithms. This is the default value
when no other padding is chosen.
@constant OMPaddingPKCS7 PKCS7 padding scheme. Used only with
symmetric key encryption/decryption
algorithms.
@constant OMPaddingPKCS1 PKCS1 padding scheme for use in keypair
algorithms.
@constant OMPaddingOAEP OAEP padding scheme for use in keypair wrap/
unwrap algorithms.
@constant OMPaddingPKCS1SHA1 PKCS1 padding and SHA1 hashing scheme for use
in keypair sign/verify operations.
@constant OMPaddingPKCS1SHA224 PKCS1 padding and SHA224 hashing scheme for
use in keypair sign/verify operations.
Available from iOS 6.0. On earlier iOS
versions throws error code 23 - Input value
invalid.
@constant OMPaddingPKCS1SHA256 PKCS1 padding and SHA256 hashing scheme for
use in keypair sign/verify operations.
Available from iOS 6.0. On earlier iOS
versions throws error code 23 - Input value
invalid.
*/
enum
{
OMPaddingNone,
OMPaddingPKCS7,
OMPaddingPKCS1,
OMPaddingOAEP,
OMPaddingPKCS1SHA1,
OMPaddingPKCS1SHA224,
OMPaddingPKCS1SHA256,
OMPaddingPKCS1SHA384,
OMPaddingPKCS1SHA512
};
typedef uint32_t OMCryptoPadding;
/*!
@enum OMCryptoMode
@discussion Modes of operation for symmetric key algorithms. Modes are
used with block ciphers like AES, DES and 3DES.
@constant OMModeCBC Cipher-block Chaining mode. This is the
default mode chosen when OMCryptoMode is not
specified.
@constant OMModeECB Eletronic codebook mode.
*/
enum
{
OMModeCBC,
OMModeECB,
};
typedef uint32_t OMCryptoMode;
/*!
@enum OMCryptoKeyType
@discussion Key types for use in keypair algorithms (asymmetric key).
Additional key types will be added based on availability of support from
underlying platform.
@constant OMKeyTypeRSA RSA
*/
enum
{
OMKeyTypeRSA,
};
typedef uint32_t OMCryptoKeyType;
/** OMCryptoService provides common crypto features like hashing,
symmetric key cipher and keypair operations.
*/
@interface OMCryptoService : NSObject
{
}
/** @name Hashing */
#pragma mark -
#pragma mark Hashing
/**
* Generate cryptographic hash using MD5 algorithm.
*
* @param plainText Data to be hashed.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. Returns nil if an
* error is encountered.
*/
+ (NSData *) MD5HashData:(NSData *)plainText
outError:(NSError **)error;
/**
* Generate cryptographic hash using MD5 algorithm with an optional salt.
* This is a variation of MD5HashData that returns base64 encoded output.
* The algorithm name and salt if any are also prefixed to the output.
*
* @param plainText Data to be hashed.
* @param saltLength Generate salt of given bit length and add to data
* before hashing. Must be a multiple of 4. Can be set to 0
* to perform hashing without a salt.
* @param outSalt Returns the salt, if generated.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. The output data is
* Base64 encoded. If a salt is generated, the output is
* prefixed with salt. The algorithm name is also prefixed
* to the output as {MD5} or {SaltedMD5}. Returns nil if an
* error is encountered.
*/
+ (NSString *) MD5HashAndBase64EncodeData:(NSData *)plainText
withSaltOfBitLength:(NSUInteger)saltLength
outSalt:(NSString **)outSalt
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA1 algorithm.
*
* @param plainText Data to be hashed.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. Returns nil if an
* error is encountered.
*/
+ (NSData *) SHA1HashData:(NSData *)plainText
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA1 algorithm with an optional salt.
* This is a variation of SHA1HashData that returns base64 encoded output.
* The algorithm name and salt if any are also prefixed to the output.
*
* @param plainText Data to be hashed.
* @param saltLength Generate salt of given bit length and add to data
* before hashing. Must be a multiple of 4. Can be set to 0
* to perform hashing without a salt.
* @param outSalt Returns the salt, if generated.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. The output data is
* Base64 encoded. If a salt is generated, the output is
* prefixed with salt. The algorithm name is also prefixed
* to the output as {SHA-1} or {SaltedSHA-1}. Returns nil if
* an error is encountered.
*/
+ (NSString *) SHA1HashAndBase64EncodeData:(NSData *)plainText
withSaltOfBitLength:(NSUInteger)saltLength
outSalt:(NSString **)outSalt
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA224 algorithm.
*
* @param plainText Data to be hashed.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. Returns nil if an
* error is encountered.
*/
+ (NSData *) SHA224HashData:(NSData *)plainText
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA224 algorithm with an optional salt.
* This is a variation of SHA224HashData that returns base64 encoded output.
* The algorithm name and salt if any are also prefixed to the output.
*
* @param plainText Data to be hashed.
* @param saltLength Generate salt of given bit length and add to data
* before hashing. Must be a multiple of 4. Can be set to 0
* to perform hashing without a salt.
* @param outSalt Returns the salt, if generated.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. The output data is
* Base64 encoded. If a salt is generated, the output is
* prefixed with salt. The algorithm name is also prefixed
* to the output as {SHA-224} or {SaltedSHA-224}. Returns nil
* if an error is encountered.
*/
+ (NSString *) SHA224HashAndBase64EncodeData:(NSData *)plainText
withSaltOfBitLength:(NSUInteger)saltLength
outSalt:(NSString **)outSalt
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA256 algorithm.
*
* @param plainText Data to be hashed.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. Returns nil if an
* error is encountered.
*/
+ (NSData *) SHA256HashData:(NSData *)plainText
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA256 algorithm with an optional salt.
* This is a variation of SHA256HashData that returns base64 encoded output.
* The algorithm name and salt if any are also prefixed to the output.
*
* @param plainText Data to be hashed.
* @param saltLength Generate salt of given bit length and add to data
* before hashing. Must be a multiple of 4. Can be set to 0
* to perform hashing without a salt.
* @param outSalt Returns the salt, if generated.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. The output data is
* Base64 encoded. If a salt is generated, the output is
* prefixed with salt. The algorithm name is also prefixed
* to the output as {SHA-256} or {SaltedSHA-256}. Returns nil
* if an error is encountered.
*/
+ (NSString *) SHA256HashAndBase64EncodeData:(NSData *)plainText
withSaltOfBitLength:(NSUInteger)saltLength
outSalt:(NSString **)outSalt
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA384 algorithm.
*
* @param plainText Data to be hashed.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. Returns nil if an
* error is encountered.
*/
+ (NSData *) SHA384HashData:(NSData *)plainText
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA384 algorithm with an optional salt.
* This is a variation of SHA384HashData that returns base64 encoded output.
* The algorithm name and salt if any are also prefixed to the output.
*
* @param plainText Data to be hashed.
* @param saltLength Generate salt of given bit length and add to data
* before hashing. Must be a multiple of 4. Can be set to 0
* to perform hashing without a salt.
* @param outSalt Returns the salt, if generated.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. The output data is
* Base64 encoded. If a salt is generated, the output is
* prefixed with salt. The algorithm name is also prefixed
* to the output as {SHA-384} or {SaltedSHA-384}. Returns nil
* if an error is encountered.
*/
+ (NSString *) SHA384HashAndBase64EncodeData:(NSData *)plainText
withSaltOfBitLength:(NSUInteger)saltLength
outSalt:(NSString **)outSalt
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA512 algorithm.
*
* @param plainText Data to be hashed.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. Returns nil if an
* error is encountered.
*/
+ (NSData *) SHA512HashData:(NSData *)plainText
outError:(NSError **)error;
/**
* Generate cryptographic hash using SHA512 algorithm with an optional salt.
* This is a variation of SHA512HashData that returns base64 encoded output.
* The algorithm name and salt if any are also prefixed to the output.
*
* @param plainText Data to be hashed.
* @param saltLength Generate salt of given bit length and add to data
* before hashing. Must be a multiple of 4. Can be set to 0
* to perform hashing without a salt.
* @param outSalt Returns the salt, if generated.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash value when successful. The output data is
* Base64 encoded. If a salt is generated, the output is
* prefixed with salt. The algorithm name is also prefixed
* to the output as {SHA-512} or {SaltedSHA-512}. Returns nil
* if an error is encountered.
*/
+ (NSString *) SHA512HashAndBase64EncodeData:(NSData *)plainText
withSaltOfBitLength:(NSUInteger)saltLength
outSalt:(NSString **)outSalt
outError:(NSError **)error;
/**
* Generate salt for use in cryptographic hash generation.
*
* @param length Length of salt in bits. Must be a multiple of 4.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return The generated salt as Hex (or Base16) encoded string.
* Returns nil if an error is encountered.
*/
+ (NSString *) generateSaltOfBitLength:(NSUInteger)length
outError:(NSError **)error;
/**
* Generate cryptographic hash of input with or without salt.
*
* @param plainText Data to be hashed.
* @param salt Salt for the hash. If a non-salted algorithm is chosen
* salt must be nil. If a salted algorithm is chosen salt
* must be provided.
* @param algorithm The hashing algorithm to use for hashing. Refer
* OMCryptoAlgorithm for values.
* @param appendSalt Prefix the given salt to output. Only effective
* when base64EncodeOutput is YES. Ignored if
* base64EncodeOutput is NO.
* @param base64 If Yes, output is Base64 encoded.
* @param prefixAlgorithm Prefix algorithm name to output. Only
* effective when base64EncodeOutput is YES. Ignored if
* base64EncodeOutput is NO. Taking SHA1 as example the
* algorithm name prefix is done with the format: {SHA-1}.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns hash as NSData object if base64EncodeOutput is NO
* Returns hash a NSString object if base64EncodeOutput is
* YES. Returns nil if an error is encountered.
*/
+ (id) hashData:(NSData *)plainText
withSalt:(NSString *)salt
algorithm:(OMCryptoAlgorithm)algorithm
appendSaltToOutput:(BOOL)appendSalt
base64Encode:(BOOL)base64
prefixOutputWithAlgorithmName:(BOOL)prefixAlgorithm
outError:(NSError **)error;
/** @name Symmetric key */
#pragma mark -
#pragma mark Symmetric key
/**
* Encrypt data with symmetric key using AES algorithm and PKCS7 padding
* in CBC mode.
*
* @param plainText The data to be encrypted.
* @param symmetricKey Symmetric key for encryption. Length must
* match the key length required by the algorithm.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns encrypted data if encryption is successful.
* Returns nil if an error is encountered.
*/
+ (NSData *) encryptData:(NSData *)plainText
withSymmetricKey:(NSData *)symmetricKey
outError:(NSError **)error;
/**
* Encrypt data with symmetric key using AES128 algorithm and PKCS7 padding
* in CBC mode. A symmetric key of requested length can be generated and used
* for encryption.
*
* @param plainText The data to be encrypted.
* @param keyLength Generate symmetric key of given length.
* Length must not be 0.
* @param key On return contains the generated symmetric key.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns encrypted data if encryption is successful.
* Returns nil if an error is encountered.
*/
+ (NSData *) encryptData:(NSData *)plainText
withSymmetricKeyOfLength:(NSUInteger)keyLength
outSymmetricKey:(NSData **)key
outError:(NSError **)error;
/**
* Decrypt data with symmetric key using AES128 algorithm and PKCS7 padding
* in CBC mode.
*
* @param cipherText The data to be decrypted.
* @param symmetricKey Symmetric key to use for decryption.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns decrypted data if decryption is successful.
* Returns nil if an error is encountered.
*/
+ (NSData *) decryptData:(NSData *)cipherText
withSymmetricKey:(NSData *)symmetricKey
outError:(NSError **)error;
/**
* Generate a key for use in symmetric encryption and decryption operations.
*
* @param length Length of key in bytes to be generated. Any length can be
* generated though when used, it must match the requirements
* of the algorithm.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return The resultant hash or nil if an error is encountered.
*/
+ (NSData *) generateSymmetricKeyOfLength:(NSUInteger)length
outError:(NSError **)error;
/**
* Generate a key for use in symmetric encryption and decryption operations.
*
* @param passPhrase A string that is used in deriving symmetric key
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return The resultant hash or nil if an error is encountered.
*/
+ (NSData *) generateSymmetricKeyWithPassPhrase:(NSString *) passPhrase
outError:(NSError **) error;
/**
* Encrypt data with symmetric key.
*
* @param plainText The data to be encrypted.
* @param symmetricKey Symmetric key for encryption. Length must be
* match the key length required by the algorithm.
* @param iv Optional, initialization vector for encryption.
* The length must be the same as the block size of the
* selected algorithm. Ignored if OMModeECB is used. In the
* default mode OMModeCBC if no initializationVector is
* provided a value of all 0's is used.
* @param algorithm The symmetric encryption algorithm to use for encryption.
* Refer OMCryptoAlgorithm. The supported algorithms are
* AES128, DES and 3DES.
* @param padding Padding to be used when plainText is not a multiple of
* algorithm's block size. Refer OMCryptoPadding for values.
* OMPaddingPKCS7 is the only padding type supported.
* @param mode Encryption mode. The default is OMOModeCBC.
* @param base64 If YES, output data is Base64 encoded.
* @param prefix Prefix algorithm name to output. Only
* effective when base64EncodeOutput is YES. Ignored if
* base64EncodeOutput is NO. Taking AES128 algorithm as an
* example the prefix format is {AES}.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns encrypted data as NSData object if
* base64EncodeOutput is NO. Returns NSString object if
* base64EncodeOutput is YES. Returns nil if an error is
* encountered.
*/
+ (id) encryptData:(NSData *)plainText
withSymmetricKey:(NSData *)symmetricKey
initializationVector:(NSData *)iv
algorithm:(OMCryptoAlgorithm)algorithm
padding:(OMCryptoPadding)padding
mode:(OMCryptoMode)mode
base64EncodeOutput:(BOOL)base64
prefixOutputWithAlgorithmName:(BOOL)prefix
outError:(NSError **)error;
/**
* Decrypt data with symmetric key.
*
* @param cipherText The data to be decrypted.
* @param symmetricKey Symmetric key required for decryption. Length must
* match the key length required by the algorithm.
* @param iv Initialization vector for decryption. The length
* must be the same as the block size of the selected
* algorithm. Ignored if OMModeECB is used. In the default
* mode OMModeCBC if no initializationVector is provided a
* value of all 0's is used.
* @param algorithm The symmetric encryption algorithm to use for decryption.
* @param padding Padding. Use the same value used for encryption.
* @param mode Mode used for encryption. OMModeCBC is the default.
* @param prefix If YES, algorithm name prefix is
* removed before decryption. Taking AES128 algorithm as an
* example the expected prefix format is {AES}.
* @param base64 If YES, input data is Base64 decoded before
* decryption.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns decrypted data when successful.
* Returns nil if an error is encountered.
*/
+ (NSData *) decryptData:(id)cipherText
withSymmetricKey:(NSData *)symmetricKey
initializationVector:(NSData *)iv
algorithm:(OMCryptoAlgorithm)algorithm
padding:(OMCryptoPadding)padding
mode:(OMCryptoMode)mode
isInputPrefixedWithAlgorithmName:(BOOL)prefix
isInputBase64Encoded:(BOOL)base64
outError:(NSError **)error;
/** @name Keypair */
#pragma mark -
#pragma mark Key pair
/**
* Generate key pair and store it in keychain.
*
* @param length The length of the key in bits.
* @param tagPrefix When storing the generated key pair, sets the
* ApplicationTag attribute value to identify the key pair.
* The value is the combination of the given prefix and
* ".private" or ".public" respectively to refer to the
* private or public key. The private key is stored with tag
* <keychainTagPrefix>.private and the public
* key is stored with tag <keychainTagPrefix>.public. For
* example, when the keychainTagPrefix is
* "com.yourcompany.appauth", the private key will be stored
* with tag "com.yourcompany.appauth.private".
* @param protection Protect the keychain item at this level. Takes the same
* values accepted by OM_PROP_KEYCHAIN_DATA_PROTECTION.
* If nil, the default value chosen is
* OM_KEYCHAIN_DATA_ACCESSIBLE_WHEN_UNLOCKED_THIS_DEVICE_ONLY
* @param error Pointer to pointer to NSError object to which error will
* be copied, if an error is encountered. This parameter is
* mandatory to unambiguously know if verification failed or
* if an error was encountered.
* @return Returns YES if key pair is successfully generated and
* stored. Returns NO if key pair generation fails or if
* an error is encountered.
*/
+ (BOOL) generateAndStoreKeyPairOfBitLength:(NSUInteger)length
keychainTagPrefix:(NSString *)tagPrefix
protection:(NSString *)protection
outError:(NSError **)error;
/**
* Generate key pair and store it in keychain.
*
* @param length The length of the key in bits.
* @param keyType Key pair type. Refer OMCryptoKeyType
* @param tagPrefix When storing the generated key pair, sets the
* ApplicationTag attribute value to identify the key pair.
* The value is the combination of the given prefix and
* ".private" or ".public" respectively to refer to the
* private or public key. The private key is stored with tag
* <keychainTagPrefix>.private and the public
* key is stored with tag <keychainTagPrefix>.public. For
* example, when the keychainTagPrefix is
* "com.yourcompany.appauth", the private key will be stored
* with tag "com.yourcompany.appauth.private".
* @param protection Protect the keychain item at this level. Takes the same
* values accepted by OM_PROP_KEYCHAIN_DATA_PROTECTION.
* If nil, the default value chosen is
* OM_KEYCHAIN_DATA_ACCESSIBLE_WHEN_UNLOCKED_THIS_DEVICE_ONLY
* @param error Pointer to pointer to NSError object to which error will
* be copied, if an error is encountered. This parameter is
* mandatory to unambiguously know if verification failed or
* if an error was encountered.
* @return Returns YES if key pair is successfully generated and
* stored. Returns NO if key pair generation fails or if
* an error is encountered.
*/
+ (BOOL) generateAndStoreKeyPairOfBitLength:(NSUInteger)length
keyType:(OMCryptoKeyType)keyType
keychainTagPrefix:(NSString *)tagPrefix
protection:(NSString *)protection
outError:(NSError **)error;
/**
* Retrieve public key bits from keychain.
*
* @param tagPrefix Retrieve the stored public key in keychain based on the
* value of ApplicationTag attribute. The value of the
* attribute is the combination of the given prefix and
* the string ".public". For example, when the TagPrefix is
* "com.yourcompany.appauth", the public key with the tag
* "com.yourcompany.appauth.public" is picked.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns public key data on success or nil on failure.
*/
+ (NSData *) publicKeyFromKeychainWithTagPrefix:(NSString *)tagPrefix
outError:(NSError **)error;
+ (NSData *) privateKeyFromKeychainWithTagPrefix:(NSString *)tagPrefix
outError:(NSError **)error;
/**
* Delete key pair from keychain.
*
* @param tagPrefix Delete a stored key pair in keychain based on the value of
* ApplicationTag attribute. The value of the attribute is
* the combination of TagPrefix and string ".public" or
* ".private". For example, when the TagPrefix is
* "com.yourcompany.appauth", the public key with tag
* "com.yourcompany.appauth.public" and the private
* key with tag "com.yourcompany.appauth.private" is deleted.
* @param error If not nil, on return this points to an error object when
* an error is encountered. This parameter is
* mandatory to unambiguously know if verification failed or
* if an error was encountered.
* @return Returns YES on success. Returns NO if key item is not
* found or if an error was encountered.
*/
+ (BOOL) deleteKeyPairFromKeychainWithTagPrefix:(NSString *)tagPrefix
outError:(NSError **)error;
/**
* Sign data using stored private key.
*
* @param plainText The data to be signed.
* @param prefix Sign with the stored private key in keychain
* identified with the value of ApplicationTag attribute. The
* value of the attribute is the combination of the given
* prefix and the string ".public". For example, when the
* TagPrefix is "com.yourcompany.appauth", the public key
* with the tag "com.yourcompany.appauth.public" is picked.
* @param padding Padding and hashing algorithm to use for
* signing. Refer OMCryptoPadding for values.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns signature data on success or nil on failure.
*/
+ (NSData *) signData:(NSData *)plainText
withPrivateKeyTagPrefix:(NSString *)prefix
paddingAndHashingScheme:(OMCryptoPadding)padding
outError:(NSError **)error;
/**
* Verify signature using stored public key.
*
* @param plainText The data to be verified.
* @param signature Signature bytes to verify the data with.
* @param prefix Verify with the stored public key in keychain
* identified with the value of ApplicationTag attribute. The
* value of the attribute is the combination of the given
* prefix and the string ".public". For example, when the
* TagPrefix is "com.yourcompany.appauth", the public key
* with the tag "com.yourcompany.appauth.public" is picked.
* @param padding Padding and hashing algorithm used when
* signing. Refer OMCryptoPadding for values.
* @param error Pointer to pointer to NSError object to which error to be
* copied, if there is an error. This parameter is mandatory
* to unambiguously know if verification failed or an
* error was encountered.
* @return Returns YES, if data is successfully verified.
* Returns NO, if verification failed or an error was
* encountered.
*/
+ (BOOL) verifyData:(NSData *)plainText
withSignature:(NSData *)signature
publicKeyTagPrefix:(NSString *)prefix
paddingAndHashingScheme:(OMCryptoPadding)padding
outError:(NSError **)error;
/**
* Wrap a key (typically symmetric key) with a stored public key.
*
* @param key The key to be wrapped. The maximum length is
* dependent on the key size and the padding used.
* @param prefix Encrypt with the stored public key in keychain
* identified by the value of ApplicationTag attribute. The
* value of the attribute is a combination of the given
* prefix and the string ".public". For example, when the
* TagPrefix is "com.yourcompany.appauth", the public key
* with tag "com.yourcompany.appauth.public" is picked.
* @param padding Padding to use for encryption. Refer OMCryptoPadding for
* values.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns wrapped symmetric key on success
* or nil on failure.
*/
+ (NSData *) wrapKeyData:(NSData *)key
withPublicKeyTagPrefix:(NSString *)prefix
padding:(OMCryptoPadding)padding
outError:(NSError **)error;
/**
* Unwrap a wrapped key (typically symmetric key) with a stored private key.
*
* @param key The wrapped key to unwrap.
* @param prefix Identify the stored key in keychain based on
* the value of ApplicationTag attribute. The value of the
* attribute is the combination of the given prefix and the
* string ".private". For example, when the TagPrefix is
* "com.yourcompany.appauth", the private key is searched for
* with tag "com.yourcompany.appauth.private".
* @param padding Padding used during encryption.
* Refer OMCryptoPadding for values.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns unwrapped symmetric key on success
* or nil on failure.
*/
+ (NSData *) unwrapKeyData:(NSData *)key
withPrivateKeyTagPrefix:(NSString *)prefix
padding:(OMCryptoPadding)padding
outError:(NSError **)error;
/**
* Generates a secure random number with given number of digits.
*
* @param digits Number of digits in the generated random number. Maximum
* number of digit can be 10
* @return Returns a random number with given number of digits and -1
if number of digits passed is greater than 10
*
*/
+ (long)secureRandomNumberOfDigits:(int)digits;
/**
* Generates a symmetric encryption key of specified size using PBKDF2.
*
* @param passphrase String containing passphrase input to PBKDF2
* @param salt String containing salt to be used to generate key
* @param hashAlgorithm OMCryptoAlgorithm specifying the hashing algorithm to be
* used with PBKDF2.
* @param iteration Number of iterations of PBKDF2 to genarate the key
* @param keySize The size of the key to be generated
* @param outError Refrence to a NSError object that will contain any error
* while generating the key
* @return NSData containing the symmetric encryption key
*/
+(NSData *)generatePBKDF2EncryptionKeywithPassphrase:(NSString *)passphrase
salt:(NSString *)salt
hashAlgorithm:(OMCryptoAlgorithm)algorithm
iteration:(NSUInteger)iterations
keySize:(NSUInteger)keySize
outError:(NSError **)error;
/**
* Genarates random NSData of specified length.
*
* @param length Length in bytes that specified the number of random bytes to be
* generated.
* @return NSData containing random bytes of specified length.
*/
+ (NSData *)randomDataOfLength:(size_t)length;
// Get Private Key Ref from keychain store
/**
* Retrieve Private keyref from keychain.
*
* @param tagPrefix Retrieve the stored private key in keychain based on the
* value of ApplicationTag attribute. The value of the
* attribute is the combination of the given prefix and
* the string ".private". For example, when the TagPrefix is
* "com.yourcompany.appauth", the public key with the tag
* "com.yourcompany.appauth.private" is picked.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns Private keyref key data on success or nil on failure.
*/
+ (SecKeyRef) privateKeyRefWithTagPrefix:(NSString *)prefix
outError:(NSError **)error;
/**
* Retrieve public KeyRef from keychain.
*
* @param tagPrefix Retrieve the stored public key in keychain based on the
* value of ApplicationTag attribute. The value of the
* attribute is the combination of the given prefix and
* the string ".public". For example, when the TagPrefix is
* "com.yourcompany.appauth", the public key with the tag
* "com.yourcompany.appauth.public" is picked.
* @param error If not nil, on return this points to an error object when
* an error is encountered.
* @return Returns Public keyref key data on success or nil on failure.
*/
+ (SecKeyRef) publicKeyRefWithTagPrefix:(NSString *)prefix
outError:(NSError **)error;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/Common/OMTimer/OMTimer.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class OMTimer;
@class OMTimeEvent;
typedef void (^OMTimerCompletionBlock)(OMTimer *timeline);
@interface OMTimer : NSObject
{
NSTimer *_mainTimer;
NSTimeInterval _startTime;
NSTimeInterval _pausedTime;
NSMutableArray *_events;
NSMutableArray *_eventTimers;
NSInteger _loop;
}
@property (nonatomic, assign) NSTimeInterval duration;
@property (nonatomic, assign) BOOL willLoop; // Default to NO
@property (nonatomic, assign) BOOL autoPauseWhenAppGoesBackground; // Default to NO
@property (nonatomic, assign) NSTimeInterval tickPeriod;
@property (nonatomic, readonly) NSArray *events;
@property (nonatomic, copy) OMTimerCompletionBlock completionBlock;
@property (nonatomic, readonly) NSTimeInterval currentTime;
@property (nonatomic, readonly) NSInteger currentLoopCount;
@property (nonatomic, readonly) BOOL isRunning;
@property (nonatomic, readonly) BOOL hasStarted;
- (void)start;
- (void)pause;
- (void)resume;
- (void)stop;
- (void)skipForwardSeconds:(NSTimeInterval)seconds;
- (void)clear;
- (NSTimeInterval)remainingTime;
#pragma mark Time Events
// Adding or removing events while timeline is running won't work
- (void)addEvent:(OMTimeEvent *)event;
- (void)removeEvent:(OMTimeEvent *)event;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMAuthenticationService.h
|
<gh_stars>10-100
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMMobileSecurityService.h"
#import "OMAuthenticationRequest.h"
#import "OMAuthenticationDelegate.h"
#import "OMAuthenticationChallenge.h"
@class OMMobileSecurityConfiguration;
@interface OMAuthenticationService : NSObject
@property (nonatomic, weak) OMMobileSecurityService *mss;
@property (nonatomic, weak) OMAuthenticationRequest *request;
@property (nonatomic, strong) NSThread *callerThread;
@property (nonatomic, strong) OMAuthenticationContext *context;
@property (nonatomic, weak) id<OMAuthenticationDelegate> delegate;
@property (nonatomic, strong) OMAuthenticationChallenge *challenge;
@property (nonatomic, strong) NSError *error;
@property (nonatomic, strong) NSDictionary *authResponse;
@property (nonatomic, strong) NSMutableDictionary *authData;
@property(nonatomic) BOOL maxRetryError;
@property (nonatomic, strong) dispatch_semaphore_t requestPauseSemaphore;
-(id)initWithMobileSecurityService:(OMMobileSecurityService *)mss
authenticationRequest:(OMAuthenticationRequest *)authReq
delegate:(id<OMAuthenticationDelegate>)delegate;
-(void)performAuthentication:(NSMutableDictionary *)authData
error:(NSError **)error;
-(BOOL)isInputRequired:(NSMutableDictionary *)authData;
-(BOOL)isRequiredTokens:(NSSet *)tokens presentFor:(NSArray *)visitedHosts;
-(NSString *)protectPassword:(NSString *)password
cryptoScheme:(NSUInteger)scheme
outError:(NSError **)error;
-(BOOL) verifyPassword:(NSString *)userPassword
withProtectedPassword:(NSString *)protectedPassword
outError:(NSError **)error;
/**
* Populates a dictionary sent by individual authentication service with user
* credentials and user preferences.
*
* @param authnData Dictiornay that will be populated with credentials and
* preferences
* @return void
*/
- (void)retrieveRememberCredentials:(NSMutableDictionary *) authnData;
/**
* Persists user credentials in keychain
*
* @param authnData Dictionary that has user credentials and preferences
* @return void
*/
- (void)storeRememberCredentials:(NSMutableDictionary *) authnData;
/**
* Persists user prefernces in NSUserDefaults
* @param authnData Dictionary that has user preferences
* @return void
*/
- (void)storeRememberCredentialsPreference:(NSDictionary *) authnData;
- (BOOL) shouldPerformAutoLogin:(NSDictionary *)authnData;
+ (NSError *)setErrorObject:(NSDictionary *)errorDict
withErrorCode:(NSUInteger)code;
+ (NSUInteger)getErrorCodeForError:(NSString *)error;
-(void)sendFinishAuthentication:(id)object;
- (void)cancelAuthentication;
- (BOOL)isMaxRetryReached:(NSInteger)previousFaliureCount maxRetryCount:
(NSInteger)maxRetryCount;
- (void)resetMaxRetryCount;
-(BOOL)isMaxRetryReached:(NSUInteger)maxRetry;
- (NSString *)maskPassword:(NSString *)password;
- (NSString *)unMaskPassword:(NSString *)password;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/Common/OMClientCertChallangeHandler.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@interface OMClientCertChallangeHandler : NSObject
+ (OMClientCertChallangeHandler*)sharedHandler;
- (void)doServerTrustForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
challengeReciver:(id)reciver
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
NSURLCredential *credential))completionHandler;
- (void)doClientTrustForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
challengeReciver:(id)reciver
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
NSURLCredential *credential))completionHandler;
- (void)doServerTrustSynchronouslyForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
challengeReciver:(id)reciver
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
NSURLCredential *credential))completionHandler;
- (void)doClientTrustSynchronouslyForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
challengeReciver:(id)reciver
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
NSURLCredential *credential))completionHandler;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/LocalAuthentication/OMAuthenticator.h
|
<reponame>x-and/cordova-plugin-oracle-idm-auth
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@class OMKeyStore,OMAuthData,OMSecureStorage;
typedef enum : NSUInteger
{
OMAuthenticationPolicyPin
} OMAuthenticationPolicy;
typedef NS_ENUM(NSInteger, BiometryType)
{
/// The device does not support biometry.
BiometryTypeNone,
/// The device supports Touch ID.
BiometryTypeTouchID,
/// The device supports Face ID.
BiometryTypeFaceID ,
};
@interface OMAuthenticator : NSObject
@property (nonatomic, strong) OMKeyStore *keyStore;
@property (nonatomic, strong) OMSecureStorage *secureStorage;
@property (nonatomic, assign) BOOL isAuthenticated;
@property (nonatomic, strong) NSString *instanceId;
- (id)initWithInstanceId:(NSString *)instanceId error:(NSError **)error;
- (void)setAuthData:(OMAuthData *)authData error:(NSError **)error;
- (void)deleteAuthData:(NSError **)error;
- (void)updateAuthData:(OMAuthData *)currentAuthData newAuthData:
(OMAuthData *)newAuthData error:(NSError **)error;
- (BOOL)authenticate:(OMAuthData*)authData error:(NSError**)error;
- (void)copyKeysFromKeyStore:(OMKeyStore*)keyStore;
- (BOOL)isAuthDataSet;
- (void)inValidate;
- (NSInteger)authDataLength;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMAuthenticationChallenge.h
|
<filename>src/ios/sdk/IDMMobileSDKv2/OMAuthenticationChallenge.h
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
enum
{
OMChallengeUsernamePassword,
OMChallengeClientCert,
OMChallengeServerTrust,
OMChallengeExternalBrowser,
OMChallengeEmbeddedBrowser,
OMChallengeEmbeddedSafari,
OMChallengeInvalidRedirect
};
typedef NSUInteger OMChallengeType;
enum
{
OMProceed,
OMCancel
};
typedef NSUInteger OMChallengeResponse;
@interface OMAuthenticationChallenge : NSObject
@property (nonatomic, strong) NSDictionary *authData;
@property (nonatomic) OMChallengeType challengeType;
@property (nonatomic, copy) __block void(^authChallengeHandler)
(NSDictionary *authData,OMChallengeResponse response );
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/Common/OMTimer/OMTimeEvent.h
|
<gh_stars>10-100
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@class OMTimer;
@class OMTimeEvent;
typedef void (^timeEventBlock)(OMTimeEvent *event, OMTimer *timer);
@interface OMTimeEvent : NSObject
@property (nonatomic, copy) timeEventBlock eventBlock;
@property (nonatomic, assign) NSTimeInterval time;
@property (nonatomic, assign) BOOL willRepeat; // Default to NO
+ (OMTimeEvent *)eventAtTime:(NSTimeInterval)time withEventBlock:(timeEventBlock)completionBlock;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMAuthenticationRequest.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMObject.h"
@interface OMAuthenticationRequest : NSObject
@property(nonatomic) OMConnectivityMode connectivityMode;
@property (nonatomic, strong) NSString *identityDomain;
@property (nonatomic) BOOL forceAuth;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMAuthenticationManager.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
#import "OMMobileSecurityConfiguration.h"
#import "OMAuthenticationService.h"
#import "OMAuthenticationDelegate.h"
@class OMMobileSecurityService;
@interface OMAuthenticationManager : NSObject<OMAuthenticationDelegate>
@property (nonatomic, weak) OMMobileSecurityService *mss;
@property (nonatomic, strong) NSMutableDictionary *authData;
@property (nonatomic, strong) OMAuthenticationService *curentAuthService;
@property (nonatomic, strong) OMAuthenticationRequest *request;
@property (nonatomic, assign) BOOL isAuthRequestInProgress;
-(id)initWithMobileSecurityService:(OMMobileSecurityService *)mss
authenticationRequest:(OMAuthenticationRequest *)authReq;
-(void)startAuthenticationProcess;
-(void)cancelAuthentication;
-(void)sendAuthenticationContext:(OMAuthenticationContext *)context
error:(NSError *)error;
@end
|
x-and/cordova-plugin-oracle-idm-auth
|
src/ios/sdk/IDMMobileSDKv2/OMToken.h
|
/**
* Copyright (c) 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
#import <Foundation/Foundation.h>
@interface OMToken : NSObject<NSCoding,NSCopying>
{
@protected
NSString *_tokenName;
NSSet *_tokenScopes;
NSString *_tokenValue;
NSDate *_sessionExpiryDate;
NSDate *_tokenIssueDate;
int _expiryTimeInSeconds;
NSString *_refreshToken;
NSString *_tokenType;
}
@property (nonatomic, strong) NSString *tokenName;
@property (nonatomic, strong) NSSet *tokenScopes;
@property (nonatomic, strong) NSDate *sessionExpiryDate;
@property (nonatomic, strong) NSDate *tokenIssueDate;
@property (nonatomic, strong) NSString *tokenValue;
@property (nonatomic) int expiryTimeInSeconds;
@property (nonatomic, strong) NSString *refreshToken;
@property (nonatomic, strong) NSString *tokenType;
- (BOOL)isTokenValid;
@end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.