text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef UINPUTEVENTHANDLER_H
#define UINPUTEVENTHANDLER_H
#include "baseeventhandler.h"
#include "../qtx11keymapper.h"
#include <springmousemoveinfo.h>
#include <joybuttonslot.h>
class UInputEventHandler : public BaseEventHandler
{
Q_OBJECT
public:
explicit UInputEventHandler(QObject *parent = 0);
~UInputEventHandler();
virtual bool init();
virtual bool cleanup();
virtual void sendKeyboardEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseEvent(int xDis, int yDis);
virtual void sendMouseAbsEvent(int xDis, int yDis, int screen);
virtual void sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height);
virtual void sendMouseSpringEvent(int xDis, int yDis);
virtual QString getName();
virtual QString getIdentifier();
virtual void printPostMessages();
virtual void sendTextEntryEvent(QString maintext);
protected:
int openUInputHandle();
void setKeyboardEvents(int filehandle);
void setRelMouseEvents(int filehandle);
void setSpringMouseEvents(int filehandle);
void populateKeyCodes(int filehandle);
void createUInputKeyboardDevice(int filehandle);
void createUInputMouseDevice(int filehandle);
void createUInputSpringMouseDevice(int filehandle);
void closeUInputDevice(int filehandle);
void write_uinput_event(int filehandle, unsigned int type,
unsigned int code, int value, bool syn=true);
int keyboardFileHandler;
int mouseFileHandler;
int springMouseFileHandler;
QString uinputDeviceLocation;
signals:
public slots:
private slots:
#ifdef WITH_X11
void x11ResetMouseAccelerationChange();
#endif
};
#endif // UINPUTEVENTHANDLER_H
``` | /content/code_sandbox/src/eventhandlers/uinputeventhandler.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 496 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <qt_windows.h>
#include <cmath>
#include "winsendinputeventhandler.h"
#include <winextras.h>
#include <antkeymapper.h>
WinSendInputEventHandler::WinSendInputEventHandler(QObject *parent) :
BaseEventHandler(parent)
{
}
bool WinSendInputEventHandler::init()
{
return true;
}
bool WinSendInputEventHandler::cleanup()
{
return true;
}
void WinSendInputEventHandler::sendKeyboardEvent(JoyButtonSlot *slot, bool pressed)
{
int code = slot->getSlotCode();
INPUT temp[1] = {};
unsigned int scancode = WinExtras::scancodeFromVirtualKey(code, slot->getSlotCodeAlias());
int extended = (scancode & WinExtras::EXTENDED_FLAG) != 0;
int tempflags = extended ? KEYEVENTF_EXTENDEDKEY : 0;
temp[0].type = INPUT_KEYBOARD;
//temp[0].ki.wScan = MapVirtualKey(code, MAPVK_VK_TO_VSC);
temp[0].ki.wScan = scancode;
temp[0].ki.time = 0;
temp[0].ki.dwExtraInfo = 0;
temp[0].ki.wVk = code;
temp[0].ki.dwFlags = pressed ? tempflags : (tempflags | KEYEVENTF_KEYUP); // 0 for key press
SendInput(1, temp, sizeof(INPUT));
}
void WinSendInputEventHandler::sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed)
{
int code = slot->getSlotCode();
INPUT temp[1] = {};
temp[0].type = INPUT_MOUSE;
if (code == 1)
{
temp[0].mi.dwFlags = pressed ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
}
else if (code == 2)
{
temp[0].mi.dwFlags = pressed ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP;
}
else if (code == 3)
{
temp[0].mi.dwFlags = pressed ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP;
}
else if (code == 4)
{
temp[0].mi.dwFlags = MOUSEEVENTF_WHEEL;
temp[0].mi.mouseData = pressed ? WHEEL_DELTA : 0;
}
else if (code == 5)
{
temp[0].mi.dwFlags = MOUSEEVENTF_WHEEL;
temp[0].mi.mouseData = pressed ? -WHEEL_DELTA : 0;
}
else if (code == 6)
{
temp[0].mi.dwFlags = 0x01000;
temp[0].mi.mouseData = pressed ? -WHEEL_DELTA : 0;
}
else if (code == 7)
{
temp[0].mi.dwFlags = 0x01000;
temp[0].mi.mouseData = pressed ? WHEEL_DELTA : 0;
}
else if (code == 8)
{
temp[0].mi.dwFlags = pressed ? MOUSEEVENTF_XDOWN : MOUSEEVENTF_XUP;
temp[0].mi.mouseData = XBUTTON1;
}
else if (code == 9)
{
temp[0].mi.dwFlags = pressed ? MOUSEEVENTF_XDOWN : MOUSEEVENTF_XUP;
temp[0].mi.mouseData = XBUTTON2;
}
SendInput(1, temp, sizeof(INPUT));
}
void WinSendInputEventHandler::sendMouseEvent(int xDis, int yDis)
{
INPUT temp[1] = {};
temp[0].type = INPUT_MOUSE;
temp[0].mi.mouseData = 0;
temp[0].mi.dwFlags = MOUSEEVENTF_MOVE;
temp[0].mi.dx = xDis;
temp[0].mi.dy = yDis;
SendInput(1, temp, sizeof(INPUT));
}
QString WinSendInputEventHandler::getName()
{
return QString("SendInput");
}
QString WinSendInputEventHandler::getIdentifier()
{
return QString("sendinput");
}
void WinSendInputEventHandler::sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height)
{
if (width > 0 && height > 0)
{
INPUT temp[1] = {};
temp[0].type = INPUT_MOUSE;
temp[0].mi.mouseData = 0;
temp[0].mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
int fx = ceil(xDis * (65535.0/static_cast<double>(width)));
int fy = ceil(yDis * (65535.0/static_cast<double>(height)));
temp[0].mi.dx = fx;
temp[0].mi.dy = fy;
SendInput(1, temp, sizeof(INPUT));
}
}
void WinSendInputEventHandler::sendTextEntryEvent(QString maintext)
{
AntKeyMapper *mapper = AntKeyMapper::getInstance();
if (mapper && mapper->getKeyMapper())
{
QtWinKeyMapper *keymapper = static_cast<QtWinKeyMapper*>(mapper->getKeyMapper());
for (int i=0; i < maintext.size(); i++)
{
QtWinKeyMapper::charKeyInformation temp = keymapper->getCharKeyInformation(maintext.at(i));
QList<unsigned int> tempList;
if (temp.modifiers != Qt::NoModifier)
{
if (temp.modifiers.testFlag(Qt::ShiftModifier))
{
tempList.append(VK_LSHIFT);
}
if (temp.modifiers.testFlag(Qt::ControlModifier))
{
tempList.append(VK_LCONTROL);
}
if (temp.modifiers.testFlag(Qt::AltModifier))
{
tempList.append(VK_LMENU);
}
if (temp.modifiers.testFlag(Qt::MetaModifier))
{
tempList.append(VK_LWIN);
}
}
tempList.append(temp.virtualkey);
if (tempList.size() > 0)
{
INPUT tempBuffer[tempList.size()] = {0};
QListIterator<unsigned int> tempiter(tempList);
unsigned int j = 0;
while (tempiter.hasNext())
{
unsigned int tempcode = tempiter.next();
unsigned int scancode = WinExtras::scancodeFromVirtualKey(tempcode);
int extended = (scancode & WinExtras::EXTENDED_FLAG) != 0;
int tempflags = extended ? KEYEVENTF_EXTENDEDKEY : 0;
tempBuffer[j].type = INPUT_KEYBOARD;
tempBuffer[j].ki.wScan = scancode;
tempBuffer[j].ki.time = 0;
tempBuffer[j].ki.dwExtraInfo = 0;
tempBuffer[j].ki.wVk = tempcode;
tempBuffer[j].ki.dwFlags = tempflags;
j++;
}
SendInput(j, tempBuffer, sizeof(INPUT));
tempiter.toBack();
j = 0;
memset(tempBuffer, 0, sizeof(tempBuffer));
//INPUT tempBuffer2[tempList.size()] = {0};
while (tempiter.hasPrevious())
{
unsigned int tempcode = tempiter.previous();
unsigned int scancode = WinExtras::scancodeFromVirtualKey(tempcode);
int extended = (scancode & WinExtras::EXTENDED_FLAG) != 0;
int tempflags = extended ? KEYEVENTF_EXTENDEDKEY : 0;
tempBuffer[j].type = INPUT_KEYBOARD;
tempBuffer[j].ki.wScan = scancode;
tempBuffer[j].ki.time = 0;
tempBuffer[j].ki.dwExtraInfo = 0;
tempBuffer[j].ki.wVk = tempcode;
tempBuffer[j].ki.dwFlags = tempflags | KEYEVENTF_KEYUP;
j++;
}
SendInput(j, tempBuffer, sizeof(INPUT));
}
}
}
}
``` | /content/code_sandbox/src/eventhandlers/winsendinputeventhandler.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,792 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <qt_windows.h>
#include <winextras.h>
#include <cmath>
#include "winvmultieventhandler.h"
#include <qtvmultikeymapper.h>
WinVMultiEventHandler::WinVMultiEventHandler(QObject *parent) :
BaseEventHandler(parent),
sendInputHandler(this)
{
vmulti = 0;
mouseButtons = 0;
shiftKeys = 0;
multiKeys = 0;
extraKeys = 0;
keyboardKeys.resize(6);
keyboardKeys.fill(0);
nativeKeyMapper = 0;
}
WinVMultiEventHandler::~WinVMultiEventHandler()
{
cleanup();
}
bool WinVMultiEventHandler::init()
{
bool result = true;
vmulti = vmulti_alloc();
if (vmulti == NULL)
{
result = false;
}
if (vmulti && !vmulti_connect(vmulti))
{
vmulti_free(vmulti);
vmulti = 0;
result = false;
}
if (vmulti)
{
nativeKeyMapper = 0;
if (AntKeyMapper::getInstance("vmulti")->hasNativeKeyMapper())
{
nativeKeyMapper = AntKeyMapper::getInstance("vmulti")->getNativeKeyMapper();
}
}
return result;
}
bool WinVMultiEventHandler::cleanup()
{
bool result = true;
if (vmulti)
{
vmulti_disconnect(vmulti);
vmulti_free(vmulti);
vmulti = 0;
}
nativeKeyMapper = 0;
return result;
}
void WinVMultiEventHandler::sendKeyboardEvent(JoyButtonSlot *slot, bool pressed)
{
int code = slot->getSlotCode();
BYTE pendingShift = 0x0;
BYTE pendingMultimedia = 0x0;
BYTE pendingExtra = 0x0;
BYTE pendingKey = 0x0;
JoyButtonSlot tempSendInputSlot(slot);
bool useSendInput = false;
bool exists = keyboardKeys.contains(code);
if (code <= 0x65)
{
pendingKey = code;
}
else if (code >= 0xE0 && code <= 0xE7)
{
//pendingShift = 1 << (code - 0xE0);
if (nativeKeyMapper)
{
unsigned int nativeKey = nativeKeyMapper->returnVirtualKey(slot->getSlotCodeAlias());
if (nativeKey > 0)
{
tempSendInputSlot.setSlotCode(nativeKey);
useSendInput = true;
}
}
}
else if (code > QtVMultiKeyMapper::consumerUsagePagePrefix)
{
if (nativeKeyMapper)
{
unsigned int nativeKey = nativeKeyMapper->returnVirtualKey(slot->getSlotCodeAlias());
if (nativeKey > 0)
{
tempSendInputSlot.setSlotCode(nativeKey);
useSendInput = true;
}
}
/*if (code == 0xB5 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingMultimedia = 1 << 0; // (Scan Next Track)
}
else if (code == 0xB6 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingMultimedia = 1 << 1; // (Scan Previous Track)
}
else if (code == 0xB1 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingMultimedia = 1 << 3; // (Play / Pause)
}
else if (code == 0x189 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingMultimedia = 1 << 6; // (WWW Home)
}
else if (code == 0x194 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 0; // (My Computer)
}
else if (code == 0x192 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 1; // (Calculator)
}
else if (code == 0x22a | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 2; // (WWW fav)
}
else if (code == 0x221 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 3; // (WWW search)
}
else if (code == 0xB7 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 3; // (WWW stop)
}
else if (code == 0x224 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 4; // (WWW back)
}
else if (code == 0x87 | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 5; // (Media Select)
}
else if (code == 0x18a | QtVMultiKeyMapper::consumerUsagePagePrefix)
{
pendingExtra = 1 << 6; // (Mail)
}
*/
}
else if (code > 0x65)
{
if (nativeKeyMapper)
{
unsigned int nativeKey = nativeKeyMapper->returnVirtualKey(slot->getSlotCodeAlias());
if (nativeKey > 0)
{
tempSendInputSlot.setSlotCode(nativeKey);
//sendInputHandler.sendKeyboardEvent(tempslot, pressed);
useSendInput = true;
}
}
/*if (code == 0x78)
{
pendingMultimedia = 1 << 2; // (Stop)
}
else if (code == 0x7F)
{
pendingMultimedia = 1 << 4; // (Mute)
}
else if (code == 0x81)
{
pendingMultimedia = 1 << 5; // (Volume Down)
}
else if (code == 0x80)
{
pendingMultimedia = 1 << 6; // (Volume Up)
}
*/
}
if (!useSendInput)
{
if (pressed)
{
shiftKeys = shiftKeys | pendingShift;
multiKeys = multiKeys | pendingMultimedia;
extraKeys = extraKeys | pendingExtra;
if (!exists)
{
// Check for an empty key value
int index = keyboardKeys.indexOf(0);
if (index != -1)
{
keyboardKeys.replace(index, pendingKey);
}
}
}
else
{
shiftKeys = shiftKeys ^ pendingShift;
multiKeys = multiKeys ^ pendingMultimedia;
extraKeys = extraKeys ^ pendingExtra;
if (exists)
{
int index = keyboardKeys.indexOf(pendingKey);
if (index != -1)
{
keyboardKeys.replace(index, 0);
}
}
}
BYTE *keykeyArray = keyboardKeys.data();
/*QStringList trying;
for (int i=0; i < 6; i++)
{
BYTE current = keykeyArray[i];
trying.append(QString("0x%1").arg(QString::number(current, 16)));
}
*/
//qDebug() << "CURRENT: " << trying.join(",");
//qDebug() << keykeyArray;
if (pendingKey > 0x0)
{
vmulti_update_keyboard(vmulti, shiftKeys, keykeyArray);
}
if (pendingMultimedia > 0 || pendingExtra > 0)
{
//vmulti_update_keyboard_enhanced(vmulti, multiKeys, extraKeys);
}
}
else
{
sendInputHandler.sendKeyboardEvent(&tempSendInputSlot, pressed);
useSendInput = false;
}
}
void WinVMultiEventHandler::sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed)
{
BYTE pendingButton = 0;
BYTE pendingWheel = 0;
BYTE pendingHWheel = 0;
bool useSendInput = false;
int code = slot->getSlotCode();
if (code == 1)
{
pendingButton = 0x01;
}
else if (code == 2)
{
pendingButton = 0x04;
}
else if (code == 3)
{
pendingButton = 0x02;
}
else if (code == 4)
{
pendingWheel = pressed ? 1 : 0;
}
else if (code == 5)
{
pendingWheel = pressed ? -1 : 0;
}
else if (code >= 6 && code <= 9)
{
useSendInput = true;
}
/*
else if (code == 6)
{
pendingHWheel = pressed ? -1 : 0;
}
else if (code == 7)
{
pendingHWheel = pressed ? 1 : 0;
}
else if (code == 8)
{
pendingButton = 0x08;
}
else if (code == 9)
{
pendingButton = 0x10;
}
*/
if (!useSendInput)
{
if (pressed)
{
mouseButtons = mouseButtons | pendingButton;
vmulti_update_relative_mouse(vmulti, mouseButtons, 0, 0, pendingWheel);//, pendingHWheel);
}
else
{
mouseButtons = mouseButtons ^ pendingButton;
vmulti_update_relative_mouse(vmulti, mouseButtons, 0, 0, pendingWheel);//, pendingHWheel);
}
}
else
{
sendInputHandler.sendMouseButtonEvent(slot, pressed);
}
}
void WinVMultiEventHandler::sendMouseEvent(int xDis, int yDis)
{
vmulti_update_relative_mouse(vmulti, mouseButtons, xDis, yDis, 0);//, 0);
}
void WinVMultiEventHandler::sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height)
{
if (width > 0 && height > 0)
{
int fx = ceil(xDis * (32767.0/static_cast<double>(width)));
int fy = ceil(yDis * (32767.0/static_cast<double>(height)));
sendMouseAbsEvent(fx, fy, -1);
}
}
void WinVMultiEventHandler::sendMouseAbsEvent(int xDis, int yDis, int screen)
{
Q_UNUSED(screen);
vmulti_update_mouse(vmulti, mouseButtons, xDis, yDis, 0);//, 0);
}
/*
* TODO: Implement text event using information from QtWinKeyMapper.
*/
void WinVMultiEventHandler::sendTextEntryEvent(QString maintext)
{
sendInputHandler.sendTextEntryEvent(maintext);
}
QString WinVMultiEventHandler::getName()
{
return QString("Vmulti");
}
QString WinVMultiEventHandler::getIdentifier()
{
return QString("vmulti");
}
``` | /content/code_sandbox/src/eventhandlers/winvmultieventhandler.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,516 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "baseeventhandler.h"
BaseEventHandler::BaseEventHandler(QObject *parent) :
QObject(parent)
{
}
QString BaseEventHandler::getErrorString()
{
return lastErrorString;
}
/**
* @brief Do nothing by default. Allow child classes to specify text to output
* to a text stream.
*/
void BaseEventHandler::printPostMessages()
{
}
/**
* @brief Do nothing by default. Useful for child classes to define behavior.
* @param Displacement of X coordinate
* @param Displacement of Y coordinate
* @param Screen number or -1 to use default
*/
void BaseEventHandler::sendMouseAbsEvent(int xDis, int yDis, int screen)
{
Q_UNUSED(xDis);
Q_UNUSED(yDis);
Q_UNUSED(screen);
}
/**
* @brief Do nothing by default. Useful for child classes to define behavior.
* @param Displacement of X coordinate
* @param Displacement of Y coordinate
* @param Bounding box width
* @param Bounding box height
*/
void BaseEventHandler::sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height)
{
Q_UNUSED(xDis);
Q_UNUSED(yDis);
Q_UNUSED(width);
Q_UNUSED(height);
}
/**
* @brief Do nothing by default. Useful for child classes to define behavior.
* @param Displacement of X coordinate
* @param Displacement of Y coordinate
*/
void BaseEventHandler::sendMouseSpringEvent(int xDis, int yDis)
{
}
void BaseEventHandler::sendTextEntryEvent(QString maintext)
{
}
``` | /content/code_sandbox/src/eventhandlers/baseeventhandler.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 427 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <unistd.h>
#include <fcntl.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <cmath>
//#include <QDebug>
#include <QStringList>
#include <QStringListIterator>
#include <QFileInfo>
#include <QTimer>
#include <antkeymapper.h>
#include <logger.h>
#include <common.h>
static const QString mouseDeviceName = PadderCommon::mouseDeviceName;
static const QString keyboardDeviceName = PadderCommon::keyboardDeviceName;
static const QString springMouseDeviceName = PadderCommon::springMouseDeviceName;
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QApplication>
#endif
#include <x11extras.h>
#endif
#include "uinputeventhandler.h"
UInputEventHandler::UInputEventHandler(QObject *parent) :
BaseEventHandler(parent)
{
keyboardFileHandler = 0;
mouseFileHandler = 0;
springMouseFileHandler = 0;
}
UInputEventHandler::~UInputEventHandler()
{
cleanup();
}
/**
* @brief Initialize keyboard and mouse virtual devices. Each device will
* use its own file handle with various codes set to distinquish the two
* devices.
* @return
*/
bool UInputEventHandler::init()
{
bool result = true;
// Open file handle for keyboard emulation.
keyboardFileHandler = openUInputHandle();
if (keyboardFileHandler > 0)
{
setKeyboardEvents(keyboardFileHandler);
populateKeyCodes(keyboardFileHandler);
createUInputKeyboardDevice(keyboardFileHandler);
}
else
{
result = false;
}
if (result)
{
// Open mouse file handle to use for relative mouse emulation.
mouseFileHandler = openUInputHandle();
if (mouseFileHandler > 0)
{
setRelMouseEvents(mouseFileHandler);
createUInputMouseDevice(mouseFileHandler);
}
else
{
result = false;
}
}
if (result)
{
// Open mouse file handle to use for absolute mouse emulation.
springMouseFileHandler = openUInputHandle();
if (springMouseFileHandler > 0)
{
setSpringMouseEvents(springMouseFileHandler);
createUInputSpringMouseDevice(springMouseFileHandler);
}
else
{
result = false;
}
}
#ifdef WITH_X11
if (result)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
// Some time needs to elapse after device creation before changing
// pointer settings. Otherwise, settings will not take effect.
QTimer::singleShot(2000, this, SLOT(x11ResetMouseAccelerationChange()));
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
}
#endif
return result;
}
#ifdef WITH_X11
void UInputEventHandler::x11ResetMouseAccelerationChange()
{
if (X11Extras::getInstance())
{
X11Extras::getInstance()->x11ResetMouseAccelerationChange();
}
}
#endif
bool UInputEventHandler::cleanup()
{
if (keyboardFileHandler > 0)
{
closeUInputDevice(keyboardFileHandler);
keyboardFileHandler = 0;
}
if (mouseFileHandler > 0)
{
closeUInputDevice(mouseFileHandler);
mouseFileHandler = 0;
}
if (springMouseFileHandler > 0)
{
closeUInputDevice(springMouseFileHandler);
springMouseFileHandler = 0;
}
return true;
}
void UInputEventHandler::sendKeyboardEvent(JoyButtonSlot *slot, bool pressed)
{
JoyButtonSlot::JoySlotInputAction device = slot->getSlotMode();
int code = slot->getSlotCode();
if (device == JoyButtonSlot::JoyKeyboard)
{
write_uinput_event(keyboardFileHandler, EV_KEY, code, pressed ? 1 : 0);
}
}
void UInputEventHandler::sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed)
{
JoyButtonSlot::JoySlotInputAction device = slot->getSlotMode();
int code = slot->getSlotCode();
if (device == JoyButtonSlot::JoyMouseButton)
{
if (code <= 3)
{
unsigned int tempcode = BTN_LEFT;
switch (code)
{
case 3:
{
tempcode = BTN_RIGHT;
break;
}
case 2:
{
tempcode = BTN_MIDDLE;
break;
}
case 1:
default:
{
tempcode = BTN_LEFT;
}
}
write_uinput_event(mouseFileHandler, EV_KEY, tempcode, pressed ? 1 : 0);
}
else if (code == 4)
{
if (pressed)
{
write_uinput_event(mouseFileHandler, EV_REL, REL_WHEEL, 1);
}
}
else if (code == 5)
{
if (pressed)
{
write_uinput_event(mouseFileHandler, EV_REL, REL_WHEEL, -1);
}
}
else if (code == 6)
{
if (pressed)
{
write_uinput_event(mouseFileHandler, EV_REL, REL_HWHEEL, 1);
}
}
else if (code == 7)
{
if (pressed)
{
write_uinput_event(mouseFileHandler, EV_REL, REL_HWHEEL, -1);
}
}
else if (code == 8)
{
write_uinput_event(mouseFileHandler, EV_KEY, BTN_SIDE, pressed ? 1 : 0);
}
else if (code == 9)
{
write_uinput_event(mouseFileHandler, EV_KEY, BTN_EXTRA, pressed ? 1 : 0);
}
}
}
void UInputEventHandler::sendMouseEvent(int xDis, int yDis)
{
write_uinput_event(mouseFileHandler, EV_REL, REL_X, xDis, false);
write_uinput_event(mouseFileHandler, EV_REL, REL_Y, yDis);
}
void UInputEventHandler::sendMouseAbsEvent(int xDis, int yDis, int screen)
{
Q_UNUSED(screen);
write_uinput_event(springMouseFileHandler, EV_ABS, ABS_X, xDis, false);
write_uinput_event(springMouseFileHandler, EV_ABS, ABS_Y, yDis);
}
void UInputEventHandler::sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height)
{
if (width > 0 && height > 0)
{
double midwidth = static_cast<double>(width) / 2.0;
double midheight = static_cast<double>(height) / 2.0;
int fx = ceil(32767 * ((xDis - midwidth) / midwidth));
int fy = ceil(32767 * ((yDis - midheight) / midheight));
sendMouseAbsEvent(fx, fy, -1);
//write_uinput_event(springMouseFileHandler, EV_ABS, ABS_X, fx, false);
//write_uinput_event(springMouseFileHandler, EV_ABS, ABS_Y, fy);
}
}
void UInputEventHandler::sendMouseSpringEvent(int xDis, int yDis)
{
if (xDis >= -1.0 && xDis <= 1.0 &&
yDis >= -1.0 && yDis <= 1.0)
{
int fx = ceil(32767 * xDis);
int fy = ceil(32767 * yDis);
sendMouseAbsEvent(fx, fy, -1);
}
}
int UInputEventHandler::openUInputHandle()
{
int filehandle = -1;
QStringList locations;
locations.append("/dev/input/uinput");
locations.append("/dev/uinput");
locations.append("/dev/misc/uinput");
QString possibleLocation;
QStringListIterator iter(locations);
while (iter.hasNext())
{
QString temp = iter.next();
QFileInfo tempFileInfo(temp);
if (tempFileInfo.exists())
{
possibleLocation = temp;
iter.toBack();
}
}
if (possibleLocation.isEmpty())
{
lastErrorString = tr("Could not find a valid uinput device file.\n"
"Please check that you have the uinput module loaded.\n"
"lsmod | grep uinput");
}
else
{
QByteArray tempArray = possibleLocation.toUtf8();
filehandle = open(tempArray.constData(), O_WRONLY | O_NONBLOCK);
if (filehandle < 0)
{
lastErrorString = tr("Could not open uinput device file\n"
"Please check that you have permission to write to the device");
lastErrorString.append("\n").append(possibleLocation);
}
else
{
uinputDeviceLocation = possibleLocation;
}
}
return filehandle;
}
void UInputEventHandler::setKeyboardEvents(int filehandle)
{
int result = 0;
result = ioctl(filehandle, UI_SET_EVBIT, EV_KEY);
result = ioctl(filehandle, UI_SET_EVBIT, EV_SYN);
}
void UInputEventHandler::setRelMouseEvents(int filehandle)
{
int result = 0;
result = ioctl(filehandle, UI_SET_EVBIT, EV_KEY);
result = ioctl(filehandle, UI_SET_EVBIT, EV_SYN);
result = ioctl(filehandle, UI_SET_EVBIT, EV_REL);
result = ioctl(filehandle, UI_SET_RELBIT, REL_X);
result = ioctl(filehandle, UI_SET_RELBIT, REL_Y);
result = ioctl(filehandle, UI_SET_RELBIT, REL_WHEEL);
result = ioctl(filehandle, UI_SET_RELBIT, REL_HWHEEL);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_LEFT);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_RIGHT);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_MIDDLE);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_SIDE);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_EXTRA);
}
void UInputEventHandler::setSpringMouseEvents(int filehandle)
{
int result = 0;
result = ioctl(filehandle, UI_SET_EVBIT, EV_KEY);
result = ioctl(filehandle, UI_SET_EVBIT, EV_SYN);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_LEFT);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_RIGHT);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_MIDDLE);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_SIDE);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_EXTRA);
result = ioctl(filehandle, UI_SET_EVBIT, EV_ABS);
result = ioctl(filehandle, UI_SET_ABSBIT, ABS_X);
result = ioctl(filehandle, UI_SET_ABSBIT, ABS_Y);
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_TOUCH);
// BTN_TOOL_PEN is required for the mouse to be seen as an
// absolute mouse as opposed to a relative mouse.
result = ioctl(filehandle, UI_SET_KEYBIT, BTN_TOOL_PEN);
}
void UInputEventHandler::populateKeyCodes(int filehandle)
{
int result = 0;
for (unsigned int i=KEY_ESC; i <= KEY_MICMUTE; i++)
{
result = ioctl(filehandle, UI_SET_KEYBIT, i);
}
}
void UInputEventHandler::createUInputKeyboardDevice(int filehandle)
{
struct uinput_user_dev uidev;
memset(&uidev, 0, sizeof(uidev));
QByteArray temp = keyboardDeviceName.toUtf8();
strncpy(uidev.name, temp.constData(), UINPUT_MAX_NAME_SIZE);
uidev.id.bustype = BUS_USB;
uidev.id.vendor = 0x0;
uidev.id.product = 0x0;
uidev.id.version = 1;
int result = 0;
result = write(filehandle, &uidev, sizeof(uidev));
result = ioctl(filehandle, UI_DEV_CREATE);
}
void UInputEventHandler::createUInputMouseDevice(int filehandle)
{
struct uinput_user_dev uidev;
memset(&uidev, 0, sizeof(uidev));
QByteArray temp = mouseDeviceName.toUtf8();
strncpy(uidev.name, temp.constData(), UINPUT_MAX_NAME_SIZE);
uidev.id.bustype = BUS_USB;
uidev.id.vendor = 0x0;
uidev.id.product = 0x0;
uidev.id.version = 1;
int result = 0;
result = write(filehandle, &uidev, sizeof(uidev));
result = ioctl(filehandle, UI_DEV_CREATE);
}
void UInputEventHandler::createUInputSpringMouseDevice(int filehandle)
{
struct uinput_user_dev uidev;
memset(&uidev, 0, sizeof(uidev));
QByteArray temp = springMouseDeviceName.toUtf8();
strncpy(uidev.name, temp.constData(), UINPUT_MAX_NAME_SIZE);
uidev.id.bustype = BUS_USB;
uidev.id.vendor = 0x0;
uidev.id.product = 0x0;
uidev.id.version = 1;
uidev.absmin[ABS_X] = -32767;
uidev.absmax[ABS_X] = 32767;
uidev.absflat[ABS_X] = 0;
uidev.absmin[ABS_Y] = -32767;
uidev.absmax[ABS_Y] = 32767;
uidev.absflat[ABS_Y] = 0;
int result = 0;
result = write(filehandle, &uidev, sizeof(uidev));
result = ioctl(filehandle, UI_DEV_CREATE);
}
void UInputEventHandler::closeUInputDevice(int filehandle)
{
int result = 0;
result = ioctl(filehandle, UI_DEV_DESTROY);
result = close(filehandle);
}
void UInputEventHandler::write_uinput_event(int filehandle, unsigned int type,
unsigned int code, int value, bool syn)
{
struct input_event ev;
struct input_event ev2;
memset(&ev, 0, sizeof(struct input_event));
gettimeofday(&ev.time, 0);
ev.type = type;
ev.code = code;
ev.value = value;
int result = 0;
result = write(filehandle, &ev, sizeof(struct input_event));
if (syn)
{
memset(&ev2, 0, sizeof(struct input_event));
gettimeofday(&ev2.time, 0);
ev2.type = EV_SYN;
ev2.code = SYN_REPORT;
ev2.value = 0;
result = write(filehandle, &ev2, sizeof(struct input_event));
}
}
QString UInputEventHandler::getName()
{
return QString("uinput");
}
QString UInputEventHandler::getIdentifier()
{
return getName();
}
/**
* @brief Print extra help messages to stdout.
*/
void UInputEventHandler::printPostMessages()
{
//QTextStream out(stdout);
if (!lastErrorString.isEmpty())
{
Logger::LogInfo(lastErrorString);
}
if (!uinputDeviceLocation.isEmpty())
{
Logger::LogInfo(tr("Using uinput device file %1").arg(uinputDeviceLocation));
}
}
void UInputEventHandler::sendTextEntryEvent(QString maintext)
{
AntKeyMapper *mapper = AntKeyMapper::getInstance();
if (mapper && mapper->getKeyMapper())
{
QtUInputKeyMapper *keymapper = static_cast<QtUInputKeyMapper*>(mapper->getKeyMapper());
QtX11KeyMapper *nativeWinKeyMapper = 0;
if (mapper->getNativeKeyMapper())
{
nativeWinKeyMapper = static_cast<QtX11KeyMapper*>(mapper->getNativeKeyMapper());
}
QList<unsigned int> tempList;
for (int i=0; i < maintext.size(); i++)
{
tempList.clear();
QtUInputKeyMapper::charKeyInformation temp;
temp.virtualkey = 0;
temp.modifiers = Qt::NoModifier;
if (nativeWinKeyMapper)
{
QtX11KeyMapper::charKeyInformation tempX11 = nativeWinKeyMapper->getCharKeyInformation(maintext.at(i));
tempX11.virtualkey = X11Extras::getInstance()->getGroup1KeySym(tempX11.virtualkey);
unsigned int tempQtKey = nativeWinKeyMapper->returnQtKey(tempX11.virtualkey);
if (tempQtKey > 0)
{
temp.virtualkey = keymapper->returnVirtualKey(tempQtKey);
temp.modifiers = tempX11.modifiers;
}
else
{
temp = keymapper->getCharKeyInformation(maintext.at(i));
}
}
else
{
temp = keymapper->getCharKeyInformation(maintext.at(i));
}
if (temp.virtualkey > KEY_RESERVED)
{
if (temp.modifiers != Qt::NoModifier)
{
if (temp.modifiers.testFlag(Qt::ShiftModifier))
{
tempList.append(KEY_LEFTSHIFT);
write_uinput_event(keyboardFileHandler, EV_KEY, KEY_LEFTSHIFT, 1, false);
}
if (temp.modifiers.testFlag(Qt::ControlModifier))
{
tempList.append(KEY_LEFTCTRL);
write_uinput_event(keyboardFileHandler, EV_KEY, KEY_LEFTCTRL, 1, false);
}
if (temp.modifiers.testFlag(Qt::AltModifier))
{
tempList.append(KEY_LEFTALT);
write_uinput_event(keyboardFileHandler, EV_KEY, KEY_LEFTALT, 1, false);
}
if (temp.modifiers.testFlag(Qt::MetaModifier))
{
tempList.append(KEY_LEFTMETA);
write_uinput_event(keyboardFileHandler, EV_KEY, KEY_LEFTMETA, 1, false);
}
}
tempList.append(temp.virtualkey);
write_uinput_event(keyboardFileHandler, EV_KEY, temp.virtualkey, 1, true);
}
if (tempList.size() > 0)
{
QListIterator<unsigned int> tempiter(tempList);
tempiter.toBack();
while (tempiter.hasPrevious())
{
unsigned int currentcode = tempiter.previous();
bool sync = !tempiter.hasPrevious() ? true : false;
write_uinput_event(keyboardFileHandler, EV_KEY, currentcode, 0, sync);
}
}
}
}
}
``` | /content/code_sandbox/src/eventhandlers/uinputeventhandler.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 4,169 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYGRADIENTBUTTON_H
#define JOYGRADIENTBUTTON_H
#include "joybutton.h"
class JoyGradientButton : public JoyButton
{
Q_OBJECT
public:
explicit JoyGradientButton(int index, int originset, SetJoystick *parentSet, QObject *parent=0);
signals:
protected slots:
virtual void turboEvent();
virtual void wheelEventVertical();
virtual void wheelEventHorizontal();
};
#endif // JOYGRADIENTBUTTON_H
``` | /content/code_sandbox/src/joybuttontypes/joygradientbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 197 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "xtesteventhandler.h"
#include <QApplication>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include <X11/extensions/XTest.h>
#include <x11extras.h>
#include <antkeymapper.h>
XTestEventHandler::XTestEventHandler(QObject *parent) :
BaseEventHandler(parent)
{
}
bool XTestEventHandler::init()
{
X11Extras *instance = X11Extras::getInstance();
if (instance)
{
instance->x11ResetMouseAccelerationChange(X11Extras::xtestMouseDeviceName);
}
return true;
}
bool XTestEventHandler::cleanup()
{
return true;
}
void XTestEventHandler::sendKeyboardEvent(JoyButtonSlot *slot, bool pressed)
{
Display* display = X11Extras::getInstance()->display();
JoyButtonSlot::JoySlotInputAction device = slot->getSlotMode();
int code = slot->getSlotCode();
if (device == JoyButtonSlot::JoyKeyboard)
{
unsigned int tempcode = XKeysymToKeycode(display, code);
if (tempcode > 0)
{
XTestFakeKeyEvent(display, tempcode, pressed, 0);
XFlush(display);
}
}
}
void XTestEventHandler::sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed)
{
Display* display = X11Extras::getInstance()->display();
JoyButtonSlot::JoySlotInputAction device = slot->getSlotMode();
int code = slot->getSlotCode();
if (device == JoyButtonSlot::JoyMouseButton)
{
XTestFakeButtonEvent(display, code, pressed, 0);
XFlush(display);
}
}
void XTestEventHandler::sendMouseEvent(int xDis, int yDis)
{
Display* display = X11Extras::getInstance()->display();
XTestFakeRelativeMotionEvent(display, xDis, yDis, 0);
XFlush(display);
}
void XTestEventHandler::sendMouseAbsEvent(int xDis, int yDis, int screen)
{
Display* display = X11Extras::getInstance()->display();
XTestFakeMotionEvent(display, screen, xDis, yDis, 0);
XFlush(display);
}
QString XTestEventHandler::getName()
{
return QString("XTest");
}
QString XTestEventHandler::getIdentifier()
{
return QString("xtest");
}
void XTestEventHandler::sendTextEntryEvent(QString maintext)
{
AntKeyMapper *mapper = AntKeyMapper::getInstance();
// Populated as needed.
unsigned int shiftcode = 0;
unsigned int controlcode = 0;
unsigned int metacode = 0;
unsigned int altcode = 0;
if (mapper && mapper->getKeyMapper())
{
//Qt::KeyboardModifiers originalModifiers = Qt::KeyboardModifiers(QApplication::keyboardModifiers());
//Qt::KeyboardModifiers currentModifiers = Qt::KeyboardModifiers(QApplication::keyboardModifiers());
Display* display = X11Extras::getInstance()->display();
QtX11KeyMapper *keymapper = static_cast<QtX11KeyMapper*>(mapper->getKeyMapper());
for (int i=0; i < maintext.size(); i++)
{
QtX11KeyMapper::charKeyInformation temp = keymapper->getCharKeyInformation(maintext.at(i));
unsigned int tempcode = XKeysymToKeycode(display, temp.virtualkey);
if (tempcode > 0)
{
QList<unsigned int> tempList;
if (temp.modifiers != Qt::NoModifier)
{
if (temp.modifiers.testFlag(Qt::ShiftModifier))
{
if (shiftcode == 0)
{
shiftcode = XKeysymToKeycode(display, XK_Shift_L);
}
unsigned int modifiercode = shiftcode;
XTestFakeKeyEvent(display, modifiercode, 1, 0);
//currentModifiers |= Qt::ShiftModifier;
tempList.append(modifiercode);
}
if (temp.modifiers.testFlag(Qt::ControlModifier))
{
if (controlcode == 0)
{
controlcode = XKeysymToKeycode(display, XK_Control_L);
}
unsigned int modifiercode = controlcode;
XTestFakeKeyEvent(display, modifiercode, 1, 0);
//currentModifiers |= Qt::ControlModifier;
tempList.append(modifiercode);
}
if (temp.modifiers.testFlag(Qt::AltModifier))
{
if (altcode == 0)
{
altcode = XKeysymToKeycode(display, XK_Alt_L);
}
unsigned int modifiercode = altcode;
XTestFakeKeyEvent(display, modifiercode, 1, 0);
//currentModifiers |= Qt::AltModifier;
tempList.append(modifiercode);
}
if (temp.modifiers.testFlag(Qt::MetaModifier))
{
if (metacode == 0)
{
metacode = XKeysymToKeycode(display, XK_Meta_L);
}
unsigned int modifiercode = metacode;
XTestFakeKeyEvent(display, modifiercode, 1, 0);
//currentModifiers |= Qt::MetaModifier;
tempList.append(modifiercode);
}
}
XTestFakeKeyEvent(display, tempcode, 1, 0);
tempList.append(tempcode);
XFlush(display);
if (tempList.size() > 0)
{
QListIterator<unsigned int> tempiter(tempList);
tempiter.toBack();
while (tempiter.hasPrevious())
{
unsigned int currentcode = tempiter.previous();
XTestFakeKeyEvent(display, currentcode, 0, 0);
}
XFlush(display);
}
}
}
// Perform a flush at the end.
//XFlush(display);
// Restore modifiers in place
/*if (originalModifiers != currentModifiers)
{
}
*/
}
}
``` | /content/code_sandbox/src/eventhandlers/xtesteventhandler.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,366 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYCONTROLSTICKMODIFIERBUTTON_H
#define JOYCONTROLSTICKMODIFIERBUTTON_H
#include "joybuttontypes/joygradientbutton.h"
class JoyControlStick;
class JoyControlStickModifierButton : public JoyGradientButton
{
Q_OBJECT
public:
explicit JoyControlStickModifierButton(JoyControlStick *stick, int originset, SetJoystick *parentSet, QObject *parent = 0);
//virtual int getRealJoyNumber();
virtual QString getPartialName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getXmlName();
virtual double getDistanceFromDeadZone();
virtual double getMouseDistanceFromDeadZone();
virtual double getLastMouseDistanceFromDeadZone();
virtual void setChangeSetCondition(SetChangeCondition condition, bool passive=false);
JoyControlStick *getStick();
virtual void setTurboMode(TurboMode mode);
virtual bool isPartRealAxis();
virtual bool isModifierButton();
virtual double getAccelerationDistance();
virtual double getLastAccelerationDistance();
static const QString xmlName;
protected:
JoyControlStick *stick;
};
#endif // JOYCONTROLSTICKMODIFIERBUTTON_H
``` | /content/code_sandbox/src/joybuttontypes/joycontrolstickmodifierbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 343 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYAXISBUTTON_H
#define JOYAXISBUTTON_H
#include <QString>
#include "joybuttontypes/joygradientbutton.h"
class JoyAxis;
class JoyAxisButton : public JoyGradientButton
{
Q_OBJECT
public:
explicit JoyAxisButton(JoyAxis *axis, int index, int originset, SetJoystick *parentSet, QObject *parent=0);
virtual QString getPartialName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getXmlName();
virtual double getDistanceFromDeadZone();
virtual double getMouseDistanceFromDeadZone();
virtual double getLastMouseDistanceFromDeadZone();
virtual void setChangeSetCondition(SetChangeCondition condition, bool passive=false,
bool updateActiveString=true);
JoyAxis* getAxis();
virtual void setVDPad(VDPad *vdpad);
virtual void setTurboMode(TurboMode mode);
virtual bool isPartRealAxis();
virtual double getAccelerationDistance();
virtual double getLastAccelerationDistance();
static const QString xmlName;
protected:
JoyAxis *axis;
signals:
void setAssignmentChanged(int current_button, int axis_index, int associated_set, int mode);
};
#endif // JOYAXISBUTTON_H
``` | /content/code_sandbox/src/joybuttontypes/joyaxisbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 360 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "joydpadbutton.h"
#include "joydpad.h"
#include "event.h"
const QString JoyDPadButton::xmlName = "dpadbutton";
// Initially, qualify direction as the button's index
JoyDPadButton::JoyDPadButton(int direction, int originset, JoyDPad* dpad, SetJoystick *parentSet, QObject *parent) :
JoyButton(direction, originset, parentSet, parent)
{
this->direction = direction;
this->dpad = dpad;
}
QString JoyDPadButton::getDirectionName()
{
QString label = QString ();
if (direction == DpadUp)
{
label.append(tr("Up"));
}
else if (direction == DpadDown)
{
label.append(tr("Down"));
}
else if (direction == DpadLeft)
{
label.append(tr("Left"));
}
else if (direction == DpadRight)
{
label.append(tr("Right"));
}
else if (direction == DpadLeftUp)
{
label.append(tr("Up")).append("+").append(tr("Left"));
}
else if (direction == DpadLeftDown)
{
label.append(tr("Down")).append("+").append(tr("Left"));
}
else if (direction == DpadRightUp)
{
label.append(tr("Up")).append("+").append(tr("Right"));
}
else if (direction == DpadRightDown)
{
label.append(tr("Down")).append("+").append(tr("Right"));
}
return label;
}
QString JoyDPadButton::getXmlName()
{
return this->xmlName;
}
int JoyDPadButton::getRealJoyNumber()
{
return index;
}
QString JoyDPadButton::getPartialName(bool forceFullFormat, bool displayNames)
{
QString temp = dpad->getName().append(" - ");
if (!buttonName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(buttonName);
}
else if (!defaultButtonName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(defaultButtonName);
}
else
{
temp.append(tr("Button")).append(" ");
temp.append(getDirectionName());
}
return temp;
}
void JoyDPadButton::reset()
{
JoyButton::reset();
}
void JoyDPadButton::reset(int index)
{
Q_UNUSED(index);
reset();
}
void JoyDPadButton::setChangeSetCondition(SetChangeCondition condition, bool passive)
{
SetChangeCondition oldCondition = setSelectionCondition;
if (condition != setSelectionCondition && !passive)
{
if (condition == SetChangeWhileHeld || condition == SetChangeTwoWay)
{
// Set new condition
emit setAssignmentChanged(index, this->dpad->getJoyNumber(), setSelection, condition);
}
else if (setSelectionCondition == SetChangeWhileHeld || setSelectionCondition == SetChangeTwoWay)
{
// Remove old condition
emit setAssignmentChanged(index, this->dpad->getJoyNumber(), setSelection, SetChangeDisabled);
}
setSelectionCondition = condition;
}
else if (passive)
{
setSelectionCondition = condition;
}
if (setSelectionCondition == SetChangeDisabled)
{
setChangeSetSelection(-1);
}
if (setSelectionCondition != oldCondition)
{
buildActiveZoneSummaryString();
emit propertyUpdated();
}
}
JoyDPad* JoyDPadButton::getDPad()
{
return dpad;
}
int JoyDPadButton::getDirection()
{
return direction;
}
``` | /content/code_sandbox/src/joybuttontypes/joydpadbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 915 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYDPADBUTTON_H
#define JOYDPADBUTTON_H
#include "joybutton.h"
class JoyDPad;
class JoyDPadButton : public JoyButton
{
Q_OBJECT
public:
JoyDPadButton(int direction, int originset, JoyDPad* dpad, SetJoystick *parentSet, QObject *parent=0);
QString getDirectionName();
int getDirection();
virtual int getRealJoyNumber();
virtual QString getPartialName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getXmlName();
JoyDPad *getDPad();
virtual void setChangeSetCondition(SetChangeCondition condition, bool passive=false);
enum JoyDPadDirections {
DpadCentered = 0, DpadUp = 1, DpadRight = 2,
DpadDown = 4, DpadLeft = 8, DpadRightUp = 3,
DpadRightDown = 6, DpadLeftUp = 9, DpadLeftDown = 12
};
static const QString xmlName;
protected:
int direction;
JoyDPad *dpad;
signals:
void setAssignmentChanged(int current_button, int dpad_index, int associated_set, int mode);
public slots:
virtual void reset();
virtual void reset(int index);
};
#endif // JOYDPADBUTTON_H
``` | /content/code_sandbox/src/joybuttontypes/joydpadbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 389 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYCONTROLSTICKBUTTON_H
#define JOYCONTROLSTICKBUTTON_H\
#include <QString>
#include "joybuttontypes/joygradientbutton.h"
#include "joycontrolstickdirectionstype.h"
class JoyControlStick;
class JoyControlStickButton : public JoyGradientButton
{
Q_OBJECT
public:
explicit JoyControlStickButton(JoyControlStick *stick, int index, int originset, SetJoystick *parentSet, QObject *parent = 0);
explicit JoyControlStickButton(JoyControlStick *stick, JoyStickDirectionsType::JoyStickDirections index, int originset, SetJoystick *parentSet, QObject *parent = 0);
virtual int getRealJoyNumber();
virtual QString getPartialName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getXmlName();
QString getDirectionName();
JoyStickDirectionsType::JoyStickDirections getDirection();
virtual double getDistanceFromDeadZone();
virtual double getMouseDistanceFromDeadZone();
virtual double getLastMouseDistanceFromDeadZone();
virtual void setChangeSetCondition(SetChangeCondition condition, bool passive=false);
JoyControlStick *getStick();
virtual void setTurboMode(TurboMode mode);
virtual bool isPartRealAxis();
virtual QString getActiveZoneSummary();
virtual QString getCalculatedActiveZoneSummary();
virtual double getAccelerationDistance();
virtual double getLastAccelerationDistance();
static const QString xmlName;
protected:
virtual double getCurrentSpringDeadCircle();
JoyControlStick *stick;
signals:
void setAssignmentChanged(int current_button, int axis_index, int associated_set, int mode);
};
#endif // JOYCONTROLSTICKBUTTON_H
``` | /content/code_sandbox/src/joybuttontypes/joycontrolstickbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 451 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QString>
#include <cmath>
#include "joycontrolstick.h"
#include "joycontrolstickmodifierbutton.h"
const QString JoyControlStickModifierButton::xmlName = "stickmodifierbutton";
JoyControlStickModifierButton::JoyControlStickModifierButton(JoyControlStick *stick, int originset, SetJoystick *parentSet, QObject *parent) :
JoyGradientButton(0, originset, parentSet, parent)
{
this->stick = stick;
}
QString JoyControlStickModifierButton::getPartialName(bool forceFullFormat, bool displayNames)
{
QString temp = stick->getPartialName(forceFullFormat, displayNames);
temp.append(": ");
if (!buttonName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
temp.append(tr("Modifier")).append(" ");
}
temp.append(buttonName);
}
else if (!defaultButtonName.isEmpty())
{
if (forceFullFormat)
{
temp.append(tr("Modifier")).append(" ");
}
temp.append(defaultButtonName);
}
else
{
temp.append(tr("Modifier"));
}
return temp;
}
QString JoyControlStickModifierButton::getXmlName()
{
return this->xmlName;
}
/**
* @brief Get the distance that an element is away from its assigned
* dead zone
* @return Normalized distance away from dead zone
*/
double JoyControlStickModifierButton::getDistanceFromDeadZone()
{
return stick->calculateDirectionalDistance();
}
/**
* @brief Get the distance factor that should be used for mouse movement
* @return Distance factor that should be used for mouse movement
*/
double JoyControlStickModifierButton::getMouseDistanceFromDeadZone()
{
return getDistanceFromDeadZone();
}
void JoyControlStickModifierButton::setChangeSetCondition(SetChangeCondition condition, bool passive)
{
Q_UNUSED(condition);
Q_UNUSED(passive);
}
/*int JoyControlStickModifierButton::getRealJoyNumber()
{
return index;
}
*/
JoyControlStick* JoyControlStickModifierButton::getStick()
{
return stick;
}
/**
* @brief Set the turbo mode that the button should use
* @param Mode that should be used
*/
void JoyControlStickModifierButton::setTurboMode(TurboMode mode)
{
if (isPartRealAxis())
{
currentTurboMode = mode;
}
}
/**
* @brief Check if button should be considered a part of a real controller
* axis. Needed for some dialogs so the program won't have to resort to
* type checking.
* @return Status of being part of a real controller axis
*/
bool JoyControlStickModifierButton::isPartRealAxis()
{
return true;
}
bool JoyControlStickModifierButton::isModifierButton()
{
return true;
}
double JoyControlStickModifierButton::getAccelerationDistance()
{
double temp = stick->getAbsoluteRawDistance();
return temp;
}
double JoyControlStickModifierButton::getLastAccelerationDistance()
{
double temp = stick->calculateLastAccelerationDirectionalDistance();
return temp;
}
double JoyControlStickModifierButton::getLastMouseDistanceFromDeadZone()
{
return stick->calculateLastDirectionalDistance();
}
``` | /content/code_sandbox/src/joybuttontypes/joycontrolstickmodifierbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 780 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <cmath>
#include "joygradientbutton.h"
#include "event.h"
JoyGradientButton::JoyGradientButton(int index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyButton(index, originset, parentSet, parent)
{
}
/**
* @brief Activate a turbo event on a button.
*/
void JoyGradientButton::turboEvent()
{
if (currentTurboMode == NormalTurbo)
{
JoyButton::turboEvent();
}
else if (currentTurboMode == GradientTurbo || currentTurboMode == PulseTurbo)
{
double diff = fabs(getMouseDistanceFromDeadZone() - lastDistance);
//qDebug() << "DIFF: " << QString::number(diff);
bool changeState = false;
int checkmate = 0;
if (!turboTimer.isActive() && !isButtonPressed)
{
changeState = true;
}
else if (currentTurboMode == GradientTurbo && diff > 0 &&
getMouseDistanceFromDeadZone() >= 1.0)
{
if (isKeyPressed)
{
changeState = false;
if (!turboTimer.isActive() || turboTimer.interval() != 5)
{
turboTimer.start(5);
}
turboHold.restart();
lastDistance = 1.0;
}
else
{
changeState = true;
}
}
else if (turboHold.isNull() || lastDistance == 0.0 || turboHold.elapsed() > tempTurboInterval)
{
changeState = true;
}
else if (diff >= 0.1)
{
int tempInterval2 = 0;
if (isKeyPressed)
{
if (currentTurboMode == GradientTurbo)
{
tempInterval2 = (int)floor((getMouseDistanceFromDeadZone() * turboInterval) + 0.5);
}
else
{
tempInterval2 = (int)floor((turboInterval * 0.5) + 0.5);
}
}
else
{
if (currentTurboMode == GradientTurbo)
{
tempInterval2 = (int)floor(((1 - getMouseDistanceFromDeadZone()) * turboInterval) + 0.5);
}
else
{
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempInterval2 = (int)floor(((turboInterval / getMouseDistanceFromDeadZone()) * 0.5) + 0.5);
}
else
{
tempInterval2 = 0;
}
}
}
if (turboHold.elapsed() < tempInterval2)
{
// Still some valid time left. Continue current action with
// remaining time left.
tempTurboInterval = tempInterval2 - turboHold.elapsed();
int timerInterval = qMin(tempTurboInterval, 5);
if (!turboTimer.isActive() || turboTimer.interval() != timerInterval)
{
turboTimer.start(timerInterval);
}
turboHold.restart();
changeState = false;
lastDistance = getMouseDistanceFromDeadZone();
//qDebug() << "diff tmpTurbo press: " << QString::number(tempTurboInterval);
//qDebug() << "diff timer press: " << QString::number(timerInterval);
}
else
{
// Elapsed time is greater than new interval. Change state.
//if (isKeyPressed)
//{
// checkmate = turboHold.elapsed();
//}
changeState = true;
//qDebug() << "YOU GOT CHANGE";
}
}
if (changeState)
{
if (!isKeyPressed)
{
if (!isButtonPressedQueue.isEmpty())
{
ignoreSetQueue.clear();
isButtonPressedQueue.clear();
ignoreSetQueue.enqueue(false);
isButtonPressedQueue.enqueue(isButtonPressed);
}
createDeskEvent();
isKeyPressed = true;
if (turboTimer.isActive())
{
if (currentTurboMode == GradientTurbo)
{
tempTurboInterval = (int)floor((getMouseDistanceFromDeadZone() * turboInterval) + 0.5);
}
else
{
tempTurboInterval = (int)floor((turboInterval * 0.5) + 0.5);
}
int timerInterval = qMin(tempTurboInterval, 5);
//qDebug() << "tmpTurbo press: " << QString::number(tempTurboInterval);
//qDebug() << "timer press: " << QString::number(timerInterval);
if (turboTimer.interval() != timerInterval)
{
turboTimer.start(timerInterval);
}
turboHold.restart();
}
}
else
{
if (!isButtonPressedQueue.isEmpty())
{
ignoreSetQueue.enqueue(false);
isButtonPressedQueue.enqueue(!isButtonPressed);
}
releaseDeskEvent();
isKeyPressed = false;
if (turboTimer.isActive())
{
if (currentTurboMode == GradientTurbo)
{
tempTurboInterval = (int)floor(((1 - getMouseDistanceFromDeadZone()) * turboInterval) + 0.5);
}
else
{
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempTurboInterval = (int)floor(((turboInterval / getMouseDistanceFromDeadZone()) * 0.5) + 0.5);
}
else
{
tempTurboInterval = 0;
}
}
int timerInterval = qMin(tempTurboInterval, 5);
//qDebug() << "tmpTurbo release: " << QString::number(tempTurboInterval);
//qDebug() << "timer release: " << QString::number(timerInterval);
if (turboTimer.interval() != timerInterval)
{
turboTimer.start(timerInterval);
}
turboHold.restart();
}
}
lastDistance = getMouseDistanceFromDeadZone();
}
checkmate = 0;
}
}
void JoyGradientButton::wheelEventVertical()
{
JoyButtonSlot *buttonslot = 0;
bool activateEvent = false;
int tempInterval = 0;
double diff = fabs(getMouseDistanceFromDeadZone() - lastWheelVerticalDistance);
int oldInterval = 0;
if (wheelSpeedY != 0)
{
if (lastWheelVerticalDistance > 0.0)
{
oldInterval = 1000 / wheelSpeedY / lastWheelVerticalDistance;
}
else
{
oldInterval = 1000 / wheelSpeedY / 0.01;
}
}
if (currentWheelVerticalEvent)
{
buttonslot = currentWheelVerticalEvent;
activateEvent = true;
}
if (!activateEvent)
{
if (!mouseWheelVerticalEventTimer.isActive())
{
activateEvent = true;
}
else if (wheelVerticalTime.elapsed() > oldInterval)
{
activateEvent = true;
}
else if (diff >= 0.1 && wheelSpeedY != 0)
{
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempInterval = static_cast<int>(1000 / wheelSpeedY / distance);
}
else
{
tempInterval = 0;
}
if (wheelVerticalTime.elapsed() < tempInterval)
{
// Still some valid time left. Continue current action with
// remaining time left.
tempInterval = tempInterval - wheelVerticalTime.elapsed();
tempInterval = qMin(tempInterval, 5);
if (!mouseWheelVerticalEventTimer.isActive() || mouseWheelVerticalEventTimer.interval() != tempInterval)
{
mouseWheelVerticalEventTimer.start(tempInterval);
}
}
else
{
// Elapsed time is greater than new interval. Change state.
activateEvent = true;
}
}
}
if (buttonslot && wheelSpeedY != 0)
{
bool isActive = activeSlots.contains(buttonslot);
if (isActive && activateEvent)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
mouseWheelVerticalEventQueue.enqueue(buttonslot);
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempInterval = static_cast<int>(1000 / wheelSpeedY / distance);
}
else
{
tempInterval = 0;
}
tempInterval = qMin(tempInterval, 5);
if (!mouseWheelVerticalEventTimer.isActive() || mouseWheelVerticalEventTimer.interval() != tempInterval)
{
mouseWheelVerticalEventTimer.start(tempInterval);
}
}
else if (!isActive)
{
mouseWheelVerticalEventTimer.stop();
}
}
else if (!mouseWheelVerticalEventQueue.isEmpty() && wheelSpeedY != 0)
{
QQueue<JoyButtonSlot*> tempQueue;
while (!mouseWheelVerticalEventQueue.isEmpty())
{
buttonslot = mouseWheelVerticalEventQueue.dequeue();
bool isActive = activeSlots.contains(buttonslot);
if (isActive && activateEvent)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
tempQueue.enqueue(buttonslot);
}
else if (isActive)
{
tempQueue.enqueue(buttonslot);
}
}
if (!tempQueue.isEmpty())
{
mouseWheelVerticalEventQueue = tempQueue;
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempInterval = static_cast<int>(1000 / wheelSpeedY / distance);
}
else
{
tempInterval = 0;
}
tempInterval = qMin(tempInterval, 5);
if (!mouseWheelVerticalEventTimer.isActive() || mouseWheelVerticalEventTimer.interval() != tempInterval)
{
mouseWheelVerticalEventTimer.start(tempInterval);
}
}
else
{
mouseWheelVerticalEventTimer.stop();
}
}
else
{
mouseWheelVerticalEventTimer.stop();
}
if (activateEvent)
{
wheelVerticalTime.restart();
lastWheelVerticalDistance = getMouseDistanceFromDeadZone();
}
}
void JoyGradientButton::wheelEventHorizontal()
{
JoyButtonSlot *buttonslot = 0;
bool activateEvent = false;
int tempInterval = 0;
double diff = fabs(getMouseDistanceFromDeadZone() - lastWheelHorizontalDistance);
int oldInterval = 0;
if (wheelSpeedX != 0)
{
if (lastWheelHorizontalDistance > 0.0)
{
oldInterval = 1000 / wheelSpeedX / lastWheelHorizontalDistance;
}
else
{
oldInterval = 1000 / wheelSpeedX / 0.01;
}
}
if (currentWheelHorizontalEvent)
{
buttonslot = currentWheelHorizontalEvent;
activateEvent = true;
}
if (!activateEvent)
{
if (!mouseWheelHorizontalEventTimer.isActive())
{
activateEvent = true;
}
else if (wheelHorizontalTime.elapsed() > oldInterval)
{
activateEvent = true;
}
else if (diff >= 0.1 && wheelSpeedX != 0)
{
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempInterval = static_cast<int>(1000 / wheelSpeedX / distance);
}
else
{
tempInterval = 0;
}
if (wheelHorizontalTime.elapsed() < tempInterval)
{
// Still some valid time left. Continue current action with
// remaining time left.
tempInterval = tempInterval - wheelHorizontalTime.elapsed();
tempInterval = qMin(tempInterval, 5);
if (!mouseWheelHorizontalEventTimer.isActive() || mouseWheelHorizontalEventTimer.interval() != tempInterval)
{
mouseWheelHorizontalEventTimer.start(tempInterval);
}
}
else
{
// Elapsed time is greater than new interval. Change state.
activateEvent = true;
}
}
}
if (buttonslot && wheelSpeedX != 0)
{
bool isActive = activeSlots.contains(buttonslot);
if (isActive && activateEvent)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
mouseWheelHorizontalEventQueue.enqueue(buttonslot);
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempInterval = static_cast<int>(1000 / wheelSpeedX / distance);
}
else
{
tempInterval = 0;
}
tempInterval = qMin(tempInterval, 5);
if (!mouseWheelHorizontalEventTimer.isActive() || mouseWheelVerticalEventTimer.interval() != tempInterval)
{
mouseWheelHorizontalEventTimer.start(tempInterval);
}
}
else if (!isActive)
{
mouseWheelHorizontalEventTimer.stop();
}
}
else if (!mouseWheelHorizontalEventQueue.isEmpty() && wheelSpeedX != 0)
{
QQueue<JoyButtonSlot*> tempQueue;
while (!mouseWheelHorizontalEventQueue.isEmpty())
{
buttonslot = mouseWheelHorizontalEventQueue.dequeue();
bool isActive = activeSlots.contains(buttonslot);
if (isActive)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
tempQueue.enqueue(buttonslot);
}
}
if (!tempQueue.isEmpty())
{
mouseWheelHorizontalEventQueue = tempQueue;
double distance = getMouseDistanceFromDeadZone();
if (distance > 0.0)
{
tempInterval = static_cast<int>(1000 / wheelSpeedX / distance);
}
else
{
tempInterval = 0;
}
tempInterval = qMin(tempInterval, 5);
if (!mouseWheelHorizontalEventTimer.isActive() || mouseWheelVerticalEventTimer.interval() != tempInterval)
{
mouseWheelHorizontalEventTimer.start(tempInterval);
}
}
else
{
mouseWheelHorizontalEventTimer.stop();
}
}
else
{
mouseWheelHorizontalEventTimer.stop();
}
if (activateEvent)
{
wheelHorizontalTime.restart();
lastWheelHorizontalDistance = getMouseDistanceFromDeadZone();
}
}
``` | /content/code_sandbox/src/joybuttontypes/joygradientbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 3,235 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <cmath>
#include "joyaxisbutton.h"
#include "joyaxis.h"
#include "event.h"
const QString JoyAxisButton::xmlName = "axisbutton";
JoyAxisButton::JoyAxisButton(JoyAxis *axis, int index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyGradientButton(index, originset, parentSet, parent)
{
this->axis = axis;
}
QString JoyAxisButton::getPartialName(bool forceFullFormat, bool displayNames)
{
QString temp = QString(axis->getPartialName(forceFullFormat, displayNames));
temp.append(": ");
if (!buttonName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(buttonName);
}
else if (!defaultButtonName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(defaultButtonName);
}
else
{
QString buttontype;
if (index == 0)
{
buttontype = tr("Negative");
}
else if (index == 1)
{
buttontype = tr("Positive");
}
else
{
buttontype = tr("Unknown");
}
temp.append(tr("Button")).append(" ").append(buttontype);
}
return temp;
}
QString JoyAxisButton::getXmlName()
{
return this->xmlName;
}
void JoyAxisButton::setChangeSetCondition(SetChangeCondition condition, bool passive, bool updateActiveString)
{
SetChangeCondition oldCondition = setSelectionCondition;
if (condition != setSelectionCondition && !passive)
{
if (condition == SetChangeWhileHeld || condition == SetChangeTwoWay)
{
// Set new condition
emit setAssignmentChanged(index, this->axis->getIndex(), setSelection, condition);
}
else if (setSelectionCondition == SetChangeWhileHeld || setSelectionCondition == SetChangeTwoWay)
{
// Remove old condition
emit setAssignmentChanged(index, this->axis->getIndex(), setSelection, SetChangeDisabled);
}
setSelectionCondition = condition;
}
else if (passive)
{
setSelectionCondition = condition;
}
if (setSelectionCondition == SetChangeDisabled)
{
setChangeSetSelection(-1);
}
if (setSelectionCondition != oldCondition)
{
if (updateActiveString)
{
buildActiveZoneSummaryString();
}
emit propertyUpdated();
}
}
/**
* @brief Get the distance that an element is away from its assigned
* dead zone
* @return Normalized distance away from dead zone
*/
double JoyAxisButton::getDistanceFromDeadZone()
{
return axis->getDistanceFromDeadZone();
}
/**
* @brief Get the distance factor that should be used for mouse movement
* @return Distance factor that should be used for mouse movement
*/
double JoyAxisButton::getMouseDistanceFromDeadZone()
{
return this->getDistanceFromDeadZone();
}
void JoyAxisButton::setVDPad(VDPad *vdpad)
{
if (axis->isPartControlStick())
{
axis->removeControlStick();
}
JoyButton::setVDPad(vdpad);
}
JoyAxis* JoyAxisButton::getAxis()
{
return this->axis;
}
/**
* @brief Set the turbo mode that the button should use
* @param Mode that should be used
*/
void JoyAxisButton::setTurboMode(TurboMode mode)
{
if (isPartRealAxis())
{
currentTurboMode = mode;
}
}
/**
* @brief Check if button should be considered a part of a real controller
* axis. Needed for some dialogs so the program won't have to resort to
* type checking.
* @return Status of being part of a real controller axis
*/
bool JoyAxisButton::isPartRealAxis()
{
return true;
}
double JoyAxisButton::getAccelerationDistance()
{
double distance = 0.0;
distance = axis->getRawDistance(axis->getCurrentThrottledValue());
return distance;
}
double JoyAxisButton::getLastAccelerationDistance()
{
double distance = 0.0;
distance = axis->getRawDistance(axis->getLastKnownThrottleValue());
/*if (axis->getAxisButtonByValue(axis->getLastKnownThrottleValue()) == this)
{
distance = axis->getRawDistance(axis->getLastKnownThrottleValue());
}
*/
return distance;
}
double JoyAxisButton::getLastMouseDistanceFromDeadZone()
{
double distance = 0.0;
if (axis->getAxisButtonByValue(axis->getLastKnownThrottleValue()) == this)
{
distance = axis->getDistanceFromDeadZone(axis->getLastKnownThrottleValue());
}
return distance;
}
``` | /content/code_sandbox/src/joybuttontypes/joyaxisbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,170 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <cmath>
#include <QStringList>
#include "joycontrolstickbutton.h"
#include "joycontrolstick.h"
#include "event.h"
const QString JoyControlStickButton::xmlName = "stickbutton";
JoyControlStickButton::JoyControlStickButton(JoyControlStick *stick, int index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyGradientButton(index, originset, parentSet, parent)
{
this->stick = stick;
}
JoyControlStickButton::JoyControlStickButton(JoyControlStick *stick, JoyStickDirectionsType::JoyStickDirections index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyGradientButton((int)index, originset, parentSet, parent)
{
this->stick = stick;
}
QString JoyControlStickButton::getDirectionName()
{
QString label = QString();
if (index == JoyControlStick::StickUp)
{
label.append(tr("Up"));
}
else if (index == JoyControlStick::StickDown)
{
label.append(tr("Down"));
}
else if (index == JoyControlStick::StickLeft)
{
label.append(tr("Left"));
}
else if (index == JoyControlStick::StickRight)
{
label.append(tr("Right"));
}
else if (index == JoyControlStick::StickLeftUp)
{
label.append(tr("Up")).append("+").append(tr("Left"));
}
else if (index == JoyControlStick::StickLeftDown)
{
label.append(tr("Down")).append("+").append(tr("Left"));
}
else if (index == JoyControlStick::StickRightUp)
{
label.append(tr("Up")).append("+").append(tr("Right"));
}
else if (index == JoyControlStick::StickRightDown)
{
label.append(tr("Down")).append("+").append(tr("Right"));
}
return label;
}
QString JoyControlStickButton::getPartialName(bool forceFullFormat, bool displayNames)
{
QString temp = stick->getPartialName(forceFullFormat, displayNames);
temp.append(": ");
if (!buttonName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(buttonName);
}
else if (!defaultButtonName.isEmpty())
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(defaultButtonName);
}
else
{
temp.append(tr("Button")).append(" ");
temp.append(getDirectionName());
}
return temp;
}
QString JoyControlStickButton::getXmlName()
{
return this->xmlName;
}
/**
* @brief Get the distance that an element is away from its assigned
* dead zone
* @return Normalized distance away from dead zone
*/
double JoyControlStickButton::getDistanceFromDeadZone()
{
return stick->calculateDirectionalDistance();
}
/**
* @brief Get the distance factor that should be used for mouse movement
* @return Distance factor that should be used for mouse movement
*/
double JoyControlStickButton::getMouseDistanceFromDeadZone()
{
return stick->calculateMouseDirectionalDistance(this);
}
void JoyControlStickButton::setChangeSetCondition(SetChangeCondition condition, bool passive)
{
SetChangeCondition oldCondition = setSelectionCondition;
if (condition != setSelectionCondition && !passive)
{
if (condition == SetChangeWhileHeld || condition == SetChangeTwoWay)
{
// Set new condition
emit setAssignmentChanged(index, this->stick->getIndex(), setSelection, condition);
}
else if (setSelectionCondition == SetChangeWhileHeld || setSelectionCondition == SetChangeTwoWay)
{
// Remove old condition
emit setAssignmentChanged(index, this->stick->getIndex(), setSelection, SetChangeDisabled);
}
setSelectionCondition = condition;
}
else if (passive)
{
setSelectionCondition = condition;
}
if (setSelectionCondition == SetChangeDisabled)
{
setChangeSetSelection(-1);
}
if (setSelectionCondition != oldCondition)
{
buildActiveZoneSummaryString();
emit propertyUpdated();
}
}
int JoyControlStickButton::getRealJoyNumber()
{
return index;
}
JoyControlStick* JoyControlStickButton::getStick()
{
return stick;
}
JoyStickDirectionsType::JoyStickDirections JoyControlStickButton::getDirection()
{
return static_cast<JoyStickDirectionsType::JoyStickDirections>(index);
}
/**
* @brief Set the turbo mode that the button should use
* @param Mode that should be used
*/
void JoyControlStickButton::setTurboMode(TurboMode mode)
{
if (isPartRealAxis())
{
currentTurboMode = mode;
}
}
/**
* @brief Check if button should be considered a part of a real controller
* axis. Needed for some dialogs so the program won't have to resort to
* type checking.
* @return Status of being part of a real controller axis
*/
bool JoyControlStickButton::isPartRealAxis()
{
return true;
}
double JoyControlStickButton::getLastAccelerationDistance()
{
double temp = stick->calculateLastAccelerationButtonDistance(this);
return temp;
}
double JoyControlStickButton::getAccelerationDistance()
{
double temp = stick->calculateAccelerationDistance(this);
return temp;
}
/**
* @brief Generate a string that represents slots that will be activated or
* slots that are currently active if a button is pressed
* @return String of currently applicable slots for a button
*/
QString JoyControlStickButton::getActiveZoneSummary()
{
QList<JoyButtonSlot*> tempList;
JoyControlStickModifierButton *tempButton = stick->getModifierButton();
/*if (tempButton && tempButton->getButtonState() &&
tempButton->hasActiveSlots() && getButtonState())
{
QList<JoyButtonSlot*> activeModifierSlots = tempButton->getActiveZoneList();
tempList.append(activeModifierSlots);
}
*/
tempList.append(getActiveZoneList());
QString temp = buildActiveZoneSummary(tempList);
return temp;
}
QString JoyControlStickButton::getCalculatedActiveZoneSummary()
{
JoyControlStickModifierButton *tempButton = stick->getModifierButton();
QString temp;
QStringList stringlist;
if (tempButton && tempButton->getButtonState() &&
tempButton->hasActiveSlots() && getButtonState())
{
stringlist.append(tempButton->getCalculatedActiveZoneSummary());
}
stringlist.append(JoyButton::getCalculatedActiveZoneSummary());
temp = stringlist.join(", ");
return temp;
}
double JoyControlStickButton::getLastMouseDistanceFromDeadZone()
{
return stick->calculateLastMouseDirectionalDistance(this);
}
double JoyControlStickButton::getCurrentSpringDeadCircle()
{
double result = (springDeadCircleMultiplier * 0.01);
if (index == JoyControlStick::StickLeft || index == JoyControlStick::StickRight)
{
result = stick->getSpringDeadCircleX() * (springDeadCircleMultiplier * 0.01);
}
else if (index == JoyControlStick::StickUp || index == JoyControlStick::StickDown)
{
result = stick->getSpringDeadCircleY() * (springDeadCircleMultiplier * 0.01);
}
else if (index == JoyControlStick::StickRightUp || index == JoyControlStick::StickRightDown ||
index == JoyControlStick::StickLeftDown || index == JoyControlStick::StickLeftUp)
{
result = 0.0;
}
return result;
}
``` | /content/code_sandbox/src/joybuttontypes/joycontrolstickbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,768 |
```smalltalk
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace SidebarDiagnostics.Style
{
public partial class FlatStyle : ResourceDictionary
{
public FlatStyle()
{
InitializeComponent();
}
private void PART_TITLEBAR_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Border _titlebar = (Border)sender;
if (_titlebar != null)
{
Window _window = Window.GetWindow(_titlebar);
if (_window != null && _window.IsInitialized)
{
_window.DragMove();
}
}
}
private void PART_MINIMIZE_Click(object sender, RoutedEventArgs e)
{
Button _button = (Button)sender;
if (_button != null)
{
Window _window = Window.GetWindow(_button);
if (_window != null && _window.IsInitialized)
{
_window.WindowState = WindowState.Minimized;
}
}
}
private void PART_MAXIMIZE_RESTORE_Click(object sender, RoutedEventArgs e)
{
Button _button = (Button)sender;
if (_button != null)
{
Window _window = Window.GetWindow(_button);
if (_window != null && _window.IsInitialized)
{
switch (_window.WindowState)
{
case WindowState.Normal:
_window.WindowState = WindowState.Maximized;
break;
case WindowState.Maximized:
_window.WindowState = WindowState.Normal;
break;
}
}
}
}
private void PART_CLOSE_Click(object sender, RoutedEventArgs e)
{
Button _button = (Button)sender;
if (_button != null)
{
Window _window = Window.GetWindow(_button);
if (_window != null && _window.IsInitialized)
{
_window.Close();
}
}
}
private void PART_RESIZE_BOTRIGHT_DragDelta(object sender, DragDeltaEventArgs e)
{
Thumb _thumb = (Thumb)sender;
if (_thumb != null)
{
Window _window = Window.GetWindow(_thumb);
if (_window != null && _window.IsInitialized)
{
double _newWidth = _window.Width + e.HorizontalChange;
if (_newWidth > 0)
{
_window.Width = _newWidth > _window.MinWidth ? _newWidth : _window.MinWidth;
}
double _newHeight = _window.Height + e.VerticalChange;
if (_newHeight > 0)
{
_window.Height = _newHeight > _window.MinHeight ? _newHeight : _window.MinHeight;
}
}
}
}
}
public partial class FlatWindow : Window
{
public static readonly DependencyProperty ShowTitleBarProperty = DependencyProperty.Register("ShowTitleBar", typeof(bool), typeof(FlatWindow), new UIPropertyMetadata(true));
public bool ShowTitleBar
{
get
{
return (bool)GetValue(ShowTitleBarProperty);
}
set
{
SetValue(ShowTitleBarProperty, value);
}
}
public static readonly DependencyProperty ShowIconProperty = DependencyProperty.Register("ShowIcon", typeof(bool), typeof(FlatWindow), new UIPropertyMetadata(true));
public bool ShowIcon
{
get
{
return (bool)GetValue(ShowIconProperty);
}
set
{
SetValue(ShowIconProperty, value);
}
}
public static readonly DependencyProperty ShowTitleProperty = DependencyProperty.Register("ShowTitle", typeof(bool), typeof(FlatWindow), new UIPropertyMetadata(true));
public bool ShowTitle
{
get
{
return (bool)GetValue(ShowTitleProperty);
}
set
{
SetValue(ShowTitleProperty, value);
}
}
public static readonly DependencyProperty ShowCloseProperty = DependencyProperty.Register("ShowClose", typeof(bool), typeof(FlatWindow), new UIPropertyMetadata(true));
public bool ShowClose
{
get
{
return (bool)GetValue(ShowCloseProperty);
}
set
{
SetValue(ShowCloseProperty, value);
}
}
public static readonly DependencyProperty ShowMaximizeProperty = DependencyProperty.Register("ShowMaximize", typeof(bool), typeof(FlatWindow), new UIPropertyMetadata(true));
public bool ShowMaximize
{
get
{
return (bool)GetValue(ShowMaximizeProperty);
}
set
{
SetValue(ShowMaximizeProperty, value);
}
}
public static readonly DependencyProperty ShowMinimizeProperty = DependencyProperty.Register("ShowMinimize", typeof(bool), typeof(FlatWindow), new UIPropertyMetadata(true));
public bool ShowMinimize
{
get
{
return (bool)GetValue(ShowMinimizeProperty);
}
set
{
SetValue(ShowMinimizeProperty, value);
}
}
}
}
``` | /content/code_sandbox/SidebarDiagnostics/FlatStyle.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1,029 |
```smalltalk
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using SidebarDiagnostics.Utilities;
using SidebarDiagnostics.Framework;
namespace SidebarDiagnostics.Models
{
public class ChangeLogModel : INotifyPropertyChanged
{
public ChangeLogModel(Version version)
{
string _vstring = version.ToString(3);
Title = string.Format("{0} v{1}", Resources.ChangeLogTitle, _vstring);
ChangeLogEntry _log = ChangeLogEntry.Load().FirstOrDefault(e => string.Equals(e.Version, _vstring, StringComparison.OrdinalIgnoreCase));
if (_log != null)
{
Changes = _log.Changes;
}
else
{
Changes = new string[0];
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private string _title { get; set; }
public string Title
{
get
{
return _title;
}
set
{
_title = value;
NotifyPropertyChanged("Title");
}
}
private string[] _changes { get; set; }
public string[] Changes
{
get
{
return _changes;
}
set
{
_changes = value;
NotifyPropertyChanged("Changes");
}
}
}
[JsonObject(MemberSerialization.OptIn)]
public class ChangeLogEntry
{
public static ChangeLogEntry[] Load()
{
ChangeLogEntry[] _return = null;
string _file = Paths.ChangeLog;
if (File.Exists(_file))
{
using (StreamReader _reader = File.OpenText(_file))
{
_return = (ChangeLogEntry[])new JsonSerializer().Deserialize(_reader, typeof(ChangeLogEntry[]));
}
}
return _return ?? new ChangeLogEntry[0];
}
[JsonProperty]
public string Version { get; set; }
[JsonProperty]
public string[] Changes { get; set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/ChangeLogModel.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 448 |
```smalltalk
using System;
using System.Windows;
using SidebarDiagnostics.Models;
using SidebarDiagnostics.Windows;
using SidebarDiagnostics.Style;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for ChangeLog.xaml
/// </summary>
public partial class ChangeLog : FlatWindow
{
public ChangeLog(Version version)
{
InitializeComponent();
DataContext = Model = new ChangeLogModel(version);
}
private void Close_Click(object sender, RoutedEventArgs e)
{
Close();
}
public ChangeLogModel Model { get; private set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/ChangeLog.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 123 |
```smalltalk
namespace SidebarDiagnostics
{
public static class Constants
{
public static class Generic
{
public const string TASKNAME = "SidebarStartup";
}
public static class URLs
{
public const string IPIFY = "path_to_url";
}
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Constants.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 63 |
```smalltalk
using System;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Threading;
using SidebarDiagnostics.Models;
using SidebarDiagnostics.Windows;
using SidebarDiagnostics.Style;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for Update.xaml
/// </summary>
public partial class Update : FlatWindow
{
public Update()
{
InitializeComponent();
DataContext = Model = new UpdateModel();
}
public void SetProgress(double percent)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
{
Model.Progress = percent;
}));
}
public new void Close()
{
_close = true;
base.Close();
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
DragMove();
}
protected override void OnClosing(CancelEventArgs e)
{
if (_close)
{
base.OnClosing(e);
}
else
{
e.Cancel = true;
}
}
public UpdateModel Model { get; private set; }
private bool _close { get; set; } = false;
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Update.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 248 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using SidebarDiagnostics.Windows;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for Dummy.xaml
/// </summary>
public partial class Dummy : AppBarWindow
{
public Dummy(Setup setup)
{
InitializeComponent();
Setup = setup;
}
public void Reposition()
{
Monitor.GetWorkArea(this, out int _screen, out DockEdge _edge, out WorkArea _initPos, out WorkArea _windowWA, out WorkArea _appbarWA);
Move(_initPos);
Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() =>
{
Move(_windowWA);
}));
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Reposition();
Setup.Owner = this;
Setup.ShowDialog();
}
private void Window_StateChanged(object sender, EventArgs e)
{
if (WindowState != WindowState.Normal)
{
WindowState = WindowState.Normal;
}
}
public Setup Setup { get; private set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Dummy.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 244 |
```smalltalk
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using OxyPlot.Wpf;
using SidebarDiagnostics.Framework;
using SidebarDiagnostics.Monitoring;
namespace SidebarDiagnostics.Models
{
public class GraphModel : INotifyPropertyChanged, IDisposable
{
public GraphModel(Plot plot)
{
_plot = plot;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_monitorItems = null;
_monitor = null;
_hardwareItems = null;
_hardware = null;
_metricItems = null;
if (_metrics != null)
{
_metrics.CollectionChanged -= Metrics_CollectionChanged;
foreach (iMetric _metric in _metrics)
{
_metric.PropertyChanged -= Metric_PropertyChanged;
}
_metrics = null;
}
_plot = null;
_data = null;
}
_disposed = true;
}
}
~GraphModel()
{
Dispose(false);
}
public void BindData(MonitorManager manager)
{
BindMonitors(manager.MonitorPanels);
ExpandConfig = true;
}
public void SetupPlot()
{
_data = new Dictionary<iMetric, ObservableCollection<MetricRecord>>();
_plot.Series.Clear();
foreach (iMetric _metric in Metrics)
{
ObservableCollection<MetricRecord> _records = new ObservableCollection<MetricRecord>();
_data.Add(_metric, _records);
_metric.PropertyChanged += Metric_PropertyChanged;
_plot.Series.Add(
new LineSeries()
{
Title = _metric.FullName,
TrackerFormatString = string.Format("{0}\r\n{{Value:#,##0.##}}{1}\r\n{{Recorded:T}}", _metric.FullName, _metric.nAppend),
ItemsSource = _records,
DataFieldX = "Recorded",
DataFieldY = "Value"
});
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void BindMonitors(MonitorPanel[] panels)
{
MonitorItems = panels;
if (panels.Length > 0)
{
Monitor = panels[0];
}
else
{
Monitor = null;
}
}
private void BindHardware(iMonitor[] monitors)
{
HardwareItems = monitors;
if (monitors.Length > 0)
{
Hardware = monitors[0];
}
else
{
Hardware = null;
}
}
private void BindMetrics(iMetric[] metrics)
{
MetricItems = metrics;
Metrics = new ObservableCollection<iMetric>();
}
private void Metrics_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (iMetric _metric in e.OldItems)
{
_metric.PropertyChanged -= Metric_PropertyChanged;
}
}
SetupPlot();
}
private void Metric_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (_disposed)
{
(sender as iMetric).PropertyChanged -= Metric_PropertyChanged;
return;
}
if (e.PropertyName != "nValue")
{
return;
}
iMetric _metric = (iMetric)sender;
if (_data == null || !_data.ContainsKey(_metric))
{
_metric.PropertyChanged -= Metric_PropertyChanged;
return;
}
DateTime _now = DateTime.Now;
try
{
ObservableCollection<MetricRecord> _mData = _data[_metric];
foreach (MetricRecord _record in _mData.Where(r => (_now - r.Recorded).TotalSeconds > Duration).ToArray())
{
_mData.Remove(_record);
}
_mData.Add(new MetricRecord(_metric.nValue, _now));
}
catch
{
_metric.PropertyChanged -= Metric_PropertyChanged;
}
}
private string _title { get; set; } = Resources.GraphTitle;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
NotifyPropertyChanged("Title");
}
}
private MonitorPanel[] _monitorItems { get; set; }
public MonitorPanel[] MonitorItems
{
get
{
return _monitorItems;
}
set
{
_monitorItems = value;
NotifyPropertyChanged("MonitorItems");
}
}
private MonitorPanel _monitor { get; set; }
public MonitorPanel Monitor
{
get
{
return _monitor;
}
set
{
_monitor = value;
if (_monitor == null)
{
BindHardware(new iMonitor[0]);
}
else
{
BindHardware(_monitor.Monitors);
}
NotifyPropertyChanged("Monitor");
}
}
private iMonitor[] _hardwareItems { get; set; }
public iMonitor[] HardwareItems
{
get
{
return _hardwareItems;
}
set
{
_hardwareItems = value;
NotifyPropertyChanged("HardwareItems");
}
}
private iMonitor _hardware { get; set; }
public iMonitor Hardware
{
get
{
return _hardware;
}
set
{
_hardware = value;
if (_hardware == null)
{
BindMetrics(new iMetric[0]);
Title = Resources.GraphTitle;
}
else
{
BindMetrics(_hardware.Metrics.Where(m => m.IsNumeric).ToArray());
Title = string.Format("{0} - {1}", Resources.GraphTitle, _hardware.Name);
}
NotifyPropertyChanged("Hardware");
}
}
private iMetric[] _metricItems { get; set; }
public iMetric[] MetricItems
{
get
{
return _metricItems;
}
set
{
_metricItems = value;
NotifyPropertyChanged("MetricItems");
}
}
private ObservableCollection<iMetric> _metrics { get; set; }
public ObservableCollection<iMetric> Metrics
{
get
{
return _metrics;
}
set
{
if (_metrics != null)
{
foreach (iMetric _metric in _metrics)
{
_metric.PropertyChanged -= Metric_PropertyChanged;
}
}
_metrics = value;
if (_metrics != null)
{
SetupPlot();
_metrics.CollectionChanged += Metrics_CollectionChanged;
}
NotifyPropertyChanged("Metrics");
}
}
public DurationItem[] DurationItems
{
get
{
return new DurationItem[5]
{
new DurationItem(15, string.Format("15 {0}", Resources.GraphDurationSeconds)),
new DurationItem(30, string.Format("30 {0}", Resources.GraphDurationSeconds)),
new DurationItem(60, string.Format("1 {0}", Resources.GraphDurationMinute)),
new DurationItem(300, string.Format("5 {0}", Resources.GraphDurationMinutes)),
new DurationItem(900, string.Format("15 {0}", Resources.GraphDurationMinutes))
};
}
}
private int _duration { get; set; } = 15;
public int Duration
{
get
{
return _duration;
}
set
{
_duration = value;
NotifyPropertyChanged("Duration");
}
}
private bool _expandConfig { get; set; } = true;
public bool ExpandConfig
{
get
{
return _expandConfig;
}
set
{
_expandConfig = value;
NotifyPropertyChanged("ExpandConfig");
}
}
private Plot _plot { get; set; }
private Dictionary<iMetric, ObservableCollection<MetricRecord>> _data { get; set; }
private bool _disposed { get; set; } = false;
}
public class DurationItem
{
public DurationItem(int seconds, string text)
{
Seconds = seconds;
Text = text;
}
public int Seconds { get; set; }
public string Text { get; set; }
}
public class MetricRecord
{
public MetricRecord(double value, DateTime recorded)
{
Value = value > 0 ? value : 0.001d;
Recorded = recorded;
}
public double Value { get; set; }
public DateTime Recorded { get; set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/GraphModel.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1,864 |
```smalltalk
using System;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Markup;
using Microsoft.Win32.TaskScheduler;
using SidebarDiagnostics.Framework;
using System.Diagnostics;
namespace SidebarDiagnostics.Utilities
{
public static class Paths
{
private const string SETTINGS = "settings.json";
private const string CHANGELOG = "ChangeLog.json";
public static string Install(Version version)
{
return Path.Combine(LocalApp, string.Format("app-{0}", version.ToString(3)));
}
public static string Exe(Version version)
{
return Path.Combine(Install(version), ExeName);
}
public static string ChangeLog
{
get
{
return Path.Combine(CurrentDirectory, CHANGELOG);
}
}
public static string CurrentDirectory
{
get
{
return Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
}
}
public static string TaskBar
{
get
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar");
}
}
private static string _assemblyName { get; set; } = null;
public static string AssemblyName
{
get
{
if (_assemblyName == null)
{
_assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
}
return _assemblyName;
}
}
private static string _exeName { get; set; } = null;
public static string ExeName
{
get
{
if (_exeName == null)
{
_exeName = string.Format("{0}.exe", AssemblyName);
}
return _exeName;
}
}
private static string _settingsFile { get; set; } = null;
public static string SettingsFile
{
get
{
if (_settingsFile == null)
{
_settingsFile = Path.Combine(LocalApp, SETTINGS);
}
return _settingsFile;
}
}
private static string _localApp { get; set; } = null;
public static string LocalApp
{
get
{
if (_localApp == null)
{
_localApp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyName);
}
return _localApp;
}
}
}
public static class Startup
{
public static bool StartupTaskExists()
{
using (TaskService _taskService = new TaskService())
{
Task _task = _taskService.FindTask(Constants.Generic.TASKNAME);
if (_task == null)
{
return false;
}
ExecAction _action = _task.Definition.Actions.OfType<ExecAction>().FirstOrDefault();
if (_action == null || _action.Path != Assembly.GetExecutingAssembly().Location)
{
return false;
}
return true;
}
}
public static void EnableStartupTask(string exePath = null)
{
try
{
using (TaskService _taskService = new TaskService())
{
TaskDefinition _def = _taskService.NewTask();
_def.Triggers.Add(new LogonTrigger() { Enabled = true });
_def.Actions.Add(new ExecAction(exePath ?? Assembly.GetExecutingAssembly().Location));
_def.Principal.RunLevel = TaskRunLevel.Highest;
_def.Settings.DisallowStartIfOnBatteries = false;
_def.Settings.StopIfGoingOnBatteries = false;
_def.Settings.ExecutionTimeLimit = TimeSpan.Zero;
_taskService.RootFolder.RegisterTaskDefinition(Constants.Generic.TASKNAME, _def);
}
}
catch (Exception e)
{
using (EventLog _log = new EventLog("Application"))
{
_log.Source = Resources.AppName;
_log.WriteEntry(e.ToString(), EventLogEntryType.Error, 100, 1);
}
}
}
public static void DisableStartupTask()
{
using (TaskService _taskService = new TaskService())
{
_taskService.RootFolder.DeleteTask(Constants.Generic.TASKNAME, false);
}
}
}
public static class Culture
{
public const string DEFAULT = "Default";
public static void SetDefault()
{
Default = Thread.CurrentThread.CurrentUICulture;
}
public static void SetCurrent(bool init)
{
Resources.Culture = CultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo;
Thread.CurrentThread.CurrentUICulture = CultureInfo;
if (init)
{
FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.Name)));
}
}
public static CultureItem[] GetAll()
{
return new CultureItem[1] { new CultureItem() { Value = DEFAULT, Text = Resources.SettingsLanguageDefault } }.Concat(CultureInfo.GetCultures(CultureTypes.SpecificCultures).Where(c => Languages.Contains(c.TwoLetterISOLanguageName)).OrderBy(c => c.DisplayName).Select(c => new CultureItem() { Value = c.Name, Text = c.DisplayName })).ToArray();
}
public static string[] Languages
{
get
{
return new string[11] { "en", "da", "de", "fr", "ja", "nl", "zh", "it", "ru", "fi", "es" };
}
}
public static CultureInfo Default { get; private set; }
public static CultureInfo CultureInfo
{
get
{
string culture = Framework.Settings.Instance.Culture;
return string.Equals(culture, DEFAULT, StringComparison.Ordinal)
? Default
: new CultureInfo(culture);
}
}
}
public class CultureItem
{
public string Value { get; set; }
public string Text { get; set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Utilities.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1,262 |
```smalltalk
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows;
using SidebarDiagnostics.Utilities;
using SidebarDiagnostics.Monitoring;
using SidebarDiagnostics.Windows;
using SidebarDiagnostics.Framework;
namespace SidebarDiagnostics.Models
{
public class SettingsModel : INotifyPropertyChanged
{
public SettingsModel(Sidebar sidebar)
{
DockEdgeItems = new DockItem[2]
{
new DockItem() { Text = Resources.SettingsDockLeft, Value = DockEdge.Left },
new DockItem() { Text = Resources.SettingsDockRight, Value = DockEdge.Right }
};
DockEdge = Framework.Settings.Instance.DockEdge;
Monitor[] _monitors = Monitor.GetMonitors();
ScreenItems = _monitors.Select((s, i) => new ScreenItem() { Index = i, Text = string.Format("#{0}", i + 1) }).ToArray();
if (Framework.Settings.Instance.ScreenIndex < _monitors.Length)
{
ScreenIndex = Framework.Settings.Instance.ScreenIndex;
}
else
{
ScreenIndex = _monitors.Where(s => s.IsPrimary).Select((s, i) => i).Single();
}
CultureItems = Utilities.Culture.GetAll();
Culture = Framework.Settings.Instance.Culture;
UIScale = Framework.Settings.Instance.UIScale;
XOffset = Framework.Settings.Instance.XOffset;
YOffset = Framework.Settings.Instance.YOffset;
PollingInterval = Framework.Settings.Instance.PollingInterval;
UseAppBar = Framework.Settings.Instance.UseAppBar;
AlwaysTop = Framework.Settings.Instance.AlwaysTop;
ToolbarMode = Framework.Settings.Instance.ToolbarMode;
ClickThrough = Framework.Settings.Instance.ClickThrough;
ShowTrayIcon = Framework.Settings.Instance.ShowTrayIcon;
AutoUpdate = Framework.Settings.Instance.AutoUpdate;
RunAtStartup = Framework.Settings.Instance.RunAtStartup;
SidebarWidth = Framework.Settings.Instance.SidebarWidth;
AutoBGColor = Framework.Settings.Instance.AutoBGColor;
BGColor = Framework.Settings.Instance.BGColor;
BGOpacity = Framework.Settings.Instance.BGOpacity;
TextAlignItems = new TextAlignItem[2]
{
new TextAlignItem() { Text = Resources.SettingsTextAlignLeft, Value = TextAlign.Left },
new TextAlignItem() { Text = Resources.SettingsTextAlignRight, Value = TextAlign.Right }
};
TextAlign = Framework.Settings.Instance.TextAlign;
FontSettingItems = new FontSetting[5]
{
FontSetting.x10,
FontSetting.x12,
FontSetting.x14,
FontSetting.x16,
FontSetting.x18
};
FontSetting = Framework.Settings.Instance.FontSetting;
FontColor = Framework.Settings.Instance.FontColor;
AlertFontColor = Framework.Settings.Instance.AlertFontColor;
AlertBlink = Framework.Settings.Instance.AlertBlink;
DateSettingItems = new DateSetting[4]
{
DateSetting.Disabled,
DateSetting.Short,
DateSetting.Normal,
DateSetting.Long
};
DateSetting = Framework.Settings.Instance.DateSetting;
CollapseMenuBar = Framework.Settings.Instance.CollapseMenuBar;
InitiallyHidden = Framework.Settings.Instance.InitiallyHidden;
ShowMachineName = Framework.Settings.Instance.ShowMachineName;
ShowClock = Framework.Settings.Instance.ShowClock;
Clock24HR = Framework.Settings.Instance.Clock24HR;
ObservableCollection<MonitorConfig> _config = new ObservableCollection<MonitorConfig>(Framework.Settings.Instance.MonitorConfig.Select(c => c.Clone()).OrderByDescending(c => c.Order));
if (sidebar.Ready)
{
foreach (MonitorConfig _record in _config)
{
_record.HardwareOC = new ObservableCollection<HardwareConfig>(
from hw in sidebar.Model.MonitorManager.GetHardware(_record.Type)
join config in _record.Hardware on hw.ID equals config.ID into merged
from newhw in merged.DefaultIfEmpty(hw).Select(newhw => { newhw.ActualName = hw.ActualName; if (string.IsNullOrEmpty(newhw.Name)) { newhw.Name = hw.ActualName; } return newhw; })
orderby newhw.Order descending, newhw.Name ascending
select newhw
);
}
}
MonitorConfig = _config;
if (Framework.Settings.Instance.Hotkeys != null)
{
ToggleKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Toggle);
ShowKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Show);
HideKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Hide);
ReloadKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Reload);
CloseKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Close);
CycleEdgeKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.CycleEdge);
CycleScreenKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.CycleScreen);
ReserveSpaceKey = Framework.Settings.Instance.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.ReserveSpace);
}
IsChanged = false;
}
public void Save()
{
if (!string.Equals(Culture, Framework.Settings.Instance.Culture, StringComparison.Ordinal))
{
MessageBox.Show(Resources.LanguageChangedText, Resources.LanguageChangedTitle, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
}
Framework.Settings.Instance.DockEdge = DockEdge;
Framework.Settings.Instance.ScreenIndex = ScreenIndex;
Framework.Settings.Instance.Culture = Culture;
Framework.Settings.Instance.UIScale = UIScale;
Framework.Settings.Instance.XOffset = XOffset;
Framework.Settings.Instance.YOffset = YOffset;
Framework.Settings.Instance.PollingInterval = PollingInterval;
Framework.Settings.Instance.UseAppBar = UseAppBar;
Framework.Settings.Instance.AlwaysTop = AlwaysTop;
Framework.Settings.Instance.ToolbarMode = ToolbarMode;
Framework.Settings.Instance.ClickThrough = ClickThrough;
Framework.Settings.Instance.ShowTrayIcon = ShowTrayIcon;
Framework.Settings.Instance.AutoUpdate = AutoUpdate;
Framework.Settings.Instance.RunAtStartup = RunAtStartup;
Framework.Settings.Instance.SidebarWidth = SidebarWidth;
Framework.Settings.Instance.AutoBGColor = AutoBGColor;
Framework.Settings.Instance.BGColor = BGColor;
Framework.Settings.Instance.BGOpacity = BGOpacity;
Framework.Settings.Instance.TextAlign = TextAlign;
Framework.Settings.Instance.FontSetting = FontSetting;
Framework.Settings.Instance.FontColor = FontColor;
Framework.Settings.Instance.AlertFontColor = AlertFontColor;
Framework.Settings.Instance.AlertBlink = AlertBlink;
Framework.Settings.Instance.DateSetting = DateSetting;
Framework.Settings.Instance.CollapseMenuBar = CollapseMenuBar;
Framework.Settings.Instance.InitiallyHidden = InitiallyHidden;
Framework.Settings.Instance.ShowMachineName = ShowMachineName;
Framework.Settings.Instance.ShowClock = ShowClock;
Framework.Settings.Instance.Clock24HR = Clock24HR;
MonitorConfig[] _config = MonitorConfig.Select(c => c.Clone()).ToArray();
for (int i = 0; i < _config.Length; i++)
{
HardwareConfig[] _hardware = _config[i].HardwareOC.ToArray();
for (int v = 0; v < _hardware.Length; v++)
{
_hardware[v].Order = Convert.ToByte(_hardware.Length - v);
if (string.IsNullOrEmpty(_hardware[v].Name) || string.Equals(_hardware[v].Name, _hardware[v].ActualName, StringComparison.Ordinal))
{
_hardware[v].Name = null;
}
}
_config[i].Hardware = _hardware;
_config[i].HardwareOC = null;
_config[i].Order = Convert.ToByte(_config.Length - i);
}
Framework.Settings.Instance.MonitorConfig = _config;
List<Hotkey> _hotkeys = new List<Hotkey>();
if (ToggleKey != null)
{
_hotkeys.Add(ToggleKey);
}
if (ShowKey != null)
{
_hotkeys.Add(ShowKey);
}
if (HideKey != null)
{
_hotkeys.Add(HideKey);
}
if (ReloadKey != null)
{
_hotkeys.Add(ReloadKey);
}
if (CloseKey != null)
{
_hotkeys.Add(CloseKey);
}
if (CycleEdgeKey != null)
{
_hotkeys.Add(CycleEdgeKey);
}
if (CycleScreenKey != null)
{
_hotkeys.Add(CycleScreenKey);
}
if (ReserveSpaceKey != null)
{
_hotkeys.Add(ReserveSpaceKey);
}
Framework.Settings.Instance.Hotkeys = _hotkeys.ToArray();
Framework.Settings.Instance.Save();
App.RefreshIcon();
if (RunAtStartup)
{
Startup.EnableStartupTask();
}
else
{
Startup.DisableStartupTask();
}
IsChanged = false;
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
if (propertyName != "IsChanged")
{
IsChanged = true;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void Child_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
IsChanged = true;
}
private void Child_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IsChanged = true;
}
private bool _isChanged { get; set; } = false;
public bool IsChanged
{
get
{
return _isChanged;
}
set
{
_isChanged = value;
NotifyPropertyChanged("IsChanged");
}
}
private DockEdge _dockEdge { get; set; }
public DockEdge DockEdge
{
get
{
return _dockEdge;
}
set
{
_dockEdge = value;
NotifyPropertyChanged("DockEdge");
}
}
private DockItem[] _dockEdgeItems { get; set; }
public DockItem[] DockEdgeItems
{
get
{
return _dockEdgeItems;
}
set
{
_dockEdgeItems = value;
NotifyPropertyChanged("DockEdgeItems");
}
}
private int _screenIndex { get; set; }
public int ScreenIndex
{
get
{
return _screenIndex;
}
set
{
_screenIndex = value;
NotifyPropertyChanged("ScreenIndex");
}
}
private ScreenItem[] _screenItems { get; set; }
public ScreenItem[] ScreenItems
{
get
{
return _screenItems;
}
set
{
_screenItems = value;
NotifyPropertyChanged("ScreenItems");
}
}
private string _culture { get; set; }
public string Culture
{
get
{
return _culture;
}
set
{
_culture = value;
NotifyPropertyChanged("Culture");
}
}
private CultureItem[] _cultureItems { get; set; }
public CultureItem[] CultureItems
{
get
{
return _cultureItems;
}
set
{
_cultureItems = value;
NotifyPropertyChanged("CultureItems");
}
}
private double _uiScale { get; set; }
public double UIScale
{
get
{
return _uiScale;
}
set
{
_uiScale = value;
NotifyPropertyChanged("UIScale");
}
}
private int _xOffset { get; set; }
public int XOffset
{
get
{
return _xOffset;
}
set
{
_xOffset = value;
NotifyPropertyChanged("XOffset");
}
}
private int _yOffset { get; set; }
public int YOffset
{
get
{
return _yOffset;
}
set
{
_yOffset = value;
NotifyPropertyChanged("YOffset");
}
}
private int _pollingInterval { get; set; }
public int PollingInterval
{
get
{
return _pollingInterval;
}
set
{
_pollingInterval = value;
NotifyPropertyChanged("PollingInterval");
}
}
private bool _useAppBar { get; set; }
public bool UseAppBar
{
get
{
return _useAppBar;
}
set
{
_useAppBar = value;
NotifyPropertyChanged("UseAppBar");
}
}
private bool _alwaysTop { get; set; }
public bool AlwaysTop
{
get
{
return _alwaysTop;
}
set
{
_alwaysTop = value;
NotifyPropertyChanged("AlwaysTop");
}
}
private bool _toolbarMode { get; set; }
public bool ToolbarMode
{
get
{
return _toolbarMode;
}
set
{
_toolbarMode = value;
NotifyPropertyChanged("ToolbarMode");
}
}
private bool _clickThrough { get; set; }
public bool ClickThrough
{
get
{
return _clickThrough;
}
set
{
_clickThrough = value;
NotifyPropertyChanged("ClickThrough");
}
}
private bool _showTrayIcon { get; set; }
public bool ShowTrayIcon
{
get
{
return _showTrayIcon;
}
set
{
_showTrayIcon = value;
NotifyPropertyChanged("ShowTrayIcon");
}
}
private bool _autoUpdate { get; set; }
public bool AutoUpdate
{
get
{
return _autoUpdate;
}
set
{
_autoUpdate = value;
NotifyPropertyChanged("AutoUpdate");
}
}
private bool _runAtStartup { get; set; }
public bool RunAtStartup
{
get
{
return _runAtStartup;
}
set
{
_runAtStartup = value;
NotifyPropertyChanged("RunAtStartup");
}
}
private int _sidebarWidth { get; set; }
public int SidebarWidth
{
get
{
return _sidebarWidth;
}
set
{
_sidebarWidth = value;
NotifyPropertyChanged("SidebarWidth");
}
}
private bool _autoBGColor { get; set; }
public bool AutoBGColor
{
get
{
return _autoBGColor;
}
set
{
_autoBGColor = value;
NotifyPropertyChanged("AutoBGColor");
}
}
private string _bgColor { get; set; }
public string BGColor
{
get
{
return _bgColor;
}
set
{
_bgColor = value;
NotifyPropertyChanged("BGColor");
}
}
private double _bgOpacity { get; set; }
public double BGOpacity
{
get
{
return _bgOpacity;
}
set
{
_bgOpacity = value;
NotifyPropertyChanged("BGOpacity");
}
}
private TextAlign _textAlign { get; set; }
public TextAlign TextAlign
{
get
{
return _textAlign;
}
set
{
_textAlign = value;
NotifyPropertyChanged("TextAlign");
}
}
private TextAlignItem[] _textAlignItems { get; set; }
public TextAlignItem[] TextAlignItems
{
get
{
return _textAlignItems;
}
set
{
_textAlignItems = value;
NotifyPropertyChanged("TextAlignItems");
}
}
private FontSetting _fontSetting { get; set; }
public FontSetting FontSetting
{
get
{
return _fontSetting;
}
set
{
_fontSetting = value;
NotifyPropertyChanged("FontSize");
}
}
private FontSetting[] _fontSettingItems { get; set;}
public FontSetting[] FontSettingItems
{
get
{
return _fontSettingItems;
}
set
{
_fontSettingItems = value;
NotifyPropertyChanged("FontSizeItems");
}
}
private string _fontColor { get; set; }
public string FontColor
{
get
{
return _fontColor;
}
set
{
_fontColor = value;
NotifyPropertyChanged("FontColor");
}
}
private string _alertFontColor { get; set; }
public string AlertFontColor
{
get
{
return _alertFontColor;
}
set
{
_alertFontColor = value;
NotifyPropertyChanged("AlertFontColor");
}
}
private bool _alertBlink { get; set; } = true;
public bool AlertBlink
{
get
{
return _alertBlink;
}
set
{
_alertBlink = value;
NotifyPropertyChanged("AlertBlink");
}
}
private DateSetting _dateSetting { get; set; }
public DateSetting DateSetting
{
get
{
return _dateSetting;
}
set
{
_dateSetting = value;
NotifyPropertyChanged("DateSetting");
}
}
private DateSetting[] _dateSettingItems { get; set; }
public DateSetting[] DateSettingItems
{
get
{
return _dateSettingItems;
}
set
{
_dateSettingItems = value;
NotifyPropertyChanged("DateSettingItems");
}
}
private bool _collapseMenuBar { get; set; }
public bool CollapseMenuBar
{
get
{
return _collapseMenuBar;
}
set
{
_collapseMenuBar = value;
NotifyPropertyChanged("CollapseMenuBar");
}
}
private bool _initiallyHidden { get; set; }
public bool InitiallyHidden
{
get
{
return _initiallyHidden;
}
set
{
_initiallyHidden = value;
NotifyPropertyChanged("InitiallyHidden");
}
}
private bool _showMachineName { get; set; } = true;
public bool ShowMachineName
{
get
{
return _showMachineName;
}
set
{
_showMachineName = value;
NotifyPropertyChanged("ShowMachineName");
}
}
private bool _showClock { get; set; }
public bool ShowClock
{
get
{
return _showClock;
}
set
{
_showClock = value;
NotifyPropertyChanged("ShowClock");
}
}
private bool _clock24HR { get; set; }
public bool Clock24HR
{
get
{
return _clock24HR;
}
set
{
_clock24HR = value;
NotifyPropertyChanged("Clock24HR");
}
}
private ObservableCollection<MonitorConfig> _monitorConfig { get; set; }
public ObservableCollection<MonitorConfig> MonitorConfig
{
get
{
return _monitorConfig;
}
set
{
_monitorConfig = value;
_monitorConfig.CollectionChanged += Child_CollectionChanged;
foreach (MonitorConfig _config in _monitorConfig)
{
_config.PropertyChanged += Child_PropertyChanged;
_config.HardwareOC.CollectionChanged += Child_CollectionChanged;
foreach (HardwareConfig _hardware in _config.HardwareOC)
{
_hardware.PropertyChanged += Child_PropertyChanged;
}
foreach (MetricConfig _metric in _config.Metrics)
{
_metric.PropertyChanged += Child_PropertyChanged;
}
foreach (ConfigParam _param in _config.Params)
{
_param.PropertyChanged += Child_PropertyChanged;
}
}
NotifyPropertyChanged("MonitorConfig");
}
}
private Hotkey _toggleKey { get; set; }
public Hotkey ToggleKey
{
get
{
return _toggleKey;
}
set
{
_toggleKey = value;
NotifyPropertyChanged("ToggleKey");
}
}
private Hotkey _showKey { get; set; }
public Hotkey ShowKey
{
get
{
return _showKey;
}
set
{
_showKey = value;
NotifyPropertyChanged("ShowKey");
}
}
private Hotkey _hideKey { get; set; }
public Hotkey HideKey
{
get
{
return _hideKey;
}
set
{
_hideKey = value;
NotifyPropertyChanged("HideKey");
}
}
private Hotkey _reloadKey { get; set; }
public Hotkey ReloadKey
{
get
{
return _reloadKey;
}
set
{
_reloadKey = value;
NotifyPropertyChanged("ReloadKey");
}
}
private Hotkey _closeKey { get; set; }
public Hotkey CloseKey
{
get
{
return _closeKey;
}
set
{
_closeKey = value;
NotifyPropertyChanged("CloseKey");
}
}
private Hotkey _cycleEdgeKey { get; set; }
public Hotkey CycleEdgeKey
{
get
{
return _cycleEdgeKey;
}
set
{
_cycleEdgeKey = value;
NotifyPropertyChanged("CycleEdgeKey");
}
}
private Hotkey _cycleScreenKey { get; set; }
public Hotkey CycleScreenKey
{
get
{
return _cycleScreenKey;
}
set
{
_cycleScreenKey = value;
NotifyPropertyChanged("CycleScreenKey");
}
}
private Hotkey _reserveSpaceKey { get; set; }
public Hotkey ReserveSpaceKey
{
get
{
return _reserveSpaceKey;
}
set
{
_reserveSpaceKey = value;
NotifyPropertyChanged("ReserveSpaceKey");
}
}
}
public class DockItem
{
public DockEdge Value { get; set; }
public string Text { get; set; }
}
public class ScreenItem
{
public int Index { get; set; }
public string Text { get; set; }
}
public class TextAlignItem
{
public TextAlign Value { get; set; }
public string Text { get; set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/SettingsModel.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 4,873 |
```smalltalk
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace SidebarDiagnostics.Commands
{
public class ActivateCommand : ICommand
{
public void Execute(object parameter)
{
Sidebar _sidebar = App.Current.Sidebar;
if (_sidebar == null)
{
return;
}
_sidebar.Activate();
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Commands.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 103 |
```smalltalk
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using SidebarDiagnostics.Windows;
namespace SidebarDiagnostics.Converters
{
public class IntToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string _format = (string)parameter;
if (string.IsNullOrEmpty(_format))
{
return value.ToString();
}
else
{
return string.Format(culture, _format, value);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
int _return = 0;
int.TryParse(value.ToString(), out _return);
return _return;
}
}
public class HotkeyToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Hotkey _hotkey = (Hotkey)value;
if (_hotkey == null)
{
return "None";
}
return
(_hotkey.AltMod ? "Alt + " : "") +
(_hotkey.CtrlMod ? "Ctrl + " : "") +
(_hotkey.ShiftMod ? "Shift + " : "") +
(_hotkey.WinMod ? "Win + " : "") +
new KeyConverter().ConvertToString(_hotkey.WinKey);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
public class PercentConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double _value = (double)value;
return string.Format("{0:0}%", _value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
public class BoolInverseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(bool)value;
}
}
public class MetricLabelConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string _value = (string)value;
return string.Format("{0}:", _value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
public class FontToSpaceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int _value = (int)value;
return new Thickness(0, 0, _value * 0.4d, 0);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Converters.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 648 |
```smalltalk
using System.ComponentModel;
namespace SidebarDiagnostics.Models
{
public class UpdateModel : INotifyPropertyChanged
{
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private double _progress { get; set; } = 0d;
public double Progress
{
get
{
return _progress;
}
set
{
_progress = value;
NotifyPropertyChanged("Progress");
NotifyPropertyChanged("ProgressNormalized");
}
}
public double ProgressNormalized
{
get
{
return _progress / 100d;
}
}
}
}
``` | /content/code_sandbox/SidebarDiagnostics/UpdateModel.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 154 |
```smalltalk
using System;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using SidebarDiagnostics.Models;
using SidebarDiagnostics.Windows;
using SidebarDiagnostics.Style;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for Settings.xaml
/// </summary>
public partial class Settings : FlatWindow
{
public Settings(Sidebar sidebar)
{
InitializeComponent();
DataContext = Model = new SettingsModel(sidebar);
Owner = sidebar;
ShowDialog();
}
private async Task Save(bool finalize)
{
Model.Save();
await App.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(async () =>
{
Sidebar _sidebar = App.Current.Sidebar;
if (_sidebar == null)
{
return;
}
await _sidebar.Reset(finalize);
}));
}
private void NumberBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (new Regex("[^0-9.-]+").IsMatch(e.Text))
{
e.Handled = true;
}
}
private void OffsetSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (e.NewValue != 0d)
{
ShowTrayIconCheckbox.IsChecked = true;
}
}
private void ClickThroughCheckbox_Checked(object sender, RoutedEventArgs e)
{
ShowTrayIconCheckbox.IsChecked = true;
}
private void ShowTrayIconCheckbox_Unchecked(object sender, RoutedEventArgs e)
{
XOffsetSlider.Value = 0d;
YOffsetSlider.Value = 0d;
ClickThroughCheckbox.IsChecked = false;
}
private void BindButton_LostFocus(object sender, RoutedEventArgs e)
{
if (_hotkey != null)
{
EndBind();
}
(sender as ToggleButton).IsChecked = false;
}
private void BindToggle_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.Toggle);
}
else
{
EndBind();
}
}
private void BindShow_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.Show);
}
else
{
EndBind();
}
}
private void BindHide_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.Hide);
}
else
{
EndBind();
}
}
private void BindReload_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.Reload);
}
else
{
EndBind();
}
}
private void BindClose_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.Close);
}
else
{
EndBind();
}
}
private void BindCycleEdge_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.CycleEdge);
}
else
{
EndBind();
}
}
private void BindCycleScreen_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.CycleScreen);
}
else
{
EndBind();
}
}
private void BindReserveSpace_Click(object sender, RoutedEventArgs e)
{
_keybinder = (ToggleButton)sender;
if (_keybinder.IsChecked == true)
{
BeginBind(Hotkey.KeyAction.ReserveSpace);
}
else
{
EndBind();
}
}
private void BeginBind(Hotkey.KeyAction action)
{
_hotkey = new Hotkey();
_hotkey.Action = action;
_hotkey.WinKey = Key.Escape;
KeyDown += Window_KeyDown;
}
private void EndBind()
{
KeyDown -= Window_KeyDown;
Hotkey.KeyAction _action = _hotkey.Action;
if (_hotkey.WinKey == Key.Escape)
{
_hotkey = null;
}
switch (_action)
{
case Hotkey.KeyAction.Toggle:
Model.ToggleKey = _hotkey;
break;
case Hotkey.KeyAction.Show:
Model.ShowKey = _hotkey;
break;
case Hotkey.KeyAction.Hide:
Model.HideKey = _hotkey;
break;
case Hotkey.KeyAction.Reload:
Model.ReloadKey = _hotkey;
break;
case Hotkey.KeyAction.Close:
Model.CloseKey = _hotkey;
break;
case Hotkey.KeyAction.CycleEdge:
Model.CycleEdgeKey = _hotkey;
break;
case Hotkey.KeyAction.CycleScreen:
Model.CycleScreenKey = _hotkey;
break;
case Hotkey.KeyAction.ReserveSpace:
Model.ReserveSpaceKey = _hotkey;
break;
}
_keybinder.IsChecked = false;
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
Key _key = e.Key == Key.System ? e.SystemKey : e.Key;
if (new Key[] { Key.LeftAlt, Key.RightAlt, Key.LeftCtrl, Key.RightCtrl, Key.LeftShift, Key.RightShift, Key.LWin, Key.RWin }.Contains(_key))
{
return;
}
if ((e.KeyboardDevice.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
_hotkey.CtrlMod = true;
}
if ((e.KeyboardDevice.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
{
_hotkey.ShiftMod = true;
}
if ((e.KeyboardDevice.Modifiers & ModifierKeys.Windows) == ModifierKeys.Windows)
{
_hotkey.WinMod = true;
}
if ((e.KeyboardDevice.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
{
_hotkey.AltMod = true;
}
_hotkey.WinKey = _key;
EndBind();
e.Handled = true;
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
await Save(true);
Close();
}
private async void ApplyButton_Click(object sender, RoutedEventArgs e)
{
await Save(false);
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
if (Model.IsChanged)
{
Sidebar _sidebar = App.Current.Sidebar;
if (_sidebar != null)
{
DataContext = Model = new SettingsModel(_sidebar);
return;
}
}
Close();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Hotkey.Disable();
}
private void Window_Closing(object sender, CancelEventArgs e)
{
DataContext = null;
Model = null;
}
private void Window_Closed(object sender, EventArgs e)
{
Hotkey.Enable();
}
public SettingsModel Model { get; private set; }
private Hotkey _hotkey { get; set; }
private ToggleButton _keybinder { get; set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Settings.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1,670 |
```smalltalk
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using SidebarDiagnostics.Windows;
using SidebarDiagnostics.Models;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for Sidebar.xaml
/// </summary>
public partial class Sidebar : AppBarWindow
{
public Sidebar(bool openSettings, bool initiallyHidden)
{
InitializeComponent();
_openSettings = openSettings;
_initiallyHidden = initiallyHidden;
}
public void Reload()
{
if (!Ready)
{
return;
}
Ready = false;
App._reloading = true;
Close();
}
public async Task Reset(bool enableHotkeys)
{
if (!Ready)
{
return;
}
Ready = false;
await BindSettings(enableHotkeys);
await BindModel();
}
public async Task Reposition()
{
if (!Ready)
{
return;
}
Ready = false;
await BindPosition();
Ready = true;
}
public void ContentReload()
{
if (!Ready)
{
return;
}
Ready = false;
Model.Reload();
Ready = true;
BindGraphs();
}
public override async Task AppBarShow()
{
await base.AppBarShow();
Model.Resume();
}
public override void AppBarHide()
{
base.AppBarHide();
Model.Pause();
}
private async Task Initialize()
{
Ready = false;
Devices.AddHook(this);
DisableAeroPeek();
await BindSettings(true);
await BindModel();
}
private async Task BindSettings(bool enableHotkeys)
{
await BindPosition();
if (Framework.Settings.Instance.AlwaysTop)
{
SetTopMost(false);
ShowDesktop.RemoveHook();
}
else
{
ClearTopMost(false);
ShowDesktop.AddHook(this);
}
if (Framework.Settings.Instance.ClickThrough)
{
SetClickThrough();
}
else
{
ClearClickThrough();
}
if (Framework.Settings.Instance.ToolbarMode)
{
HideInAltTab();
}
else
{
ShowInAltTab();
}
if (WindowControls.Visibility != Visibility.Visible)
{
if (Framework.Settings.Instance.CollapseMenuBar)
{
WindowControls.Visibility = Visibility.Collapsed;
}
else
{
WindowControls.Visibility = Visibility.Hidden;
}
}
Hotkey.Initialize(this, Framework.Settings.Instance.Hotkeys);
if (enableHotkeys)
{
Hotkey.Enable();
}
}
private async Task BindPosition()
{
await SetAppBar();
}
private async Task BindModel()
{
await Task.Run(async () =>
{
if (Model != null)
{
Model.Dispose();
Model = null;
}
await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ModelReadyHandler(ModelReady), new SidebarModel());
});
}
private delegate void ModelReadyHandler(SidebarModel model);
private void ModelReady(SidebarModel model)
{
DataContext = Model = model;
model.Start();
Ready = true;
BindGraphs();
if (_openSettings)
{
_openSettings = false;
App.Current.OpenSettings();
}
if (_initiallyHidden)
{
_initiallyHidden = false;
AppBarHide();
}
}
private void BindGraphs()
{
foreach (Graph _graph in App.Current.Graphs)
{
_graph.Model.BindData(Model.MonitorManager);
}
}
private void GraphButton_Click(object sender, RoutedEventArgs e)
{
App.Current.OpenGraph();
}
private void SettingsButton_Click(object sender, RoutedEventArgs e)
{
App.Current.OpenSettings();
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
App.Current.Shutdown();
}
private void Window_MouseEnter(object sender, MouseEventArgs e)
{
WindowControls.Visibility = Visibility.Visible;
}
private void Window_MouseLeave(object sender, MouseEventArgs e)
{
WindowControls.Visibility = Framework.Settings.Instance.CollapseMenuBar ? Visibility.Collapsed : Visibility.Hidden;
}
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
await Initialize();
}
private void Window_StateChanged(object sender, EventArgs e)
{
if (WindowState != WindowState.Normal)
{
WindowState = WindowState.Normal;
}
}
private void Window_Closing(object sender, CancelEventArgs e)
{
Ready = false;
DataContext = null;
if (Model != null)
{
Model.Dispose();
Model = null;
}
ClearAppBar();
Devices.RemoveHook(this);
ShowDesktop.RemoveHook();
Hotkey.Dispose();
}
private void Window_Closed(object sender, EventArgs e)
{
if (App._reloading)
{
App._reloading = false;
new Sidebar(false, false).Show();
}
else
{
App.Current.Shutdown();
}
}
private bool _ready { get; set; } = false;
public bool Ready
{
get
{
return _ready;
}
set
{
_ready = value;
if (Model != null)
{
Model.Ready = value;
}
}
}
public SidebarModel Model { get; private set; }
private bool _openSettings { get; set; } = false;
private bool _initiallyHidden { get; set; } = false;
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Sidebar.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1,194 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using Squirrel;
using Hardcodet.Wpf.TaskbarNotification;
using SidebarDiagnostics.Monitoring;
using SidebarDiagnostics.Utilities;
using SidebarDiagnostics.Windows;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected async override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// ERROR HANDLING
#if !DEBUG
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_Error);
#endif
// LANGUAGE
Culture.SetDefault();
Culture.SetCurrent(true);
// UPDATE
#if !DEBUG
if (Framework.Settings.Instance.AutoUpdate)
{
await AppUpdate(false);
}
#endif
// SETTINGS
CheckSettings();
// VERSION
Version _version = Assembly.GetExecutingAssembly().GetName().Version;
string _vstring = _version.ToString(3);
// TRAY ICON
TrayIcon = (TaskbarIcon)FindResource("TrayIcon");
TrayIcon.ToolTipText = string.Format("{0} v{1}", Framework.Resources.AppName, _vstring);
TrayIcon.TrayContextMenuOpen += TrayIcon_TrayContextMenuOpen;
// START APP
if (Framework.Settings.Instance.InitialSetup)
{
new Setup();
}
else
{
StartApp(false);
}
}
protected override void OnExit(ExitEventArgs e)
{
TrayIcon.Dispose();
base.OnExit(e);
}
public static void StartApp(bool openSettings)
{
Version _version = Assembly.GetExecutingAssembly().GetName().Version;
string _vstring = _version.ToString(3);
if (!string.Equals(Framework.Settings.Instance.ChangeLog, _vstring, StringComparison.OrdinalIgnoreCase))
{
Framework.Settings.Instance.ChangeLog = _vstring;
Framework.Settings.Instance.Save();
new ChangeLog(_version).Show();
}
new Sidebar(openSettings, Framework.Settings.Instance.InitiallyHidden).Show();
RefreshIcon();
}
public static void RefreshIcon()
{
TrayIcon.Visibility = Framework.Settings.Instance.ShowTrayIcon ? Visibility.Visible : Visibility.Collapsed;
}
public static void ShowPerformanceCounterError()
{
MessageBoxResult _result = MessageBox.Show(Framework.Resources.ErrorPerformanceCounter, Framework.Resources.ErrorTitle, MessageBoxButton.OKCancel, MessageBoxImage.Warning, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
if (_result == MessageBoxResult.OK)
{
Process.Start(ConfigurationManager.AppSettings["WikiURL"]);
}
}
public void OpenSettings()
{
Settings _settings = Windows.OfType<Settings>().FirstOrDefault();
if (_settings != null)
{
_settings.WindowState = WindowState.Normal;
_settings.Activate();
return;
}
Sidebar _sidebar = Sidebar;
if (_sidebar == null)
{
return;
}
new Settings(_sidebar);
}
public void OpenGraph()
{
Sidebar _sidebar = Sidebar;
if (_sidebar == null || !_sidebar.Ready)
{
return;
}
new Graph(_sidebar);
}
private async Task AppUpdate(bool showInfo)
{
string _exe = await SquirrelUpdate(showInfo);
if (_exe != null)
{
if (Framework.Settings.Instance.RunAtStartup)
{
Utilities.Startup.EnableStartupTask(_exe);
}
Process.Start(_exe);
Shutdown();
}
}
private async Task<string> SquirrelUpdate(bool showInfo)
{
try
{
using (UpdateManager _manager = new UpdateManager(ConfigurationManager.AppSettings["CurrentReleaseURL"]))
{
UpdateInfo _update = await _manager.CheckForUpdate();
if (_update.ReleasesToApply.Any())
{
Version _newVersion = _update.ReleasesToApply.OrderByDescending(r => r.Version).First().Version.Version;
Update _updateWindow = new Update();
_updateWindow.Show();
await _manager.UpdateApp((p) => _updateWindow.SetProgress(p));
_updateWindow.Close();
return Utilities.Paths.Exe(_newVersion);
}
else if (showInfo)
{
MessageBox.Show(Framework.Resources.UpdateSuccessText, Framework.Resources.AppName, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
}
}
}
catch (WebException)
{
if (showInfo)
{
MessageBox.Show(Framework.Resources.UpdateErrorText, Framework.Resources.UpdateErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
}
}
catch (Exception e)
{
Framework.Settings.Instance.AutoUpdate = false;
Framework.Settings.Instance.Save();
using (EventLog _log = new EventLog("Application"))
{
_log.Source = Framework.Resources.AppName;
_log.WriteEntry(e.ToString(), EventLogEntryType.Error, 100, 1);
}
MessageBox.Show(Framework.Resources.UpdateErrorFatalText, Framework.Resources.UpdateErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
}
return null;
}
private void CheckSettings()
{
if (Framework.Settings.Instance.RunAtStartup && !Utilities.Startup.StartupTaskExists())
{
Utilities.Startup.EnableStartupTask();
}
Framework.Settings.Instance.MonitorConfig = MonitorConfig.CheckConfig(Framework.Settings.Instance.MonitorConfig);
}
private void TrayIcon_TrayContextMenuOpen(object sender, RoutedEventArgs e)
{
Monitor _primary = Monitor.GetMonitors().GetPrimary();
TrayIcon.ContextMenu.HorizontalOffset *= _primary.InverseScaleX;
TrayIcon.ContextMenu.VerticalOffset *= _primary.InverseScaleY;
}
private void Settings_Click(object sender, EventArgs e)
{
OpenSettings();
}
private void Reload_Click(object sender, EventArgs e)
{
Sidebar _sidebar = Sidebar;
if (_sidebar == null)
{
return;
}
_sidebar.Reload();
}
private void Graph_Click(object sender, EventArgs e)
{
OpenGraph();
}
private void Visibility_SubmenuOpened(object sender, EventArgs e)
{
Sidebar _sidebar = Sidebar;
if (_sidebar == null)
{
return;
}
MenuItem _this = (MenuItem)sender;
(_this.Items.GetItemAt(0) as MenuItem).IsChecked = _sidebar.Visibility == Visibility.Visible;
(_this.Items.GetItemAt(1) as MenuItem).IsChecked = _sidebar.Visibility == Visibility.Hidden;
}
private void Show_Click(object sender, EventArgs e)
{
Sidebar _sidebar = Sidebar;
if (_sidebar == null || _sidebar.Visibility == Visibility.Visible)
{
return;
}
_sidebar.AppBarShow();
}
private void Hide_Click(object sender, EventArgs e)
{
Sidebar _sidebar = Sidebar;
if (_sidebar == null || _sidebar.Visibility == Visibility.Hidden)
{
return;
}
_sidebar.AppBarHide();
}
private void Donate_Click(object sender, RoutedEventArgs e)
{
Process.Start(ConfigurationManager.AppSettings["DonateURL"]);
}
private void GitHub_Click(object sender, RoutedEventArgs e)
{
Process.Start(ConfigurationManager.AppSettings["RepoURL"]);
}
private async void Update_Click(object sender, RoutedEventArgs e)
{
await AppUpdate(true);
}
private void Close_Click(object sender, EventArgs e)
{
Shutdown();
}
private static void AppDomain_Error(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show(ex.ToString(), Framework.Resources.ErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
}
public Sidebar Sidebar
{
get
{
return Windows.OfType<Sidebar>().FirstOrDefault();
}
}
public IEnumerable<Graph> Graphs
{
get
{
return Windows.OfType<Graph>();
}
}
public new static App Current
{
get
{
return (App)Application.Current;
}
}
public static TaskbarIcon TrayIcon { get; set; }
internal static bool _reloading { get; set; } = false;
}
}
``` | /content/code_sandbox/SidebarDiagnostics/App.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1,780 |
```smalltalk
using System;
using System.ComponentModel;
using System.Windows.Threading;
using SidebarDiagnostics.Monitoring;
using SidebarDiagnostics.Utilities;
namespace SidebarDiagnostics.Models
{
public class SidebarModel : INotifyPropertyChanged, IDisposable
{
public SidebarModel()
{
InitMachineName();
InitClock();
InitMonitors();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
DisposeClock();
DisposeMonitors();
}
_disposed = true;
}
}
~SidebarModel()
{
Dispose(false);
}
public void Start()
{
StartClock();
StartMonitors();
}
public void Reload()
{
DisposeMonitors();
InitMonitors();
StartMonitors();
}
public void Pause()
{
PauseClock();
PauseMonitors();
}
public void Resume()
{
ResumeClock();
ResumeMonitors();
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void InitMachineName()
{
ShowMachineName = Framework.Settings.Instance.ShowMachineName;
MachineName = Environment.MachineName;
}
private void InitClock()
{
ShowClock = Framework.Settings.Instance.ShowClock;
if (!ShowClock)
{
return;
}
ShowDate = !Framework.Settings.Instance.DateSetting.Equals(Framework.DateSetting.Disabled);
UpdateClock();
}
private void InitMonitors()
{
MonitorManager = new MonitorManager(Framework.Settings.Instance.MonitorConfig);
MonitorManager.Update();
}
private void StartClock()
{
if (!ShowClock)
{
return;
}
_clockTimer = new DispatcherTimer();
_clockTimer.Interval = TimeSpan.FromSeconds(1);
_clockTimer.Tick += new EventHandler(ClockTimer_Tick);
_clockTimer.Start();
}
private void StartMonitors()
{
_monitorTimer = new DispatcherTimer();
_monitorTimer.Interval = TimeSpan.FromMilliseconds(Framework.Settings.Instance.PollingInterval);
_monitorTimer.Tick += new EventHandler(MonitorTimer_Tick);
_monitorTimer.Start();
}
private void UpdateClock()
{
DateTime _now = DateTime.Now;
Time = _now.ToString(Framework.Settings.Instance.Clock24HR ? "H:mm:ss" : "h:mm:ss tt", Culture.CultureInfo);
if (ShowDate)
{
Date = _now.ToString(Framework.Settings.Instance.DateSetting.Format, Culture.CultureInfo);
}
}
private void UpdateMonitors()
{
MonitorManager.Update();
}
private void PauseClock()
{
if (_clockTimer != null)
{
_clockTimer.Stop();
}
}
private void PauseMonitors()
{
if (_monitorTimer != null)
{
_monitorTimer.Stop();
}
}
private void ResumeClock()
{
if (_clockTimer != null)
{
_clockTimer.Start();
}
}
private void ResumeMonitors()
{
if (_monitorTimer != null)
{
_monitorTimer.Start();
}
}
private void DisposeClock()
{
if (_clockTimer != null)
{
_clockTimer.Stop();
_clockTimer = null;
}
}
private void DisposeMonitors()
{
if (_monitorTimer != null)
{
_monitorTimer.Stop();
_monitorTimer = null;
}
if (MonitorManager != null)
{
MonitorManager.Dispose();
_monitorManager = null;
}
}
private void ClockTimer_Tick(object sender, EventArgs e)
{
UpdateClock();
}
private void MonitorTimer_Tick(object sender, EventArgs e)
{
UpdateMonitors();
}
private bool _ready { get; set; } = false;
public bool Ready
{
get
{
return _ready;
}
set
{
_ready = value;
NotifyPropertyChanged("Ready");
}
}
private bool _showMachineName { get; set; }
public bool ShowMachineName
{
get
{
return _showMachineName;
}
set
{
_showMachineName = value;
NotifyPropertyChanged("ShowMachineName");
}
}
private string _machineName { get; set; }
public string MachineName
{
get
{
return _machineName;
}
set
{
_machineName = value;
NotifyPropertyChanged("MachineName");
}
}
private bool _showClock { get; set; }
public bool ShowClock
{
get
{
return _showClock;
}
set
{
_showClock = value;
NotifyPropertyChanged("ShowClock");
}
}
private string _time { get; set; }
public string Time
{
get
{
return _time;
}
set
{
_time = value;
NotifyPropertyChanged("Time");
}
}
private bool _showDate { get; set; }
public bool ShowDate
{
get
{
return _showDate;
}
set
{
_showDate = value;
NotifyPropertyChanged("ShowDate");
}
}
private string _date { get; set; }
public string Date
{
get
{
return _date;
}
set
{
_date = value;
NotifyPropertyChanged("Date");
}
}
private MonitorManager _monitorManager { get; set; }
public MonitorManager MonitorManager
{
get
{
return _monitorManager;
}
set
{
_monitorManager = value;
NotifyPropertyChanged("MonitorManager");
}
}
private DispatcherTimer _clockTimer { get; set; }
private DispatcherTimer _monitorTimer { get; set; }
private bool _disposed { get; set; } = false;
}
}
``` | /content/code_sandbox/SidebarDiagnostics/SidebarModel.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1,330 |
```smalltalk
using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using SidebarDiagnostics.Windows;
using SidebarDiagnostics.Style;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for Setup.xaml
/// </summary>
public partial class Setup : FlatWindow
{
public Setup()
{
InitializeComponent();
Framework.Settings.Instance.ScreenIndex = 0;
Framework.Settings.Instance.DockEdge = DockEdge.Right;
Framework.Settings.Instance.XOffset = 0;
Framework.Settings.Instance.YOffset = 0;
Sidebar = new Dummy(this);
Sidebar.Show();
}
private void ShowPage(Page page)
{
foreach (DockPanel _panel in SetupGrid.Children)
{
_panel.IsEnabled = _panel.Name == page.ToString();
}
CurrentPage = page;
}
private void Yes_Click(object sender, RoutedEventArgs e)
{
switch (CurrentPage)
{
case Page.Initial:
case Page.BeginCustom:
ShowPage(Page.Final);
return;
}
}
private void No_Click(object sender, RoutedEventArgs e)
{
switch (CurrentPage)
{
case Page.Initial:
ShowPage(Page.BeginCustom);
return;
}
}
private void OffsetSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (_cancelReposition != null)
{
_cancelReposition.Cancel();
}
_cancelReposition = new CancellationTokenSource();
Task.Delay(TimeSpan.FromMilliseconds(500), _cancelReposition.Token).ContinueWith(_ =>
{
if (_.IsCanceled)
{
return;
}
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
{
Framework.Settings.Instance.XOffset = (int)XOffsetSlider.Value;
Framework.Settings.Instance.YOffset = (int)YOffsetSlider.Value;
Sidebar.Reposition();
}));
_cancelReposition = null;
});
}
private void NumberBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (new Regex("[^0-9.-]+").IsMatch(e.Text))
{
e.Handled = true;
}
}
private void Settings_Click(object sender, RoutedEventArgs e)
{
_openSettings = true;
Close();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void Window_Closed(object sender, EventArgs e)
{
if (Sidebar != null && Sidebar.IsInitialized)
{
Sidebar.Close();
}
Framework.Settings.Instance.InitialSetup = false;
Framework.Settings.Instance.Save();
App.StartApp(_openSettings);
}
public Dummy Sidebar { get; private set; }
public Page CurrentPage { get; set; } = Page.Initial;
private CancellationTokenSource _cancelReposition { get; set; }
private bool _openSettings { get; set; } = false;
public enum Page : byte
{
Initial,
BeginCustom,
Final
}
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Setup.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 659 |
```smalltalk
using System.Windows.Input;
using SidebarDiagnostics.Models;
using SidebarDiagnostics.Windows;
using System.ComponentModel;
using SidebarDiagnostics.Style;
namespace SidebarDiagnostics
{
/// <summary>
/// Interaction logic for Graph.xaml
/// </summary>
public partial class Graph : FlatWindow
{
public Graph(Sidebar sidebar)
{
InitializeComponent();
DataContext = Model = new GraphModel(OPGraph);
Model.BindData(sidebar.Model.MonitorManager);
Show();
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
OPGraph.ResetAllAxes();
}
}
private void Window_Closing(object sender, CancelEventArgs e)
{
DataContext = null;
if (Model != null)
{
Model.Dispose();
Model = null;
}
}
public GraphModel Model { get; private set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Graph.xaml.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 198 |
```smalltalk
using System;
using System.IO;
using System.ComponentModel;
using Newtonsoft.Json;
using SidebarDiagnostics.Utilities;
using SidebarDiagnostics.Monitoring;
using SidebarDiagnostics.Windows;
using System.Globalization;
namespace SidebarDiagnostics.Framework
{
[JsonObject(MemberSerialization.OptIn)]
public sealed class Settings : INotifyPropertyChanged
{
private Settings() { }
public void Save()
{
if (!Directory.Exists(Paths.LocalApp))
{
Directory.CreateDirectory(Paths.LocalApp);
}
using (StreamWriter _writer = File.CreateText(Paths.SettingsFile))
{
new JsonSerializer() { Formatting = Formatting.Indented }.Serialize(_writer, this);
}
}
public void Reload()
{
_instance = Load();
}
private static Settings Load()
{
Settings _return = null;
if (File.Exists(Paths.SettingsFile))
{
using (StreamReader _reader = File.OpenText(Paths.SettingsFile))
{
_return = (Settings)new JsonSerializer().Deserialize(_reader, typeof(Settings));
}
}
return _return ?? new Settings();
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private string _changeLog { get; set; } = null;
[JsonProperty]
public string ChangeLog
{
get
{
return _changeLog;
}
set
{
_changeLog = value;
NotifyPropertyChanged("ChangeLog");
}
}
private bool _initialSetup { get; set; } = true;
[JsonProperty]
public bool InitialSetup
{
get
{
return _initialSetup;
}
set
{
_initialSetup = value;
NotifyPropertyChanged("InitialSetup");
}
}
private DockEdge _dockEdge { get; set; } = DockEdge.Right;
[JsonProperty]
public DockEdge DockEdge
{
get
{
return _dockEdge;
}
set
{
_dockEdge = value;
NotifyPropertyChanged("DockEdge");
}
}
private int _screenIndex { get; set; } = 0;
[JsonProperty]
public int ScreenIndex
{
get
{
return _screenIndex;
}
set
{
_screenIndex = value;
NotifyPropertyChanged("ScreenIndex");
}
}
private string _culture { get; set; } = Utilities.Culture.DEFAULT;
[JsonProperty]
public string Culture
{
get
{
return _culture;
}
set
{
_culture = value;
NotifyPropertyChanged("Culture");
}
}
private bool _useAppBar { get; set; } = true;
[JsonProperty]
public bool UseAppBar
{
get
{
return _useAppBar;
}
set
{
_useAppBar = value;
NotifyPropertyChanged("UseAppBar");
}
}
private bool _alwaysTop { get; set; } = true;
[JsonProperty]
public bool AlwaysTop
{
get
{
return _alwaysTop;
}
set
{
_alwaysTop = value;
NotifyPropertyChanged("AlwaysTop");
}
}
private bool _autoUpdate { get; set; } = true;
[JsonProperty]
public bool AutoUpdate
{
get
{
return _autoUpdate;
}
set
{
_autoUpdate = value;
NotifyPropertyChanged("AutoUpdate");
}
}
private bool _runAtStartup { get; set; } = true;
[JsonProperty]
public bool RunAtStartup
{
get
{
return _runAtStartup;
}
set
{
_runAtStartup = value;
NotifyPropertyChanged("RunAtStartup");
}
}
private double _uiScale { get; set; } = 1d;
[JsonProperty]
public double UIScale
{
get
{
return _uiScale;
}
set
{
_uiScale = value;
NotifyPropertyChanged("UIScale");
}
}
private int _xOffset { get; set; } = 0;
[JsonProperty]
public int XOffset
{
get
{
return _xOffset;
}
set
{
_xOffset = value;
NotifyPropertyChanged("XOffset");
}
}
private int _yOffset { get; set; } = 0;
[JsonProperty]
public int YOffset
{
get
{
return _yOffset;
}
set
{
_yOffset = value;
NotifyPropertyChanged("YOffset");
}
}
private int _pollingInterval { get; set; } = 1000;
[JsonProperty]
public int PollingInterval
{
get
{
return _pollingInterval;
}
set
{
_pollingInterval = value;
NotifyPropertyChanged("PollingInterval");
}
}
private bool _toolbarMode { get; set; } = true;
[JsonProperty]
public bool ToolbarMode
{
get
{
return _toolbarMode;
}
set
{
_toolbarMode = value;
NotifyPropertyChanged("ToolbarMode");
}
}
private bool _clickThrough { get; set; } = false;
[JsonProperty]
public bool ClickThrough
{
get
{
return _clickThrough;
}
set
{
_clickThrough = value;
NotifyPropertyChanged("ClickThrough");
}
}
private bool _showTrayIcon { get; set; } = true;
[JsonProperty]
public bool ShowTrayIcon
{
get
{
return _showTrayIcon;
}
set
{
_showTrayIcon = value;
NotifyPropertyChanged("ShowTrayIcon");
}
}
private bool _collapseMenuBar { get; set; } = false;
[JsonProperty]
public bool CollapseMenuBar
{
get
{
return _collapseMenuBar;
}
set
{
_collapseMenuBar = value;
NotifyPropertyChanged("CollapseMenuBar");
}
}
private bool _initiallyHidden { get; set; } = false;
[JsonProperty]
public bool InitiallyHidden
{
get
{
return _initiallyHidden;
}
set
{
_initiallyHidden = value;
NotifyPropertyChanged("InitiallyHidden");
}
}
private int _sidebarWidth { get; set; } = 180;
[JsonProperty]
public int SidebarWidth
{
get
{
return _sidebarWidth;
}
set
{
_sidebarWidth = value;
NotifyPropertyChanged("SidebarWidth");
}
}
private bool _autoBGColor { get; set; } = false;
[JsonProperty]
public bool AutoBGColor
{
get
{
return _autoBGColor;
}
set
{
_autoBGColor = value;
NotifyPropertyChanged("AutoBGColor");
}
}
private string _bgColor { get; set; } = "#000000";
[JsonProperty]
public string BGColor
{
get
{
return _bgColor;
}
set
{
_bgColor = value;
NotifyPropertyChanged("BGColor");
}
}
private double _bgOpacity { get; set; } = 0.85d;
[JsonProperty]
public double BGOpacity
{
get
{
return _bgOpacity;
}
set
{
_bgOpacity = value;
NotifyPropertyChanged("BGOpacity");
}
}
private TextAlign _textAlign { get; set; } = TextAlign.Left;
[JsonProperty]
public TextAlign TextAlign
{
get
{
return _textAlign;
}
set
{
_textAlign = value;
NotifyPropertyChanged("TextAlign");
}
}
private FontSetting _fontSetting { get; set; } = FontSetting.x14;
[JsonProperty]
public FontSetting FontSetting
{
get
{
return _fontSetting;
}
set
{
_fontSetting = value;
NotifyPropertyChanged("FontSetting");
}
}
private string _fontColor { get; set; } = "#FFFFFF";
[JsonProperty]
public string FontColor
{
get
{
return _fontColor;
}
set
{
_fontColor = value;
NotifyPropertyChanged("FontColor");
}
}
private string _alertFontColor { get; set; } = "#FF4136";
[JsonProperty]
public string AlertFontColor
{
get
{
return _alertFontColor;
}
set
{
_alertFontColor = value;
NotifyPropertyChanged("AlertFontColor");
}
}
private bool _alertBlink { get; set; } = true;
[JsonProperty]
public bool AlertBlink
{
get
{
return _alertBlink;
}
set
{
_alertBlink = value;
NotifyPropertyChanged("AlertBlink");
}
}
private bool _showMachineName { get; set; } = false;
[JsonProperty]
public bool ShowMachineName
{
get
{
return _showMachineName;
}
set
{
_showMachineName = value;
NotifyPropertyChanged("ShowMachineName");
}
}
private bool _showClock { get; set; } = true;
[JsonProperty]
public bool ShowClock
{
get
{
return _showClock;
}
set
{
_showClock = value;
NotifyPropertyChanged("ShowClock");
}
}
private bool _clock24HR { get; set; } = false;
[JsonProperty]
public bool Clock24HR
{
get
{
return _clock24HR;
}
set
{
_clock24HR = value;
NotifyPropertyChanged("Clock24HR");
}
}
private DateSetting _dateSetting { get; set; } = DateSetting.Short;
[JsonProperty]
public DateSetting DateSetting
{
get
{
return _dateSetting;
}
set
{
_dateSetting = value;
NotifyPropertyChanged("DateSetting");
}
}
private MonitorConfig[] _monitorConfig { get; set; } = null;
[JsonProperty]
public MonitorConfig[] MonitorConfig
{
get
{
return _monitorConfig;
}
set
{
_monitorConfig = value;
NotifyPropertyChanged("MonitorConfig");
}
}
private Hotkey[] _hotkeys { get; set; } = new Hotkey[0];
[JsonProperty]
public Hotkey[] Hotkeys
{
get
{
return _hotkeys;
}
set
{
_hotkeys = value;
NotifyPropertyChanged("Hotkeys");
}
}
private static Settings _instance { get; set; } = null;
public static Settings Instance
{
get
{
if (_instance == null)
{
_instance = Load();
}
return _instance;
}
}
}
public enum TextAlign : byte
{
Left,
Right
}
[JsonObject(MemberSerialization.OptIn)]
public sealed class FontSetting
{
internal FontSetting() { }
private FontSetting(int fontSize)
{
FontSize = fontSize;
}
public override bool Equals(object obj)
{
FontSetting _that = obj as FontSetting;
if (_that == null)
{
return false;
}
return this.FontSize == _that.FontSize;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static FontSetting x10
{
get
{
return new FontSetting(10);
}
}
public static FontSetting x12
{
get
{
return new FontSetting(12);
}
}
public static FontSetting x14
{
get
{
return new FontSetting(14);
}
}
public static FontSetting x16
{
get
{
return new FontSetting(16);
}
}
public static FontSetting x18
{
get
{
return new FontSetting(18);
}
}
[JsonProperty]
public int FontSize { get; set; }
public int TitleFontSize
{
get
{
return FontSize + 2;
}
}
public int SmallFontSize
{
get
{
return FontSize - 2;
}
}
public int IconSize
{
get
{
switch (FontSize)
{
case 10:
return 18;
case 12:
return 22;
case 14:
default:
return 24;
case 16:
return 28;
case 18:
return 32;
}
}
}
public int BarHeight
{
get
{
return FontSize - 3;
}
}
public int BarWidth
{
get
{
return BarHeight * 6;
}
}
public int BarWidthWide
{
get
{
return BarHeight * 8;
}
}
}
[JsonObject(MemberSerialization.OptIn)]
public sealed class DateSetting
{
internal DateSetting() { }
private DateSetting(string format)
{
Format = format;
}
[JsonProperty]
public string Format { get; set; }
public string Display
{
get
{
if (string.Equals(Format, "Disabled", StringComparison.Ordinal))
{
return Resources.SettingsDateFormatDisabled;
}
return DateTime.Today.ToString(Format, Culture.CultureInfo);
}
}
public override bool Equals(object obj)
{
DateSetting _that = obj as DateSetting;
if (_that == null)
{
return false;
}
return string.Equals(this.Format, _that.Format, StringComparison.Ordinal);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static readonly DateSetting Disabled = new DateSetting("Disabled");
public static readonly DateSetting Short = new DateSetting("M");
public static readonly DateSetting Normal = new DateSetting("d");
public static readonly DateSetting Long = new DateSetting("D");
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Settings.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 3,206 |
```smalltalk
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using System.Windows.Media;
using SidebarDiagnostics.Style;
using Newtonsoft.Json;
namespace SidebarDiagnostics.Windows
{
public enum WinOS : byte
{
Unknown,
Other,
Win7,
Win8,
Win8_1,
Win10
}
public static class OS
{
private static WinOS _os { get; set; } = WinOS.Unknown;
public static WinOS Get
{
get
{
if (_os != WinOS.Unknown)
{
return _os;
}
Version _version = Environment.OSVersion.Version;
if (_version.Major >= 10)
{
_os = WinOS.Win10;
}
else if (_version.Major == 6 && _version.Minor == 3)
{
_os = WinOS.Win8_1;
}
else if (_version.Major == 6 && _version.Minor == 2)
{
_os = WinOS.Win8;
}
else if (_version.Major == 6 && _version.Minor == 1)
{
_os = WinOS.Win7;
}
else
{
_os = WinOS.Other;
}
return _os;
}
}
public static bool SupportDPI
{
get
{
return OS.Get >= WinOS.Win8_1;
}
}
public static bool SupportVirtualDesktop
{
get
{
return OS.Get >= WinOS.Win10;
}
}
}
internal static class NativeMethods
{
[DllImport("user32.dll")]
internal static extern long GetWindowLong(IntPtr hwnd, int index);
[DllImport("user32.dll")]
internal static extern long GetWindowLongPtr(IntPtr hwnd, int index);
[DllImport("user32.dll")]
internal static extern long SetWindowLong(IntPtr hwnd, int index, long newStyle);
[DllImport("user32.dll")]
internal static extern long SetWindowLongPtr(IntPtr hwnd, int index, long newStyle);
[DllImport("user32.dll")]
internal static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwnd_after, int x, int y, int cx, int cy, uint uflags);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern int RegisterWindowMessage(string msg);
[DllImport("shell32.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern UIntPtr SHAppBarMessage(int dwMessage, ref AppBarWindow.APPBARDATA pData);
[DllImport("user32.dll")]
internal static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, Monitor.EnumCallback callback, int dwData);
[DllImport("user32.dll")]
internal static extern bool GetMonitorInfo(IntPtr hMonitor, ref Monitor.MONITORINFO lpmi);
[DllImport("shcore.dll")]
internal static extern IntPtr GetDpiForMonitor(IntPtr hmonitor, Monitor.MONITOR_DPI_TYPE dpiType, out uint dpiX, out uint dpiY);
[DllImport("user32.dll")]
internal static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);
[DllImport("user32.dll")]
internal static extern bool RegisterHotKey(IntPtr hwnd, int id, uint modifiers, uint vk);
[DllImport("user32.dll")]
internal static extern bool UnregisterHotKey(IntPtr hwnd, int id);
[DllImport("user32.dll")]
internal static extern IntPtr RegisterDeviceNotification(IntPtr recipient, IntPtr notificationFilter, int flags);
[DllImport("user32.dll")]
internal static extern bool UnregisterDeviceNotification(IntPtr handle);
[DllImport("user32.dll")]
internal static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, ShowDesktop.WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
[DllImport("user32.dll")]
internal static extern bool UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetClassName(IntPtr hwnd, StringBuilder name, int count);
[DllImport("dwmapi.dll")]
internal static extern int DwmSetWindowAttribute(IntPtr hwnd, AppBarWindow.DWMWINDOWATTRIBUTE dwmAttribute, IntPtr pvAttribute, uint cbAttribute);
}
public static class ShowDesktop
{
private const uint WINEVENT_OUTOFCONTEXT = 0u;
private const uint EVENT_SYSTEM_FOREGROUND = 3u;
private const string WORKERW = "WorkerW";
private const string PROGMAN = "Progman";
public static void AddHook(Sidebar sidebar)
{
if (IsHooked)
{
return;
}
IsHooked = true;
_delegate = new WinEventDelegate(WinEventHook);
_hookIntPtr = NativeMethods.SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _delegate, 0, 0, WINEVENT_OUTOFCONTEXT);
_sidebar = sidebar;
_sidebarHwnd = new WindowInteropHelper(sidebar).Handle;
}
public static void RemoveHook()
{
if (!IsHooked)
{
return;
}
IsHooked = false;
NativeMethods.UnhookWinEvent(_hookIntPtr.Value);
_delegate = null;
_hookIntPtr = null;
_sidebar = null;
_sidebarHwnd = null;
}
private static string GetWindowClass(IntPtr hwnd)
{
StringBuilder _sb = new StringBuilder(32);
NativeMethods.GetClassName(hwnd, _sb, _sb.Capacity);
return _sb.ToString();
}
internal delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
private static void WinEventHook(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
if (eventType == EVENT_SYSTEM_FOREGROUND)
{
string _class = GetWindowClass(hwnd);
if (string.Equals(_class, WORKERW, StringComparison.Ordinal) /*|| string.Equals(_class, PROGMAN, StringComparison.Ordinal)*/ )
{
_sidebar.SetTopMost(false);
}
else if (_sidebar.IsTopMost)
{
_sidebar.SetBottom(false);
}
}
}
public static bool IsHooked { get; private set; } = false;
private static IntPtr? _hookIntPtr { get; set; }
private static WinEventDelegate _delegate { get; set; }
private static Sidebar _sidebar { get; set; }
private static IntPtr? _sidebarHwnd { get; set; }
}
public static class Devices
{
private const int WM_DEVICECHANGE = 0x0219;
private static class DBCH_DEVICETYPE
{
public const int DBT_DEVTYP_DEVICEINTERFACE = 5;
public const int DBT_DEVTYP_HANDLE = 6;
public const int DBT_DEVTYP_OEM = 0;
public const int DBT_DEVTYP_PORT = 3;
public const int DBT_DEVTYP_VOLUME = 2;
}
private static class FLAGS
{
public const int DEVICE_NOTIFY_WINDOW_HANDLE = 0;
public const int DEVICE_NOTIFY_SERVICE_HANDLE = 1;
public const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 4;
}
private static class WM_DEVICECHANGE_EVENT
{
public const int DBT_CONFIGCHANGECANCELED = 0x0019;
public const int DBT_CONFIGCHANGED = 0x0018;
public const int DBT_CUSTOMEVENT = 0x8006;
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICEQUERYREMOVE = 0x8001;
public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int DBT_DEVICEREMOVEPENDING = 0x8003;
public const int DBT_DEVICETYPESPECIFIC = 0x8005;
public const int DBT_DEVNODES_CHANGED = 0x0007;
public const int DBT_QUERYCHANGECONFIG = 0x0017;
public const int DBT_USERDEFINED = 0xFFFF;
}
[StructLayout(LayoutKind.Sequential)]
private struct DEV_BROADCAST_HDR
{
public int dbch_size;
public int dbch_devicetype;
public int dbch_reserved;
}
public static void AddHook(Sidebar window)
{
if (IsHooked)
{
return;
}
IsHooked = true;
DEV_BROADCAST_HDR _data = new DEV_BROADCAST_HDR();
_data.dbch_size = Marshal.SizeOf(_data);
_data.dbch_devicetype = DBCH_DEVICETYPE.DBT_DEVTYP_DEVICEINTERFACE;
IntPtr _buffer = Marshal.AllocHGlobal(_data.dbch_size);
Marshal.StructureToPtr(_data, _buffer, true);
IntPtr _hwnd = new WindowInteropHelper(window).Handle;
NativeMethods.RegisterDeviceNotification(
_hwnd,
_buffer,
FLAGS.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES
);
window.HwndSource.AddHook(DeviceHook);
}
public static void RemoveHook(Sidebar window)
{
if (!IsHooked)
{
return;
}
IsHooked = false;
window.HwndSource.RemoveHook(DeviceHook);
}
private static IntPtr DeviceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_DEVICECHANGE)
{
switch (wParam.ToInt32())
{
case WM_DEVICECHANGE_EVENT.DBT_DEVICEARRIVAL:
case WM_DEVICECHANGE_EVENT.DBT_DEVICEREMOVECOMPLETE:
if (_cancelRestart != null)
{
_cancelRestart.Cancel();
}
_cancelRestart = new CancellationTokenSource();
Task.Delay(TimeSpan.FromSeconds(1), _cancelRestart.Token).ContinueWith(_ =>
{
if (_.IsCanceled)
{
return;
}
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() =>
{
Sidebar _sidebar = App.Current.Sidebar;
if (_sidebar != null)
{
_sidebar.ContentReload();
}
}));
_cancelRestart = null;
});
break;
}
handled = true;
}
return IntPtr.Zero;
}
public static bool IsHooked { get; private set; } = false;
private static CancellationTokenSource _cancelRestart { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class Hotkey
{
private const int WM_HOTKEY = 0x0312;
private static class MODIFIERS
{
public const uint MOD_NOREPEAT = 0x4000;
public const uint MOD_ALT = 0x0001;
public const uint MOD_CONTROL = 0x0002;
public const uint MOD_SHIFT = 0x0004;
public const uint MOD_WIN = 0x0008;
}
public enum KeyAction : byte
{
Toggle,
Show,
Hide,
Reload,
Close,
CycleEdge,
CycleScreen,
ReserveSpace
}
public Hotkey() { }
public Hotkey(int index, KeyAction action, uint virtualKey, bool altMod = false, bool ctrlMod = false, bool shiftMod = false, bool winMod = false)
{
Index = index;
Action = action;
VirtualKey = virtualKey;
AltMod = altMod;
CtrlMod = ctrlMod;
ShiftMod = shiftMod;
WinMod = winMod;
}
[JsonProperty]
public KeyAction Action { get; set; }
[JsonProperty]
public uint VirtualKey { get; set; }
[JsonProperty]
public bool AltMod { get; set; }
[JsonProperty]
public bool CtrlMod { get; set; }
[JsonProperty]
public bool ShiftMod { get; set; }
[JsonProperty]
public bool WinMod { get; set; }
public Key WinKey
{
get
{
return KeyInterop.KeyFromVirtualKey((int)VirtualKey);
}
set
{
VirtualKey = (uint)KeyInterop.VirtualKeyFromKey(value);
}
}
private int Index { get; set; }
public static void Initialize(Sidebar window, Hotkey[] settings)
{
if (settings == null || settings.Length == 0)
{
Dispose();
return;
}
Disable();
_sidebar = window;
_index = 0;
RegisteredKeys = settings.Select(h =>
{
h.Index = _index;
_index++;
return h;
}).ToArray();
window.HwndSource.AddHook(KeyHook);
IsHooked = true;
}
public static void Dispose()
{
if (!IsHooked)
{
return;
}
IsHooked = false;
Disable();
RegisteredKeys = null;
_sidebar.HwndSource.RemoveHook(KeyHook);
_sidebar = null;
}
public static void Enable()
{
if (RegisteredKeys == null)
{
return;
}
foreach (Hotkey _hotkey in RegisteredKeys)
{
Register(_hotkey);
}
}
public static void Disable()
{
if (RegisteredKeys == null)
{
return;
}
foreach (Hotkey _hotkey in RegisteredKeys)
{
Unregister(_hotkey);
}
}
private static void Register(Hotkey hotkey)
{
uint _mods = MODIFIERS.MOD_NOREPEAT;
if (hotkey.AltMod)
{
_mods |= MODIFIERS.MOD_ALT;
}
if (hotkey.CtrlMod)
{
_mods |= MODIFIERS.MOD_CONTROL;
}
if (hotkey.ShiftMod)
{
_mods |= MODIFIERS.MOD_SHIFT;
}
if (hotkey.WinMod)
{
_mods |= MODIFIERS.MOD_WIN;
}
NativeMethods.RegisterHotKey(
new WindowInteropHelper(_sidebar).Handle,
hotkey.Index,
_mods,
hotkey.VirtualKey
);
}
private static void Unregister(Hotkey hotkey)
{
NativeMethods.UnregisterHotKey(
new WindowInteropHelper(_sidebar).Handle,
hotkey.Index
);
}
public static Hotkey[] RegisteredKeys { get; private set; }
private static IntPtr KeyHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_HOTKEY)
{
int _id = wParam.ToInt32();
Hotkey _hotkey = RegisteredKeys.FirstOrDefault(k => k.Index == _id);
if (_hotkey != null && _sidebar != null && _sidebar.Ready)
{
switch (_hotkey.Action)
{
case KeyAction.Toggle:
if (_sidebar.Visibility == Visibility.Visible)
{
_sidebar.AppBarHide();
}
else
{
_sidebar.AppBarShow();
}
break;
case KeyAction.Show:
_sidebar.AppBarShow();
break;
case KeyAction.Hide:
_sidebar.AppBarHide();
break;
case KeyAction.Reload:
_sidebar.Reload();
break;
case KeyAction.Close:
App.Current.Shutdown();
break;
case KeyAction.CycleEdge:
if (_sidebar.Visibility == Visibility.Visible)
{
switch (Framework.Settings.Instance.DockEdge)
{
case DockEdge.Right:
Framework.Settings.Instance.DockEdge = DockEdge.Left;
break;
default:
case DockEdge.Left:
Framework.Settings.Instance.DockEdge = DockEdge.Right;
break;
}
Framework.Settings.Instance.Save();
_sidebar.Reposition();
}
break;
case KeyAction.CycleScreen:
if (_sidebar.Visibility == Visibility.Visible)
{
Monitor[] _monitors = Monitor.GetMonitors();
if (Framework.Settings.Instance.ScreenIndex < (_monitors.Length - 1))
{
Framework.Settings.Instance.ScreenIndex++;
}
else
{
Framework.Settings.Instance.ScreenIndex = 0;
}
Framework.Settings.Instance.Save();
_sidebar.Reposition();
}
break;
case KeyAction.ReserveSpace:
Framework.Settings.Instance.UseAppBar = !Framework.Settings.Instance.UseAppBar;
Framework.Settings.Instance.Save();
_sidebar.Reposition();
break;
}
handled = true;
}
}
return IntPtr.Zero;
}
public static bool IsHooked { get; private set; } = false;
private static Sidebar _sidebar { get; set; }
private static int _index { get; set; }
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public int Width
{
get
{
return Right - Left;
}
}
public int Height
{
get
{
return Bottom - Top;
}
}
}
public class WorkArea
{
public double Left { get; set; }
public double Top { get; set; }
public double Right { get; set; }
public double Bottom { get; set; }
public double Width
{
get
{
return Right - Left;
}
}
public double Height
{
get
{
return Bottom - Top;
}
}
public void Scale(double x, double y)
{
Left *= x;
Top *= y;
Right *= x;
Bottom *= y;
}
public void Offset(double x, double y)
{
Left += x;
Top += y;
Right += x;
Bottom += y;
}
public void SetWidth(DockEdge edge, double width)
{
switch (edge)
{
case DockEdge.Left:
Right = Left + width;
break;
case DockEdge.Right:
Left = Right - width;
break;
}
}
public static WorkArea FromRECT(RECT rect)
{
return new WorkArea()
{
Left = rect.Left,
Top = rect.Top,
Right = rect.Right,
Bottom = rect.Bottom
};
}
}
public class Monitor
{
private const uint DPICONST = 96u;
[StructLayout(LayoutKind.Sequential)]
internal struct MONITORINFO
{
public int cbSize;
public RECT Size;
public RECT WorkArea;
public bool IsPrimary;
}
internal enum MONITOR_DPI_TYPE : int
{
MDT_EFFECTIVE_DPI = 0,
MDT_ANGULAR_DPI = 1,
MDT_RAW_DPI = 2,
MDT_DEFAULT = MDT_EFFECTIVE_DPI
}
public RECT Size { get; set; }
public RECT WorkArea { get; set; }
public double DPIx { get; set; }
public double ScaleX
{
get
{
return DPIx / DPICONST;
}
}
public double InverseScaleX
{
get
{
return 1 / ScaleX;
}
}
public double DPIy { get; set; }
public double ScaleY
{
get
{
return DPIy / DPICONST;
}
}
public double InverseScaleY
{
get
{
return 1 / ScaleY;
}
}
public bool IsPrimary { get; set; }
internal delegate bool EnumCallback(IntPtr hDesktop, IntPtr hdc, ref RECT pRect, int dwData);
public static Monitor GetMonitor(IntPtr hMonitor)
{
MONITORINFO _info = new MONITORINFO();
_info.cbSize = Marshal.SizeOf(_info);
NativeMethods.GetMonitorInfo(hMonitor, ref _info);
uint _dpiX = Monitor.DPICONST;
uint _dpiY = Monitor.DPICONST;
if (OS.SupportDPI)
{
NativeMethods.GetDpiForMonitor(hMonitor, MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out _dpiX, out _dpiY);
}
return new Monitor()
{
Size = _info.Size,
WorkArea = _info.WorkArea,
DPIx = _dpiX,
DPIy = _dpiY,
IsPrimary = _info.IsPrimary
};
}
public static Monitor[] GetMonitors()
{
List<Monitor> _monitors = new List<Monitor>();
EnumCallback _callback = (IntPtr hMonitor, IntPtr hdc, ref RECT pRect, int dwData) =>
{
_monitors.Add(GetMonitor(hMonitor));
return true;
};
NativeMethods.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, _callback, 0);
return _monitors.OrderByDescending(m => m.IsPrimary).ToArray();
}
public static Monitor GetMonitorFromIndex(int index)
{
return GetMonitorFromIndex(index, GetMonitors());
}
private static Monitor GetMonitorFromIndex(int index, Monitor[] monitors)
{
if (index < monitors.Length)
return monitors[index];
else
return monitors.GetPrimary();
}
public static void GetWorkArea(AppBarWindow window, out int screen, out DockEdge edge, out WorkArea initPos, out WorkArea windowWA, out WorkArea appbarWA)
{
screen = Framework.Settings.Instance.ScreenIndex;
edge = Framework.Settings.Instance.DockEdge;
double _uiScale = Framework.Settings.Instance.UIScale;
if (OS.SupportDPI)
{
window.UpdateScale(_uiScale, _uiScale, false);
}
Monitor[] _monitors = GetMonitors();
Monitor _primary = _monitors.GetPrimary();
Monitor _active = GetMonitorFromIndex(screen, _monitors);
initPos = new WorkArea()
{
Top = _active.WorkArea.Top,
Left = _active.WorkArea.Left,
Bottom = _active.WorkArea.Top + 10,
Right = _active.WorkArea.Left + 10
};
windowWA = Windows.WorkArea.FromRECT(_active.WorkArea);
windowWA.Scale(_active.InverseScaleX, _active.InverseScaleY);
double _modifyX = 0d;
double _modifyY = 0d;
windowWA.Offset(_modifyX, _modifyY);
double _windowWidth = Framework.Settings.Instance.SidebarWidth * _uiScale;
windowWA.SetWidth(edge, _windowWidth);
int _offsetX = Framework.Settings.Instance.XOffset;
int _offsetY = Framework.Settings.Instance.YOffset;
windowWA.Offset(_offsetX, _offsetY);
appbarWA = Windows.WorkArea.FromRECT(_active.WorkArea);
appbarWA.Offset(_modifyX, _modifyY);
double _appbarWidth = Framework.Settings.Instance.UseAppBar ? windowWA.Width * _active.ScaleX : 0;
appbarWA.SetWidth(edge, _appbarWidth);
appbarWA.Offset(_offsetX, _offsetY);
}
}
public static class MonitorExtensions
{
public static Monitor GetPrimary(this Monitor[] monitors)
{
return monitors.Where(m => m.IsPrimary).Single();
}
}
public partial class DPIAwareWindow : FlatWindow
{
private static class WM_MESSAGES
{
public const int WM_DPICHANGED = 0x02E0;
public const int WM_GETMINMAXINFO = 0x0024;
public const int WM_SIZE = 0x0005;
public const int WM_WINDOWPOSCHANGING = 0x0046;
public const int WM_WINDOWPOSCHANGED = 0x0047;
}
public override void BeginInit()
{
Utilities.Culture.SetCurrent(false);
base.BeginInit();
}
public override void EndInit()
{
base.EndInit();
_originalWidth = base.Width;
_originalHeight = base.Height;
if (AutoDPI && OS.SupportDPI)
{
Loaded += DPIAwareWindow_Loaded;
}
}
public void HandleDPI()
{
//IntPtr _hwnd = new WindowInteropHelper(this).Handle;
//IntPtr _hmonitor = NativeMethods.MonitorFromWindow(_hwnd, 0);
//Monitor _monitorInfo = Monitor.GetMonitor(_hmonitor);
double _uiScale = Framework.Settings.Instance.UIScale;
UpdateScale(_uiScale, _uiScale, true);
}
public void UpdateScale(double scaleX, double scaleY, bool resize)
{
if (VisualChildrenCount > 0)
{
GetVisualChild(0).SetValue(LayoutTransformProperty, new ScaleTransform(scaleX, scaleY));
}
if (resize)
{
SizeToContent _autosize = SizeToContent;
SizeToContent = SizeToContent.Manual;
base.Width = _originalWidth * scaleX;
base.Height = _originalHeight * scaleY;
SizeToContent = _autosize;
}
}
private void DPIAwareWindow_Loaded(object sender, RoutedEventArgs e)
{
HandleDPI();
Framework.Settings.Instance.PropertyChanged += UIScale_PropertyChanged;
//HwndSource.AddHook(WindowHook);
}
private void UIScale_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "UIScale")
{
HandleDPI();
}
}
//private IntPtr WindowHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
//{
// if (msg == WM_MESSAGES.WM_DPICHANGED)
// {
// HandleDPI();
// handled = true;
// }
// return IntPtr.Zero;
//}
public HwndSource HwndSource
{
get
{
return (HwndSource)PresentationSource.FromVisual(this);
}
}
public static readonly DependencyProperty AutoDPIProperty = DependencyProperty.Register("AutoDPI", typeof(bool), typeof(DPIAwareWindow), new UIPropertyMetadata(true));
public bool AutoDPI
{
get
{
return (bool)GetValue(AutoDPIProperty);
}
set
{
SetValue(AutoDPIProperty, value);
}
}
public new double Width
{
get
{
return base.Width;
}
set
{
_originalWidth = base.Width = value;
}
}
public new double Height
{
get
{
return base.Height;
}
set
{
_originalHeight = base.Height = value;
}
}
private double _originalWidth { get; set; }
private double _originalHeight { get; set; }
}
[Serializable]
public enum DockEdge : byte
{
Left,
Top,
Right,
Bottom,
None
}
public partial class AppBarWindow : DPIAwareWindow
{
[StructLayout(LayoutKind.Sequential)]
internal struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
}
private static class APPBARMSG
{
public const int ABM_NEW = 0;
public const int ABM_REMOVE = 1;
public const int ABM_QUERYPOS = 2;
public const int ABM_SETPOS = 3;
public const int ABM_GETSTATE = 4;
public const int ABM_GETTASKBARPOS = 5;
public const int ABM_ACTIVATE = 6;
public const int ABM_GETAUTOHIDEBAR = 7;
public const int ABM_SETAUTOHIDEBAR = 8;
public const int ABM_WINDOWPOSCHANGED = 9;
public const int ABM_SETSTATE = 10;
}
private static class APPBARNOTIFY
{
public const int ABN_STATECHANGE = 0;
public const int ABN_POSCHANGED = 1;
public const int ABN_FULLSCREENAPP = 2;
public const int ABN_WINDOWARRANGE = 3;
}
internal enum DWMWINDOWATTRIBUTE : int
{
DWMWA_NCRENDERING_ENABLED = 1,
DWMWA_NCRENDERING_POLICY = 2,
DWMWA_TRANSITIONS_FORCEDISABLED = 3,
DWMWA_ALLOW_NCPAINT = 4,
DWMWA_CAPTION_BUTTON_BOUNDS = 5,
DWMWA_NONCLIENT_RTL_LAYOUT = 6,
DWMWA_FORCE_ICONIC_REPRESENTATION = 7,
DWMWA_FLIP3D_POLICY = 8,
DWMWA_EXTENDED_FRAME_BOUNDS = 9,
DWMWA_HAS_ICONIC_BITMAP = 10,
DWMWA_DISALLOW_PEEK = 11,
DWMWA_EXCLUDED_FROM_PEEK = 12,
DWMWA_CLOAK = 13,
DWMWA_CLOAKED = 14,
DWMWA_FREEZE_REPRESENTATION = 15,
DWMWA_LAST = 16
}
private static class HWND_FLAG
{
public static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
public const uint SWP_NOSIZE = 0x0001;
public const uint SWP_NOMOVE = 0x0002;
public const uint SWP_NOACTIVATE = 0x0010;
}
private static class WND_STYLE
{
public const int GWL_EXSTYLE = -20;
public const long WS_EX_TRANSPARENT = 32;
public const long WS_EX_TOOLWINDOW = 128;
}
private static class WM_WINDOWPOSCHANGING
{
public const int MSG = 0x0046;
public const int SWP_NOMOVE = 0x0002;
}
[StructLayout(LayoutKind.Sequential)]
internal struct WINDOWPOS
{
public IntPtr hWnd;
public IntPtr hWndInsertAfter;
public int x;
public int y;
public int cx;
public int cy;
public uint flags;
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
Loaded += AppBarWindow_Loaded;
}
private void AppBarWindow_Loaded(object sender, RoutedEventArgs e)
{
PreventMove();
}
public void Move(WorkArea workArea)
{
AllowMove();
Left = workArea.Left;
Top = workArea.Top;
Width = workArea.Width;
Height = workArea.Height;
PreventMove();
}
private void PreventMove()
{
if (!_canMove)
{
return;
}
_canMove = false;
HwndSource.AddHook(MoveHook);
}
private void AllowMove()
{
if (_canMove)
{
return;
}
_canMove = true;
HwndSource.RemoveHook(MoveHook);
}
private IntPtr MoveHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_WINDOWPOSCHANGING.MSG)
{
WINDOWPOS _pos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
_pos.flags |= WM_WINDOWPOSCHANGING.SWP_NOMOVE;
Marshal.StructureToPtr(_pos, lParam, true);
handled = true;
}
return IntPtr.Zero;
}
public void SetTopMost(bool activate)
{
if (IsTopMost)
{
return;
}
IsTopMost = true;
SetPos(HWND_FLAG.HWND_TOPMOST, activate);
}
public void ClearTopMost(bool activate)
{
if (!IsTopMost)
{
return;
}
IsTopMost = false;
SetPos(HWND_FLAG.HWND_NOTOPMOST, activate);
}
public void SetBottom(bool activate)
{
IsTopMost = false;
SetPos(HWND_FLAG.HWND_BOTTOM, activate);
}
private void SetPos(IntPtr hwnd_after, bool activate)
{
uint _uflags = HWND_FLAG.SWP_NOMOVE | HWND_FLAG.SWP_NOSIZE;
if (!activate)
{
_uflags |= HWND_FLAG.SWP_NOACTIVATE;
}
NativeMethods.SetWindowPos(
new WindowInteropHelper(this).Handle,
hwnd_after,
0,
0,
0,
0,
_uflags
);
}
public void SetClickThrough()
{
if (IsClickThrough)
{
return;
}
IsClickThrough = true;
SetWindowLong(WND_STYLE.WS_EX_TRANSPARENT, null);
}
public void ClearClickThrough()
{
if (!IsClickThrough)
{
return;
}
IsClickThrough = false;
SetWindowLong(null, WND_STYLE.WS_EX_TRANSPARENT);
}
public void ShowInAltTab()
{
if (IsInAltTab)
{
return;
}
IsInAltTab = true;
SetWindowLong(null, WND_STYLE.WS_EX_TOOLWINDOW);
}
public void HideInAltTab()
{
if (!IsInAltTab)
{
return;
}
IsInAltTab = false;
SetWindowLong(WND_STYLE.WS_EX_TOOLWINDOW, null);
}
public void DisableAeroPeek()
{
IntPtr _hwnd = new WindowInteropHelper(this).Handle;
IntPtr _status = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(_status, 1);
NativeMethods.DwmSetWindowAttribute(_hwnd, DWMWINDOWATTRIBUTE.DWMWA_EXCLUDED_FROM_PEEK, _status, sizeof(int));
}
private void SetWindowLong(long? add, long? remove)
{
IntPtr _hwnd = new WindowInteropHelper(this).Handle;
bool _32bit = IntPtr.Size == 4;
long _style;
if (_32bit)
{
_style = NativeMethods.GetWindowLong(_hwnd, WND_STYLE.GWL_EXSTYLE);
}
else
{
_style = NativeMethods.GetWindowLongPtr(_hwnd, WND_STYLE.GWL_EXSTYLE);
}
if (add.HasValue)
{
_style |= add.Value;
}
if (remove.HasValue)
{
_style &= ~remove.Value;
}
if (_32bit)
{
NativeMethods.SetWindowLong(_hwnd, WND_STYLE.GWL_EXSTYLE, _style);
}
else
{
NativeMethods.SetWindowLongPtr(_hwnd, WND_STYLE.GWL_EXSTYLE, _style);
}
}
public async Task SetAppBar()
{
ClearAppBar();
await Task.Delay(100).ContinueWith(async (_) =>
{
await Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(async () =>
{
await BindAppBar();
}));
});
}
private async Task BindAppBar()
{
Monitor.GetWorkArea(this, out int screen, out DockEdge edge, out WorkArea initPos, out WorkArea windowWA, out WorkArea appbarWA);
Move(initPos);
APPBARDATA _data = NewData();
_callbackID = _data.uCallbackMessage = NativeMethods.RegisterWindowMessage("AppBarMessage");
NativeMethods.SHAppBarMessage(APPBARMSG.ABM_NEW, ref _data);
Screen = screen;
DockEdge = edge;
_data.uEdge = (int)edge;
_data.rc = new RECT()
{
Left = (int)Math.Round(appbarWA.Left),
Top = (int)Math.Round(appbarWA.Top),
Right = (int)Math.Round(appbarWA.Right),
Bottom = (int)Math.Round(appbarWA.Bottom)
};
NativeMethods.SHAppBarMessage(APPBARMSG.ABM_QUERYPOS, ref _data);
NativeMethods.SHAppBarMessage(APPBARMSG.ABM_SETPOS, ref _data);
IsAppBar = true;
appbarWA.Left = _data.rc.Left;
appbarWA.Top = _data.rc.Top;
appbarWA.Right = _data.rc.Right;
appbarWA.Bottom = _data.rc.Bottom;
AppBarWidth = appbarWA.Width;
await Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() =>
{
Move(windowWA);
}));
await Task.Delay(500).ContinueWith(async (_) =>
{
await Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() =>
{
HwndSource.AddHook(AppBarHook);
}));
});
}
public void ClearAppBar()
{
if (!IsAppBar)
{
return;
}
HwndSource.RemoveHook(AppBarHook);
APPBARDATA _data = NewData();
NativeMethods.SHAppBarMessage(APPBARMSG.ABM_REMOVE, ref _data);
IsAppBar = false;
}
public virtual async Task AppBarShow()
{
if (Framework.Settings.Instance.UseAppBar)
{
await SetAppBar();
}
Show();
}
public virtual void AppBarHide()
{
Hide();
if (IsAppBar)
{
ClearAppBar();
}
}
private APPBARDATA NewData()
{
APPBARDATA _data = new APPBARDATA();
_data.cbSize = Marshal.SizeOf(_data);
_data.hWnd = new WindowInteropHelper(this).Handle;
return _data;
}
private IntPtr AppBarHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == _callbackID)
{
switch (wParam.ToInt32())
{
case APPBARNOTIFY.ABN_POSCHANGED:
SetAppBar();
break;
case APPBARNOTIFY.ABN_FULLSCREENAPP:
if (lParam.ToInt32() == 1)
{
_wasTopMost = IsTopMost;
if (IsTopMost)
{
SetBottom(false);
}
}
else if (_wasTopMost)
{
SetTopMost(false);
}
break;
}
handled = true;
}
return IntPtr.Zero;
}
public bool IsTopMost { get; private set; } = false;
public bool IsClickThrough { get; private set; } = false;
public bool IsInAltTab { get; private set; } = true;
public bool IsAppBar { get; private set; } = false;
public int Screen { get; private set; } = 0;
public DockEdge DockEdge { get; private set; } = DockEdge.None;
public double AppBarWidth { get; private set; } = 0;
private bool _canMove { get; set; } = true;
private bool _wasTopMost { get; set; } = false;
private int _callbackID { get; set; }
private CancellationTokenSource _cancelReposition { get; set; }
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Windows.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 8,553 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Windows.Threading;
using System.Windows.Media;
using LibreHardwareMonitor.Hardware;
using Newtonsoft.Json;
using SidebarDiagnostics.Framework;
namespace SidebarDiagnostics.Monitoring
{
public class MonitorManager : INotifyPropertyChanged, IDisposable
{
public MonitorManager(MonitorConfig[] config)
{
_computer = new Computer()
{
IsCpuEnabled = true,
IsControllerEnabled = true,
IsGpuEnabled = true,
IsStorageEnabled = false,
IsMotherboardEnabled = true,
IsMemoryEnabled = true,
IsNetworkEnabled = false
};
_computer.Open();
_board = GetHardware(HardwareType.Motherboard).FirstOrDefault();
UpdateBoard();
MonitorPanels = config.Where(c => c.Enabled).OrderByDescending(c => c.Order).Select(c => NewPanel(c)).ToArray();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
foreach (MonitorPanel _panel in MonitorPanels)
{
_panel.Dispose();
}
_computer.Close();
_monitorPanels = null;
_computer = null;
_board = null;
}
_disposed = true;
}
}
~MonitorManager()
{
Dispose(false);
}
public HardwareConfig[] GetHardware(MonitorType type)
{
switch (type)
{
case MonitorType.CPU:
case MonitorType.RAM:
case MonitorType.GPU:
return GetHardware(type.GetHardwareTypes()).Select(h => new HardwareConfig() { ID = h.Identifier.ToString(), Name = h.Name, ActualName = h.Name }).ToArray();
case MonitorType.HD:
return DriveMonitor.GetHardware().ToArray();
case MonitorType.Network:
return NetworkMonitor.GetHardware().ToArray();
default:
throw new ArgumentException("Invalid MonitorType.");
}
}
public void Update()
{
UpdateBoard();
foreach (iMonitor _monitor in MonitorPanels.SelectMany(p => p.Monitors))
{
_monitor.Update();
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private IEnumerable<IHardware> GetHardware(params HardwareType[] types)
{
return _computer.Hardware.Where(h => types.Contains(h.HardwareType));
}
private MonitorPanel NewPanel(MonitorConfig config)
{
switch (config.Type)
{
case MonitorType.CPU:
return OHMPanel(
config.Type,
"M 19,19L 57,19L 57,22.063C 56.1374,22.285 55.5,23.0681 55.5,24C 55.5,24.9319 56.1374,25.715 57,25.937L 57,57L 19,57L 19,27.937C 19.8626,27.715 20.5,26.9319 20.5,26C 20.5,25.0681 19.8626,24.285 19,24.063L 19,19 Z M 21.9998,22.0005L 21.9998,24.0005L 23.9998,24.0005L 23.9998,22.0005L 21.9998,22.0005 Z M 24.9998,22.0005L 24.9998,24.0005L 26.9998,24.0005L 26.9998,22.0005L 24.9998,22.0005 Z M 27.9998,22.0005L 27.9998,24.0005L 29.9998,24.0005L 29.9998,22.0005L 27.9998,22.0005 Z M 30.9998,22.0005L 30.9998,24.0005L 32.9998,24.0005L 32.9998,22.0005L 30.9998,22.0005 Z M 33.9998,22.0005L 33.9998,24.0005L 35.9998,24.0005L 35.9998,22.0005L 33.9998,22.0005 Z M 36.9998,22.0005L 36.9998,24.0005L 38.9998,24.0005L 38.9998,22.0005L 36.9998,22.0005 Z M 39.9998,22.0005L 39.9998,24.0005L 41.9998,24.0005L 41.9998,22.0005L 39.9998,22.0005 Z M 42.9995,22.0005L 42.9995,24.0005L 44.9995,24.0005L 44.9995,22.0005L 42.9995,22.0005 Z M 45.9995,22.0005L 45.9995,24.0005L 47.9995,24.0005L 47.9995,22.0005L 45.9995,22.0005 Z M 48.9995,22.0004L 48.9995,24.0004L 50.9995,24.0004L 50.9995,22.0004L 48.9995,22.0004 Z M 51.9996,22.0004L 51.9996,24.0004L 53.9996,24.0004L 53.9996,22.0004L 51.9996,22.0004 Z M 21.9998,25.0004L 21.9998,27.0004L 23.9998,27.0004L 23.9998,25.0004L 21.9998,25.0004 Z M 24.9998,25.0004L 24.9998,27.0004L 26.9998,27.0004L 26.9998,25.0004L 24.9998,25.0004 Z M 27.9998,25.0004L 27.9998,27.0004L 29.9998,27.0004L 29.9998,25.0004L 27.9998,25.0004 Z M 30.9998,25.0004L 30.9998,27.0004L 32.9998,27.0004L 32.9998,25.0004L 30.9998,25.0004 Z M 33.9998,25.0004L 33.9998,27.0004L 35.9998,27.0004L 35.9998,25.0004L 33.9998,25.0004 Z M 36.9998,25.0004L 36.9998,27.0004L 38.9998,27.0004L 38.9998,25.0004L 36.9998,25.0004 Z M 39.9998,25.0004L 39.9998,27.0004L 41.9998,27.0004L 41.9998,25.0004L 39.9998,25.0004 Z M 42.9996,25.0004L 42.9996,27.0004L 44.9996,27.0004L 44.9996,25.0004L 42.9996,25.0004 Z M 45.9996,25.0004L 45.9996,27.0004L 47.9996,27.0004L 47.9996,25.0004L 45.9996,25.0004 Z M 48.9996,25.0004L 48.9996,27.0004L 50.9996,27.0004L 50.9996,25.0004L 48.9996,25.0004 Z M 51.9996,25.0004L 51.9996,27.0004L 53.9996,27.0004L 53.9996,25.0004L 51.9996,25.0004 Z M 21.9998,28.0004L 21.9998,30.0004L 23.9998,30.0004L 23.9998,28.0004L 21.9998,28.0004 Z M 24.9998,28.0004L 24.9998,30.0004L 26.9998,30.0004L 26.9998,28.0004L 24.9998,28.0004 Z M 27.9998,28.0004L 27.9998,30.0004L 29.9998,30.0004L 29.9998,28.0004L 27.9998,28.0004 Z M 30.9998,28.0004L 30.9998,30.0004L 32.9998,30.0004L 32.9998,28.0004L 30.9998,28.0004 Z M 33.9998,28.0004L 33.9998,30.0004L 35.9998,30.0004L 35.9998,28.0004L 33.9998,28.0004 Z M 36.9998,28.0004L 36.9998,30.0004L 38.9998,30.0004L 38.9998,28.0004L 36.9998,28.0004 Z M 39.9998,28.0004L 39.9998,30.0004L 41.9998,30.0004L 41.9998,28.0004L 39.9998,28.0004 Z M 42.9996,28.0004L 42.9996,30.0004L 44.9996,30.0004L 44.9996,28.0004L 42.9996,28.0004 Z M 45.9997,28.0004L 45.9997,30.0004L 47.9997,30.0004L 47.9997,28.0004L 45.9997,28.0004 Z M 48.9997,28.0003L 48.9997,30.0003L 50.9997,30.0003L 50.9997,28.0003L 48.9997,28.0003 Z M 51.9997,28.0003L 51.9997,30.0003L 53.9997,30.0003L 53.9997,28.0003L 51.9997,28.0003 Z M 21.9998,31.0003L 21.9998,33.0003L 23.9998,33.0003L 23.9998,31.0003L 21.9998,31.0003 Z M 24.9998,31.0003L 24.9998,33.0003L 26.9998,33.0003L 26.9998,31.0003L 24.9998,31.0003 Z M 27.9998,31.0003L 27.9998,33.0003L 29.9998,33.0003L 29.9998,31.0003L 27.9998,31.0003 Z M 45.9997,31.0003L 45.9997,33.0003L 47.9997,33.0003L 47.9997,31.0003L 45.9997,31.0003 Z M 48.9997,31.0003L 48.9997,33.0003L 50.9997,33.0003L 50.9997,31.0003L 48.9997,31.0003 Z M 51.9997,31.0003L 51.9997,33.0003L 53.9997,33.0003L 53.9997,31.0003L 51.9997,31.0003 Z M 21.9998,34.0001L 21.9998,36.0001L 23.9998,36.0001L 23.9998,34.0001L 21.9998,34.0001 Z M 24.9999,34.0001L 24.9999,36.0001L 26.9999,36.0001L 26.9999,34.0001L 24.9999,34.0001 Z M 27.9999,34.0001L 27.9999,36.0001L 29.9999,36.0001L 29.9999,34.0001L 27.9999,34.0001 Z M 45.9997,34.0001L 45.9997,36.0001L 47.9997,36.0001L 47.9997,34.0001L 45.9997,34.0001 Z M 48.9997,34.0001L 48.9997,36.0001L 50.9997,36.0001L 50.9997,34.0001L 48.9997,34.0001 Z M 51.9997,34.0001L 51.9997,36.0001L 53.9997,36.0001L 53.9997,34.0001L 51.9997,34.0001 Z M 21.9999,37.0001L 21.9999,39.0001L 23.9999,39.0001L 23.9999,37.0001L 21.9999,37.0001 Z M 24.9999,37.0001L 24.9999,39.0001L 26.9999,39.0001L 26.9999,37.0001L 24.9999,37.0001 Z M 27.9999,37.0001L 27.9999,39.0001L 29.9999,39.0001L 29.9999,37.0001L 27.9999,37.0001 Z M 45.9997,37.0001L 45.9997,39.0001L 47.9997,39.0001L 47.9997,37.0001L 45.9997,37.0001 Z M 48.9998,37.0001L 48.9998,39.0001L 50.9998,39.0001L 50.9998,37.0001L 48.9998,37.0001 Z M 51.9998,37.0001L 51.9998,39.0001L 53.9998,39.0001L 53.9998,37.0001L 51.9998,37.0001 Z M 21.9999,40.0001L 21.9999,42.0001L 23.9999,42.0001L 23.9999,40.0001L 21.9999,40.0001 Z M 24.9999,40.0001L 24.9999,42.0001L 26.9999,42.0001L 26.9999,40.0001L 24.9999,40.0001 Z M 27.9999,40.0001L 27.9999,42.0001L 29.9999,42.0001L 29.9999,40.0001L 27.9999,40.0001 Z M 45.9998,40.0001L 45.9998,42.0001L 47.9998,42.0001L 47.9998,40.0001L 45.9998,40.0001 Z M 48.9998,40.0001L 48.9998,42.0001L 50.9998,42.0001L 50.9998,40.0001L 48.9998,40.0001 Z M 51.9998,40.0001L 51.9998,42.0001L 53.9998,42.0001L 53.9998,40.0001L 51.9998,40.0001 Z M 21.9999,43.0001L 21.9999,45.0001L 23.9999,45.0001L 23.9999,43.0001L 21.9999,43.0001 Z M 24.9999,43.0001L 24.9999,45.0001L 26.9999,45.0001L 26.9999,43.0001L 24.9999,43.0001 Z M 27.9999,43.0001L 27.9999,45.0001L 29.9999,45.0001L 29.9999,43.0001L 27.9999,43.0001 Z M 45.9998,43.0001L 45.9998,45.0001L 47.9998,45.0001L 47.9998,43.0001L 45.9998,43.0001 Z M 48.9998,43.0001L 48.9998,45.0001L 50.9998,45.0001L 50.9998,43.0001L 48.9998,43.0001 Z M 51.9998,43.0001L 51.9998,45.0001L 53.9998,45.0001L 53.9998,43.0001L 51.9998,43.0001 Z M 21.9999,46.0001L 21.9999,48.0001L 23.9999,48.0001L 23.9999,46.0001L 21.9999,46.0001 Z M 24.9999,46.0001L 24.9999,48.0001L 26.9999,48.0001L 26.9999,46.0001L 24.9999,46.0001 Z M 27.9999,46.0001L 27.9999,48.0001L 29.9999,48.0001L 29.9999,46.0001L 27.9999,46.0001 Z M 30.9999,46.0001L 30.9999,48.0001L 32.9999,48.0001L 32.9999,46.0001L 30.9999,46.0001 Z M 33.9999,46.0001L 33.9999,48.0001L 35.9999,48.0001L 35.9999,46.0001L 33.9999,46.0001 Z M 36.9999,46.0001L 36.9999,48.0001L 38.9999,48.0001L 38.9999,46.0001L 36.9999,46.0001 Z M 39.9999,46.0001L 39.9999,48.0001L 41.9999,48.0001L 41.9999,46.0001L 39.9999,46.0001 Z M 42.9999,46.0001L 42.9999,48.0001L 44.9999,48.0001L 44.9999,46.0001L 42.9999,46.0001 Z M 45.9999,46.0001L 45.9999,48.0001L 47.9999,48.0001L 47.9999,46.0001L 45.9999,46.0001 Z M 48.9999,46.0001L 48.9999,48.0001L 50.9999,48.0001L 50.9999,46.0001L 48.9999,46.0001 Z M 51.9999,46.0001L 51.9999,48.0001L 53.9999,48.0001L 53.9999,46.0001L 51.9999,46.0001 Z M 21.9999,49.0001L 21.9999,51.0001L 23.9999,51.0001L 23.9999,49.0001L 21.9999,49.0001 Z M 24.9999,49.0001L 24.9999,51.0001L 26.9999,51.0001L 26.9999,49.0001L 24.9999,49.0001 Z M 27.9999,49.0001L 27.9999,51.0001L 29.9999,51.0001L 29.9999,49.0001L 27.9999,49.0001 Z M 30.9999,49.0001L 30.9999,51.0001L 33,51.0001L 33,49.0001L 30.9999,49.0001 Z M 34,49.0001L 34,51.0001L 36,51.0001L 36,49.0001L 34,49.0001 Z M 37,49.0001L 37,51.0001L 39,51.0001L 39,49.0001L 37,49.0001 Z M 40,49.0001L 40,51.0001L 42,51.0001L 42,49.0001L 40,49.0001 Z M 42.9999,49.0001L 42.9999,51.0001L 44.9999,51.0001L 44.9999,49.0001L 42.9999,49.0001 Z M 45.9999,49L 45.9999,51L 47.9999,51L 47.9999,49L 45.9999,49 Z M 48.9999,49L 48.9999,51L 50.9999,51L 50.9999,49L 48.9999,49 Z M 51.9999,49L 51.9999,51L 53.9999,51L 53.9999,49L 51.9999,49 Z M 22,52L 22,54L 24,54L 24,52L 22,52 Z M 25,52L 25,54L 27,54L 27,52L 25,52 Z M 28,52L 28,54L 30,54L 30,52L 28,52 Z M 31,52L 31,54L 33,54L 33,52L 31,52 Z M 34,52L 34,54L 36,54L 36,52L 34,52 Z M 37,52L 37,54L 39,54L 39,52L 37,52 Z M 40,52L 40,54L 42,54L 42,52L 40,52 Z M 43,52L 43,54L 45,54L 45,52L 43,52 Z M 46,52L 46,54L 48,54L 48,52L 46,52 Z M 49,52L 49,54L 51,54L 51,52L 49,52 Z M 52,52L 52,54L 54,54L 54,52L 52,52 Z M 31,31L 31,45L 45,45L 45,31L 31,31 Z M 33.6375,36.64L 33.4504,36.565L 33.3733,36.375L 33.4504,36.1829L 33.6375,36.1067L 33.8283,36.1829L 33.9067,36.375L 33.8283,36.5625L 33.6375,36.64 Z M 33.8533,40L 33.4266,40L 33.4266,37.3334L 33.8533,37.3334L 33.8533,40 Z M 36.9467,40L 36.52,40L 36.52,38.4942C 36.52,37.9336 36.3092,37.6533 35.8875,37.6533C 35.6697,37.6533 35.4896,37.7328 35.3471,37.8917C 35.2046,38.0506 35.1333,38.2514 35.1333,38.4942L 35.1333,40L 34.7066,40L 34.7066,37.3333L 35.1333,37.3333L 35.1333,37.7992L 35.1441,37.7992C 35.3486,37.4531 35.6444,37.28 36.0317,37.28C 36.3278,37.28 36.5543,37.3739 36.7112,37.5617C 36.8682,37.7495 36.9467,38.0206 36.9467,38.375L 36.9467,40 Z M 39.0267,39.9642L 38.6208,40.0533C 38.1447,40.0533 37.9067,39.7945 37.9067,39.2767L 37.9067,37.7067L 37.4267,37.7067L 37.4267,37.3333L 37.9067,37.3333L 37.9067,36.6733L 38.3333,36.5333L 38.3333,37.3333L 39.0267,37.3333L 39.0267,37.7067L 38.3333,37.7067L 38.3333,39.1892C 38.3333,39.3658 38.3647,39.4918 38.4275,39.5671C 38.4903,39.6424 38.5942,39.68 38.7392,39.68L 39.0267,39.5733L 39.0267,39.9642 Z M 41.6933,38.7733L 39.8267,38.7733C 39.8339,39.0628 39.9142,39.2863 40.0675,39.4438C 40.2208,39.6013 40.4319,39.68 40.7008,39.68C 41.003,39.68 41.2805,39.5911 41.5333,39.4133L 41.5333,39.8042C 41.3,39.9703 40.9911,40.0533 40.6067,40.0533C 40.2311,40.0533 39.9361,39.9331 39.7217,39.6925C 39.5072,39.452 39.4,39.1133 39.4,38.6767C 39.4,38.2645 39.516,37.9286 39.7479,37.6692C 39.9799,37.4097 40.268,37.28 40.6125,37.28C 40.9564,37.28 41.2225,37.3921 41.4108,37.6163C 41.5992,37.8404 41.6933,38.152 41.6933,38.5508L 41.6933,38.7733 Z M 41.2667,38.4C 41.265,38.1645 41.2058,37.9811 41.0892,37.85C 40.9725,37.7189 40.8103,37.6533 40.6025,37.6533C 40.4019,37.6533 40.2317,37.7222 40.0917,37.86C 39.9517,37.9978 39.8653,38.1778 39.8325,38.4L 41.2667,38.4 Z M 42.76,40L 42.3333,40L 42.3333,36.0533L 42.76,36.0533L 42.76,40 Z",
config.Hardware,
config.Metrics,
config.Params,
config.Type.GetHardwareTypes()
);
case MonitorType.RAM:
return OHMPanel(
config.Type,
"M 473.00,193.00 C 473.00,193.00 434.00,193.00 434.00,193.00 434.00,193.00 434.00,245.00 434.00,245.00 434.00,245.00 259.00,245.00 259.00,245.00 259.00,239.01 259.59,235.54 256.67,230.00 247.91,213.34 228.26,212.83 217.65,228.00 213.65,233.71 214.00,238.44 214.00,245.00 214.00,245.00 27.00,245.00 27.00,245.00 27.00,245.00 27.00,193.00 27.00,193.00 27.00,193.00 0.00,193.00 0.00,193.00 0.00,193.00 0.00,20.00 0.00,20.00 12.36,19.43 21.26,13.56 18.00,0.00 18.00,0.00 453.00,0.00 453.00,0.00 453.01,7.85 454.03,15.96 463.00,18.82 465.56,19.42 470.18,19.04 473.00,18.82 473.00,18.82 473.00,193.00 473.00,193.00 Z M 433.00,39.00 C 433.00,39.00 386.00,39.00 386.00,39.00 386.00,39.00 386.00,147.00 386.00,147.00 386.00,147.00 433.00,147.00 433.00,147.00 433.00,147.00 433.00,39.00 433.00,39.00 Z M 423.00,193.00 C 423.00,193.00 399.00,193.00 399.00,193.00 399.00,193.00 399.00,224.00 399.00,224.00 399.00,224.00 387.00,224.00 387.00,224.00 387.00,224.00 387.00,193.00 387.00,193.00 387.00,193.00 377.00,193.00 377.00,193.00 377.00,193.00 377.00,224.00 377.00,224.00 377.00,224.00 365.00,224.00 365.00,224.00 365.00,224.00 365.00,193.00 365.00,193.00 365.00,193.00 354.00,193.00 354.00,193.00 354.00,193.00 354.00,224.00 354.00,224.00 354.00,224.00 343.00,224.00 343.00,224.00 343.00,224.00 343.00,193.00 343.00,193.00 343.00,193.00 333.00,193.00 333.00,193.00 333.00,193.00 333.00,224.00 333.00,224.00 333.00,224.00 322.00,224.00 322.00,224.00 322.00,224.00 322.00,193.00 322.00,193.00 322.00,193.00 311.00,193.00 311.00,193.00 311.00,193.00 311.00,224.00 311.00,224.00 311.00,224.00 300.00,224.00 300.00,224.00 300.00,224.00 300.00,193.00 300.00,193.00 300.00,193.00 289.00,193.00 289.00,193.00 289.00,193.00 289.00,224.00 289.00,224.00 289.00,224.00 277.00,224.00 277.00,224.00 277.00,224.00 277.00,193.00 277.00,193.00 277.00,193.00 191.00,193.00 191.00,193.00 191.00,193.00 191.00,224.00 191.00,224.00 191.00,224.00 179.00,224.00 179.00,224.00 179.00,224.00 179.00,193.00 179.00,193.00 179.00,193.00 169.00,193.00 169.00,193.00 169.00,193.00 169.00,224.00 169.00,224.00 169.00,224.00 157.00,224.00 157.00,224.00 157.00,224.00 157.00,193.00 157.00,193.00 157.00,193.00 146.00,193.00 146.00,193.00 146.00,193.00 146.00,224.00 146.00,224.00 146.00,224.00 134.00,224.00 134.00,224.00 134.00,224.00 134.00,193.00 134.00,193.00 134.00,193.00 125.00,193.00 125.00,193.00 125.00,193.00 125.00,224.00 125.00,224.00 125.00,224.00 114.00,224.00 114.00,224.00 114.00,224.00 114.00,193.00 114.00,193.00 114.00,193.00 103.00,193.00 103.00,193.00 103.00,193.00 103.00,224.00 103.00,224.00 103.00,224.00 91.00,224.00 91.00,224.00 91.00,224.00 91.00,193.00 91.00,193.00 91.00,193.00 81.00,193.00 81.00,193.00 81.00,193.00 81.00,224.00 81.00,224.00 81.00,224.00 69.00,224.00 69.00,224.00 69.00,224.00 69.00,193.00 69.00,193.00 69.00,193.00 39.00,193.00 39.00,193.00 39.00,193.00 39.00,234.00 39.00,234.00 39.00,234.00 203.00,234.00 203.00,234.00 204.62,218.32 219.49,205.67 235.00,205.04 245.28,204.62 255.94,209.24 262.67,217.04 265.14,219.89 267.13,223.51 268.54,227.00 269.28,228.84 269.93,231.78 271.56,232.98 273.27,234.24 276.91,234.00 279.00,234.00 279.00,234.00 423.00,234.00 423.00,234.00 423.00,234.00 423.00,193.00 423.00,193.00 Z M 367.00,39.00 C 367.00,39.00 320.00,39.00 320.00,39.00 320.00,39.00 320.00,147.00 320.00,147.00 320.00,147.00 367.00,147.00 367.00,147.00 367.00,147.00 367.00,39.00 367.00,39.00 Z M 303.00,39.00 C 303.00,39.00 256.00,39.00 256.00,39.00 256.00,39.00 256.00,147.00 256.00,147.00 256.00,147.00 303.00,147.00 303.00,147.00 303.00,147.00 303.00,39.00 303.00,39.00 Z M 215.00,39.00 C 215.00,39.00 168.00,39.00 168.00,39.00 168.00,39.00 168.00,147.00 168.00,147.00 168.00,147.00 215.00,147.00 215.00,147.00 215.00,147.00 215.00,39.00 215.00,39.00 Z M 148.00,39.00 C 148.00,39.00 101.00,39.00 101.00,39.00 101.00,39.00 101.00,147.00 101.00,147.00 101.00,147.00 148.00,147.00 148.00,147.00 148.00,147.00 148.00,39.00 148.00,39.00 Z M 84.00,39.00 C 84.00,39.00 37.00,39.00 37.00,39.00 37.00,39.00 37.00,147.00 37.00,147.00 37.00,147.00 84.00,147.00 84.00,147.00 84.00,147.00 84.00,39.00 84.00,39.00 Z",
config.Hardware,
config.Metrics,
config.Params,
config.Type.GetHardwareTypes()
);
case MonitorType.GPU:
return OHMPanel(
config.Type,
"F1 M 20,23.0002L 55.9998,23.0002C 57.1044,23.0002 57.9998,23.8956 57.9998,25.0002L 57.9999,46C 57.9999,47.1046 57.1045,48 55.9999,48L 41,48L 41,53L 45,53C 46.1046,53 47,53.8954 47,55L 47,57L 29,57L 29,55C 29,53.8954 29.8955,53 31,53L 35,53L 35,48L 20,48C 18.8954,48 18,47.1046 18,46L 18,25.0002C 18,23.8956 18.8954,23.0002 20,23.0002 Z M 21,26.0002L 21,45L 54.9999,45L 54.9998,26.0002L 21,26.0002 Z",
config.Hardware,
config.Metrics,
config.Params,
config.Type.GetHardwareTypes()
);
case MonitorType.HD:
return DrivePanel(
config.Type,
config.Hardware,
config.Metrics,
config.Params
);
case MonitorType.Network:
return NetworkPanel(
config.Type,
config.Hardware,
config.Metrics,
config.Params
);
default:
throw new ArgumentException("Invalid MonitorType.");
}
}
private MonitorPanel OHMPanel(MonitorType type, string pathData, HardwareConfig[] hardwareConfig, MetricConfig[] metrics, ConfigParam[] parameters, params HardwareType[] hardwareTypes)
{
return new MonitorPanel(
type.GetDescription(),
pathData,
OHMMonitor.GetInstances(hardwareConfig, metrics, parameters, type, _board, GetHardware(hardwareTypes).ToArray())
);
}
private MonitorPanel DrivePanel(MonitorType type, HardwareConfig[] hardwareConfig, MetricConfig[] metrics, ConfigParam[] parameters)
{
return new MonitorPanel(
type.GetDescription(),
"m12.56977,260.69523l0,63.527l352.937,0l0,-63.527l-352.937,0zm232.938,45.881c-7.797,0 -14.118,-6.318 -14.118,-14.117c0,-7.801 6.321,-14.117 14.118,-14.117c7.795,0 14.117,6.316 14.117,14.117c0.001,7.798 -6.322,14.117 -14.117,14.117zm42.353,0c-7.797,0 -14.118,-6.318 -14.118,-14.117c0,-7.801 6.321,-14.117 14.118,-14.117c7.796,0 14.117,6.316 14.117,14.117c0,7.798 -6.321,14.117 -14.117,14.117zm42.352,0c-7.797,0 -14.117,-6.318 -14.117,-14.117c0,-7.801 6.32,-14.117 14.117,-14.117c7.796,0 14.118,6.316 14.118,14.117c0,7.798 -6.323,14.117 -14.118,14.117 M309.0357666015625,52.46223449707031 69.03976440429688,52.46223449707031 12.569778442382812,246.57623291015625 365.50677490234375,246.57623291015625z",
DriveMonitor.GetInstances(hardwareConfig, metrics, parameters)
);
}
private MonitorPanel NetworkPanel(MonitorType type, HardwareConfig[] hardwareConfig, MetricConfig[] metrics, ConfigParam[] parameters)
{
return new MonitorPanel(
type.GetDescription(),
"M 40,44L 39.9999,51L 44,51C 45.1046,51 46,51.8954 46,53L 46,57C 46,58.1046 45.1045,59 44,59L 32,59C 30.8954,59 30,58.1046 30,57L 30,53C 30,51.8954 30.8954,51 32,51L 36,51L 36,44L 40,44 Z M 47,53L 57,53L 57,57L 47,57L 47,53 Z M 29,53L 29,57L 19,57L 19,53L 29,53 Z M 19,22L 57,22L 57,31L 19,31L 19,22 Z M 55,24L 53,24L 53,29L 55,29L 55,24 Z M 51,24L 49,24L 49,29L 51,29L 51,24 Z M 47,24L 45,24L 45,29L 47,29L 47,24 Z M 21,27L 21,29L 23,29L 23,27L 21,27 Z M 19,33L 57,33L 57,42L 19,42L 19,33 Z M 55,35L 53,35L 53,40L 55,40L 55,35 Z M 51,35L 49,35L 49,40L 51,40L 51,35 Z M 47,35L 45,35L 45,40L 47,40L 47,35 Z M 21,38L 21,40L 23,40L 23,38L 21,38 Z",
NetworkMonitor.GetInstances(hardwareConfig, metrics, parameters)
);
}
private void UpdateBoard()
{
_board.Update();
}
private MonitorPanel[] _monitorPanels { get; set; }
public MonitorPanel[] MonitorPanels
{
get
{
return _monitorPanels;
}
private set
{
_monitorPanels = value;
NotifyPropertyChanged("MonitorPanels");
}
}
private Computer _computer { get; set; }
private IHardware _board { get; set; }
private bool _disposed { get; set; } = false;
}
public class MonitorPanel : INotifyPropertyChanged, IDisposable
{
public MonitorPanel(string title, string iconData, params iMonitor[] monitors)
{
IconPath = Geometry.Parse(iconData);
Title = title;
Monitors = monitors;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
foreach (iMonitor _monitor in Monitors)
{
_monitor.Dispose();
}
_monitors = null;
_iconPath = null;
}
_disposed = true;
}
}
~MonitorPanel()
{
Dispose(false);
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private Geometry _iconPath { get; set; }
public Geometry IconPath
{
get
{
return _iconPath;
}
private set
{
_iconPath = value;
NotifyPropertyChanged("IconPath");
}
}
private string _title { get; set; }
public string Title
{
get
{
return _title;
}
private set
{
_title = value;
NotifyPropertyChanged("Title");
}
}
private iMonitor[] _monitors { get; set; }
public iMonitor[] Monitors
{
get
{
return _monitors;
}
private set
{
_monitors = value;
NotifyPropertyChanged("Monitors");
}
}
private bool _disposed { get; set; } = false;
}
public interface iMonitor : INotifyPropertyChanged, IDisposable
{
string ID { get; }
string Name { get; }
bool ShowName { get; }
iMetric[] Metrics { get; }
void Update();
}
public class BaseMonitor : iMonitor
{
public BaseMonitor(string id, string name, bool showName)
{
ID = id;
Name = name;
ShowName = showName;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
foreach (iMetric _metric in Metrics)
{
_metric.Dispose();
}
_metrics = null;
}
_disposed = true;
}
}
~BaseMonitor()
{
Dispose(false);
}
public virtual void Update()
{
foreach (iMetric _metric in Metrics)
{
_metric.Update();
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private string _id { get; set; }
public string ID
{
get
{
return _id;
}
protected set
{
_id = value;
NotifyPropertyChanged("ID");
}
}
private string _name { get; set; }
public string Name
{
get
{
return _name;
}
protected set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
private bool _showName { get; set; }
public bool ShowName
{
get
{
return _showName;
}
protected set
{
_showName = value;
NotifyPropertyChanged("ShowName");
}
}
private iMetric[] _metrics { get; set; }
public iMetric[] Metrics
{
get
{
return _metrics;
}
protected set
{
_metrics = value;
NotifyPropertyChanged("Metrics");
}
}
private bool _disposed { get; set; } = false;
}
public class OHMMonitor : BaseMonitor
{
public OHMMonitor(MonitorType type, string id, string name, IHardware hardware, IHardware board, MetricConfig[] metrics, ConfigParam[] parameters) : base(id, name, parameters.GetValue<bool>(ParamKey.HardwareNames))
{
_hardware = hardware;
UpdateHardware();
switch (type)
{
case MonitorType.CPU:
InitCPU(
board,
metrics,
parameters.GetValue<bool>(ParamKey.RoundAll),
parameters.GetValue<bool>(ParamKey.AllCoreClocks),
parameters.GetValue<bool>(ParamKey.UseGHz),
parameters.GetValue<bool>(ParamKey.UseFahrenheit),
parameters.GetValue<int>(ParamKey.TempAlert)
);
break;
case MonitorType.RAM:
InitRAM(
board,
metrics,
parameters.GetValue<bool>(ParamKey.RoundAll)
);
break;
case MonitorType.GPU:
InitGPU(
metrics,
parameters.GetValue<bool>(ParamKey.RoundAll),
parameters.GetValue<bool>(ParamKey.UseGHz),
parameters.GetValue<bool>(ParamKey.UseFahrenheit),
parameters.GetValue<int>(ParamKey.TempAlert)
);
break;
default:
throw new ArgumentException("Invalid MonitorType.");
}
}
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_disposed)
{
if (disposing)
{
_hardware = null;
}
_disposed = true;
}
}
~OHMMonitor()
{
Dispose(false);
}
public static iMonitor[] GetInstances(HardwareConfig[] hardwareConfig, MetricConfig[] metrics, ConfigParam[] parameters, MonitorType type, IHardware board, IHardware[] hardware)
{
return (
from hw in hardware
join c in hardwareConfig on hw.Identifier.ToString() equals c.ID into merged
from n in merged.DefaultIfEmpty(new HardwareConfig() { ID = hw.Identifier.ToString(), Name = hw.Name, ActualName = hw.Name }).Select(n => { if (n.ActualName != hw.Name) { n.Name = n.ActualName = hw.Name; } return n; })
where n.Enabled
orderby n.Order descending, n.Name ascending
select new OHMMonitor(type, n.ID, n.Name ?? n.ActualName, hw, board, metrics, parameters)
).ToArray();
}
public override void Update()
{
UpdateHardware();
base.Update();
}
private void UpdateHardware()
{
_hardware.Update();
}
private void InitCPU(IHardware board, MetricConfig[] metrics, bool roundAll, bool allCoreClocks, bool useGHz, bool useFahrenheit, double tempAlert)
{
List<OHMMetric> _sensorList = new List<OHMMetric>();
if (metrics.IsEnabled(MetricKey.CPUClock))
{
Regex regex = new Regex(@"^.*(CPU|Core).*#(\d+)$");
var coreClocks = _hardware.Sensors
.Where(s => s.SensorType == SensorType.Clock)
.Select(s => new
{
Match = regex.Match(s.Name),
Sensor = s
})
.Where(s => s.Match.Success)
.Select(s => new
{
Index = int.Parse(s.Match.Groups[2].Value),
s.Sensor
})
.OrderBy(s => s.Index)
.ToList();
if (coreClocks.Count > 0)
{
if (allCoreClocks)
{
foreach (var coreClock in coreClocks)
{
_sensorList.Add(new OHMMetric(coreClock.Sensor, MetricKey.CPUClock, DataType.MHz, string.Format("{0} {1}", Resources.CPUCoreClockLabel, coreClock.Index - 1), (useGHz ? false : true), 0, (useGHz ? MHzToGHz.Instance : null)));
}
}
else
{
ISensor firstClock = coreClocks
.Select(s => s.Sensor)
.FirstOrDefault();
_sensorList.Add(new OHMMetric(firstClock, MetricKey.CPUClock, DataType.MHz, null, (useGHz ? false : true), 0, (useGHz ? MHzToGHz.Instance : null)));
}
}
}
if (metrics.IsEnabled(MetricKey.CPUVoltage))
{
ISensor _voltage = null;
if (board != null)
{
_voltage = board.Sensors.Where(s => s.SensorType == SensorType.Voltage && s.Name.Contains("CPU")).FirstOrDefault();
}
if (_voltage == null)
{
_voltage = _hardware.Sensors.Where(s => s.SensorType == SensorType.Voltage).FirstOrDefault();
}
if (_voltage != null)
{
_sensorList.Add(new OHMMetric(_voltage, MetricKey.CPUVoltage, DataType.Voltage, null, roundAll));
}
}
if (metrics.IsEnabled(MetricKey.CPUTemp))
{
ISensor _tempSensor = null;
_tempSensor = _hardware.Sensors.Where(s => s.SensorType == SensorType.Temperature && s.Name.Contains("CCDs Max (Tdie)")).FirstOrDefault(); // Check for AMD core chiplet dies (CCDs)
if (board != null && _tempSensor == null)
{
_tempSensor = board.Sensors.Where(s => s.SensorType == SensorType.Temperature && s.Name.Contains("CPU")).FirstOrDefault();
}
if (_tempSensor == null)
{
_tempSensor =
_hardware.Sensors.Where(s => s.SensorType == SensorType.Temperature && (s.Name == "CPU Package" || s.Name.Contains("Tdie"))).FirstOrDefault() ??
_hardware.Sensors.Where(s => s.SensorType == SensorType.Temperature).FirstOrDefault();
}
if (_tempSensor != null)
{
_sensorList.Add(new OHMMetric(_tempSensor, MetricKey.CPUTemp, DataType.Celcius, null, roundAll, tempAlert, (useFahrenheit ? CelciusToFahrenheit.Instance : null)));
}
}
if (metrics.IsEnabled(MetricKey.CPUFan))
{
ISensor _fanSensor = null;
if (board != null)
{
_fanSensor = board.Sensors.Where(s => new SensorType[2] { SensorType.Fan, SensorType.Control }.Contains(s.SensorType) && s.Name.Contains("CPU")).FirstOrDefault();
}
if (_fanSensor == null)
{
_fanSensor = _hardware.Sensors.Where(s => new SensorType[2] { SensorType.Fan, SensorType.Control }.Contains(s.SensorType)).FirstOrDefault();
}
if (_fanSensor != null)
{
_sensorList.Add(new OHMMetric(_fanSensor, MetricKey.CPUFan, DataType.RPM, null, roundAll));
}
}
bool _loadEnabled = metrics.IsEnabled(MetricKey.CPULoad);
bool _coreLoadEnabled = metrics.IsEnabled(MetricKey.CPUCoreLoad);
if (_loadEnabled || _coreLoadEnabled)
{
ISensor[] _loadSensors = _hardware.Sensors.Where(s => s.SensorType == SensorType.Load).ToArray();
if (_loadSensors.Length > 0)
{
if (_loadEnabled)
{
ISensor _totalCPU = _loadSensors.Where(s => s.Index == 0).FirstOrDefault();
if (_totalCPU != null)
{
_sensorList.Add(new OHMMetric(_totalCPU, MetricKey.CPULoad, DataType.Percent, null, roundAll));
}
}
if (_coreLoadEnabled)
{
for (int i = 1; i <= _loadSensors.Max(s => s.Index); i++)
{
ISensor _coreLoad = _loadSensors.Where(s => s.Index == i).FirstOrDefault();
if (_coreLoad != null)
{
_sensorList.Add(new OHMMetric(_coreLoad, MetricKey.CPUCoreLoad, DataType.Percent, string.Format("{0} {1}", Resources.CPUCoreLoadLabel, i - 1), roundAll));
}
}
}
}
}
Metrics = _sensorList.ToArray();
}
public void InitRAM(IHardware board, MetricConfig[] metrics, bool roundAll)
{
List<OHMMetric> _sensorList = new List<OHMMetric>();
if (metrics.IsEnabled(MetricKey.RAMClock))
{
ISensor _ramClock = _hardware.Sensors.Where(s => s.SensorType == SensorType.Clock).FirstOrDefault();
if (_ramClock != null)
{
_sensorList.Add(new OHMMetric(_ramClock, MetricKey.RAMClock, DataType.MHz, null, true));
}
}
if (metrics.IsEnabled(MetricKey.RAMVoltage))
{
ISensor _voltage = null;
if (board != null)
{
_voltage = board.Sensors.Where(s => s.SensorType == SensorType.Voltage && s.Name.Contains("RAM")).FirstOrDefault();
}
if (_voltage == null)
{
_voltage = _hardware.Sensors.Where(s => s.SensorType == SensorType.Voltage).FirstOrDefault();
}
if (_voltage != null)
{
_sensorList.Add(new OHMMetric(_voltage, MetricKey.RAMVoltage, DataType.Voltage, null, roundAll));
}
}
if (metrics.IsEnabled(MetricKey.RAMLoad))
{
ISensor _loadSensor = _hardware.Sensors.Where(s => s.SensorType == SensorType.Load && s.Index == 0).FirstOrDefault();
if (_loadSensor != null)
{
_sensorList.Add(new OHMMetric(_loadSensor, MetricKey.RAMLoad, DataType.Percent, null, roundAll));
}
}
if (metrics.IsEnabled(MetricKey.RAMUsed))
{
ISensor _usedSensor = _hardware.Sensors.Where(s => s.SensorType == SensorType.Data && s.Index == 0).FirstOrDefault();
if (_usedSensor != null)
{
_sensorList.Add(new OHMMetric(_usedSensor, MetricKey.RAMUsed, DataType.Gigabyte, null, roundAll));
}
}
if (metrics.IsEnabled(MetricKey.RAMFree))
{
ISensor _freeSensor = _hardware.Sensors.Where(s => s.SensorType == SensorType.Data && s.Index == 1).FirstOrDefault();
if (_freeSensor != null)
{
_sensorList.Add(new OHMMetric(_freeSensor, MetricKey.RAMFree, DataType.Gigabyte, null, roundAll));
}
}
Metrics = _sensorList.ToArray();
}
public void InitGPU(MetricConfig[] metrics, bool roundAll, bool useGHz, bool useFahrenheit, double tempAlert)
{
List<iMetric> _sensorList = new List<iMetric>();
if (metrics.IsEnabled(MetricKey.GPUCoreClock))
{
ISensor _coreClock = _hardware.Sensors.Where(s => s.SensorType == SensorType.Clock && s.Name.Contains("Core")).FirstOrDefault();
if (_coreClock != null)
{
_sensorList.Add(new OHMMetric(_coreClock, MetricKey.GPUCoreClock, DataType.MHz, null, (useGHz ? false : true), 0, (useGHz ? MHzToGHz.Instance : null)));
}
}
if (metrics.IsEnabled(MetricKey.GPUVRAMClock))
{
ISensor _vramClock = _hardware.Sensors.Where(s => s.SensorType == SensorType.Clock && s.Name.Contains("Memory")).FirstOrDefault();
if (_vramClock != null)
{
_sensorList.Add(new OHMMetric(_vramClock, MetricKey.GPUVRAMClock, DataType.MHz, null, (useGHz ? false : true), 0, (useGHz ? MHzToGHz.Instance : null)));
}
}
if (metrics.IsEnabled(MetricKey.GPUCoreLoad))
{
ISensor _coreLoad = _hardware.Sensors.Where(s => s.SensorType == SensorType.Load && s.Name.Contains("Core")).FirstOrDefault() ??
_hardware.Sensors.Where(s => s.SensorType == SensorType.Load && s.Index == 0).FirstOrDefault();
if (_coreLoad != null)
{
_sensorList.Add(new OHMMetric(_coreLoad, MetricKey.GPUCoreLoad, DataType.Percent, null, roundAll));
}
}
if (metrics.IsEnabled(MetricKey.GPUVRAMLoad))
{
ISensor _memoryUsed = _hardware.Sensors.Where(s => (s.SensorType == SensorType.Data || s.SensorType == SensorType.SmallData) && s.Name == "GPU Memory Used").FirstOrDefault();
ISensor _memoryTotal = _hardware.Sensors.Where(s => (s.SensorType == SensorType.Data || s.SensorType == SensorType.SmallData) && s.Name == "GPU Memory Total").FirstOrDefault();
if (_memoryUsed != null && _memoryTotal != null)
{
_sensorList.Add(new GPUVRAMMLoadMetric(_memoryUsed, _memoryTotal, MetricKey.GPUVRAMLoad, DataType.Percent, null, roundAll));
}
else
{
ISensor _vramLoad = _hardware.Sensors.Where(s => s.SensorType == SensorType.Load && s.Name.Contains("Memory")).FirstOrDefault() ??
_hardware.Sensors.Where(s => s.SensorType == SensorType.Load && s.Index == 1).FirstOrDefault();
if (_vramLoad != null)
{
_sensorList.Add(new OHMMetric(_vramLoad, MetricKey.GPUVRAMLoad, DataType.Percent, null, roundAll));
}
}
}
if (metrics.IsEnabled(MetricKey.GPUVoltage))
{
ISensor _voltage = _hardware.Sensors.Where(s => s.SensorType == SensorType.Voltage && s.Index == 0).FirstOrDefault();
if (_voltage != null)
{
_sensorList.Add(new OHMMetric(_voltage, MetricKey.GPUVoltage, DataType.Voltage, null, roundAll));
}
}
if (metrics.IsEnabled(MetricKey.GPUTemp))
{
ISensor _tempSensor = _hardware.Sensors.Where(s => s.SensorType == SensorType.Temperature && s.Index == 0).FirstOrDefault();
if (_tempSensor != null)
{
_sensorList.Add(new OHMMetric(_tempSensor, MetricKey.GPUTemp, DataType.Celcius, null, roundAll, tempAlert, (useFahrenheit ? CelciusToFahrenheit.Instance : null)));
}
}
if (metrics.IsEnabled(MetricKey.GPUFan))
{
ISensor _fanSensor = _hardware.Sensors.Where(s => s.SensorType == SensorType.Control).OrderBy(s => s.Index).FirstOrDefault();
if (_fanSensor != null)
{
_sensorList.Add(new OHMMetric(_fanSensor, MetricKey.GPUFan, DataType.Percent));
}
}
Metrics = _sensorList.ToArray();
}
private IHardware _hardware { get; set; }
private bool _disposed { get; set; } = false;
}
public class DriveMonitor : BaseMonitor
{
private const string CATEGORYNAME = "LogicalDisk";
private const string FREEMB = "Free Megabytes";
private const string PERCENTFREE = "% Free Space";
private const string BYTESREADPERSECOND = "Disk Read Bytes/sec";
private const string BYTESWRITEPERSECOND = "Disk Write Bytes/sec";
public DriveMonitor(string id, string name, MetricConfig[] metrics, bool roundAll = false, double usedSpaceAlert = 0) : base(id, name, true)
{
_loadEnabled = metrics.IsEnabled(MetricKey.DriveLoad);
bool _loadBarEnabled = metrics.IsEnabled(MetricKey.DriveLoadBar);
bool _usedEnabled = metrics.IsEnabled(MetricKey.DriveUsed);
bool _freeEnabled = metrics.IsEnabled(MetricKey.DriveFree);
bool _readEnabled = metrics.IsEnabled(MetricKey.DriveRead);
bool _writeEnabled = metrics.IsEnabled(MetricKey.DriveWrite);
if (_loadBarEnabled)
{
if (metrics.Count(m => m.Enabled) == 1 && new Regex("^[A-Z]:$").IsMatch(name))
{
Status = State.LoadBarInline;
}
else
{
Status = State.LoadBarStacked;
}
}
else
{
Status = State.NoLoadBar;
}
if (_loadBarEnabled || _loadEnabled || _usedEnabled || _freeEnabled)
{
_counterFreeMB = new PerformanceCounter(CATEGORYNAME, FREEMB, id);
_counterFreePercent = new PerformanceCounter(CATEGORYNAME, PERCENTFREE, id);
}
List<iMetric> _metrics = new List<iMetric>();
if (_loadBarEnabled || _loadEnabled)
{
LoadMetric = new BaseMetric(MetricKey.DriveLoad, DataType.Percent, null, roundAll, usedSpaceAlert);
_metrics.Add(LoadMetric);
}
if (_usedEnabled)
{
UsedMetric = new BaseMetric(MetricKey.DriveUsed, DataType.Gigabyte, null, roundAll);
_metrics.Add(UsedMetric);
}
if (_freeEnabled)
{
FreeMetric = new BaseMetric(MetricKey.DriveFree, DataType.Gigabyte, null, roundAll);
_metrics.Add(FreeMetric);
}
if (_readEnabled)
{
_metrics.Add(new PCMetric(new PerformanceCounter(CATEGORYNAME, BYTESREADPERSECOND, id), MetricKey.DriveRead, DataType.kBps, null, roundAll, 0, BytesPerSecondConverter.Instance));
}
if (_writeEnabled)
{
_metrics.Add(new PCMetric(new PerformanceCounter(CATEGORYNAME, BYTESWRITEPERSECOND, id), MetricKey.DriveWrite, DataType.kBps, null, roundAll, 0, BytesPerSecondConverter.Instance));
}
Metrics = _metrics.ToArray();
}
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_disposed)
{
if (disposing)
{
if (_loadMetric != null)
{
_loadMetric.Dispose();
_loadMetric = null;
}
if (_usedMetric != null)
{
_usedMetric.Dispose();
_usedMetric = null;
}
if (_freeMetric != null)
{
_freeMetric.Dispose();
_freeMetric = null;
}
if (_counterFreeMB != null)
{
_counterFreeMB.Dispose();
_counterFreeMB = null;
}
if (_counterFreePercent != null)
{
_counterFreePercent.Dispose();
_counterFreePercent = null;
}
}
_disposed = true;
}
}
~DriveMonitor()
{
Dispose(false);
}
public static IEnumerable<HardwareConfig> GetHardware()
{
string[] _instances;
try
{
_instances = new PerformanceCounterCategory(CATEGORYNAME).GetInstanceNames();
}
catch (InvalidOperationException)
{
_instances = new string[0];
App.ShowPerformanceCounterError();
}
Regex _regex = new Regex("^[A-Z]:$");
return _instances.Where(n => _regex.IsMatch(n)).OrderBy(d => d[0]).Select(h => new HardwareConfig() { ID = h, Name = h, ActualName = h });
}
public static iMonitor[] GetInstances(HardwareConfig[] hardwareConfig, MetricConfig[] metrics, ConfigParam[] parameters)
{
bool _roundAll = parameters.GetValue<bool>(ParamKey.RoundAll);
int _usedSpaceAlert = parameters.GetValue<int>(ParamKey.UsedSpaceAlert);
return (
from hw in GetHardware()
join c in hardwareConfig on hw.ID equals c.ID into merged
from n in merged.DefaultIfEmpty(hw).Select(n => { n.ActualName = hw.Name; return n; })
where n.Enabled
orderby n.Order descending, n.Name ascending
select new DriveMonitor(n.ID, n.Name ?? n.ActualName, metrics, _roundAll, _usedSpaceAlert)
).ToArray();
}
public override void Update()
{
if (!PerformanceCounterCategory.InstanceExists(ID, CATEGORYNAME))
{
return;
}
if (_counterFreeMB != null && _counterFreePercent != null)
{
double _freeGB = _counterFreeMB.NextValue() / 1024d;
double _freePercent = _counterFreePercent.NextValue();
double _usedPercent = 100d - _freePercent;
double _totalGB = _freeGB / (_freePercent / 100d);
double _usedGB = _totalGB - _freeGB;
if (LoadMetric != null)
{
LoadMetric.Update(_usedPercent);
}
if (UsedMetric != null)
{
UsedMetric.Update(_usedGB);
}
if (FreeMetric != null)
{
FreeMetric.Update(_freeGB);
}
}
base.Update();
}
private State _status { get; set; }
public State Status
{
get
{
return _status;
}
private set
{
_status = value;
NotifyPropertyChanged("Status");
}
}
private iMetric _loadMetric { get; set; }
public iMetric LoadMetric
{
get
{
return _loadMetric;
}
private set
{
_loadMetric = value;
NotifyPropertyChanged("LoadMetric");
}
}
private iMetric _usedMetric { get; set; }
public iMetric UsedMetric
{
get
{
return _usedMetric;
}
private set
{
_usedMetric = value;
NotifyPropertyChanged("UsedMetric");
}
}
private iMetric _freeMetric { get; set; }
public iMetric FreeMetric
{
get
{
return _freeMetric;
}
private set
{
_freeMetric = value;
NotifyPropertyChanged("FreeMetric");
}
}
public iMetric[] DriveMetrics
{
get
{
if (_loadEnabled)
{
return Metrics;
}
else
{
return Metrics.Where(m => m.Key != MetricKey.DriveLoad).ToArray();
}
}
}
private PerformanceCounter _counterFreeMB { get; set; }
private PerformanceCounter _counterFreePercent { get; set; }
private bool _loadEnabled { get; set; }
private bool _disposed { get; set; } = false;
public enum State : byte
{
NoLoadBar,
LoadBarInline,
LoadBarStacked
}
}
public class NetworkMonitor : BaseMonitor
{
private const string CATEGORYNAME = "Network Interface";
private const string BYTESRECEIVEDPERSECOND = "Bytes Received/sec";
private const string BYTESSENTPERSECOND = "Bytes Sent/sec";
public NetworkMonitor(string id, string name, string extIP, MetricConfig[] metrics, bool showName = true, bool roundAll = false, bool useBytes = false, double bandwidthInAlert = 0, double bandwidthOutAlert = 0) : base(id, name, showName)
{
iConverter _converter;
if (useBytes)
{
_converter = BytesPerSecondConverter.Instance;
}
else
{
_converter = BitsPerSecondConverter.Instance;
}
List<iMetric> _metrics = new List<iMetric>();
if (metrics.IsEnabled(MetricKey.NetworkIP))
{
string _ipAddress = GetAdapterIPAddress(name);
if (!string.IsNullOrEmpty(_ipAddress))
{
_metrics.Add(new IPMetric(_ipAddress, MetricKey.NetworkIP, DataType.IP));
}
}
if (!string.IsNullOrEmpty(extIP))
{
_metrics.Add(new IPMetric(extIP, MetricKey.NetworkExtIP, DataType.IP));
}
if (metrics.IsEnabled(MetricKey.NetworkIn))
{
_metrics.Add(new PCMetric(new PerformanceCounter(CATEGORYNAME, BYTESRECEIVEDPERSECOND, id), MetricKey.NetworkIn, DataType.kbps, null, roundAll, bandwidthInAlert, _converter));
}
if (metrics.IsEnabled(MetricKey.NetworkOut))
{
_metrics.Add(new PCMetric(new PerformanceCounter(CATEGORYNAME, BYTESSENTPERSECOND, id), MetricKey.NetworkOut, DataType.kbps, null, roundAll, bandwidthOutAlert, _converter));
}
Metrics = _metrics.ToArray();
}
~NetworkMonitor()
{
Dispose(false);
}
public static IEnumerable<HardwareConfig> GetHardware()
{
string[] _instances;
try
{
_instances = new PerformanceCounterCategory(CATEGORYNAME).GetInstanceNames();
}
catch (InvalidOperationException)
{
_instances = new string[0];
App.ShowPerformanceCounterError();
}
Regex _regex = new Regex(@"^isatap.*$");
return _instances.Where(i => !_regex.IsMatch(i)).OrderBy(h => h).Select(h => new HardwareConfig() { ID = h, Name = h, ActualName = h });
}
public static iMonitor[] GetInstances(HardwareConfig[] hardwareConfig, MetricConfig[] metrics, ConfigParam[] parameters)
{
bool _showName = parameters.GetValue<bool>(ParamKey.HardwareNames);
bool _roundAll = parameters.GetValue<bool>(ParamKey.RoundAll);
bool _useBytes = parameters.GetValue<bool>(ParamKey.UseBytes);
int _bandwidthInAlert = parameters.GetValue<int>(ParamKey.BandwidthInAlert);
int _bandwidthOutAlert = parameters.GetValue<int>(ParamKey.BandwidthOutAlert);
string _extIP = null;
if (metrics.IsEnabled(MetricKey.NetworkExtIP))
{
_extIP = GetExternalIPAddress();
}
return (
from hw in GetHardware()
join c in hardwareConfig on hw.ID equals c.ID into merged
from n in merged.DefaultIfEmpty(hw).Select(n => { n.ActualName = hw.Name; return n; })
where n.Enabled
orderby n.Order descending, n.Name ascending
select new NetworkMonitor(n.ID, n.Name ?? n.ActualName, _extIP, metrics, _showName, _roundAll, _useBytes, _bandwidthInAlert, _bandwidthOutAlert)
).ToArray();
}
public override void Update()
{
if (!PerformanceCounterCategory.InstanceExists(ID, CATEGORYNAME))
{
return;
}
base.Update();
}
private static string GetAdapterIPAddress(string name)
{
//Here we need to match the apdapter returned by the network interface to the
//adapter represented by this instance of the class.
string configuredName = Regex.Replace(name, @"[^\w\d\s]", "");
foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces())
{
//Strange pattern matching as the Performance Monitor routines which provide the ID and Names
//instantiating this class return different values for the devices than the NetworkInterface calls used here.
//For example Performance Monitor routines return Intel[R] where as NetworkInterface returns Intel(R) causing the
//strings not to match. So to get around this, use Regex to strip off the special characters and just compare the string values.
//Also, in some cases the values for Description match the Performance Monitor calls, and
//in others the Name is what matches. It's a little weird, but this will pick up all 4 network adapters on
//my test machine correctly.
string interfaceDesc = Regex.Replace(netif.Description, @"[^\w\d\s]", "");
string interfaceName = Regex.Replace(netif.Name, @"[^\w\d\s]", "");
if (interfaceDesc == configuredName || interfaceName == configuredName)
{
IPInterfaceProperties properties = netif.GetIPProperties();
foreach (IPAddressInformation unicast in properties.UnicastAddresses)
{
if (unicast.Address.AddressFamily == AddressFamily.InterNetwork)
{
return unicast.Address.ToString();
}
}
}
}
return null;
}
private static string GetExternalIPAddress()
{
try
{
HttpWebRequest _request = WebRequest.CreateHttp(Constants.URLs.IPIFY);
_request.Method = HttpMethod.Get.Method;
_request.Timeout = 5000;
using (HttpWebResponse _response = (HttpWebResponse)_request.GetResponse())
{
using (Stream _stream = _response.GetResponseStream())
{
using (StreamReader _reader = new StreamReader(_stream))
{
return _reader.ReadToEnd();
}
}
}
}
catch (WebException)
{
return "";
}
}
}
public interface iMetric : INotifyPropertyChanged, IDisposable
{
MetricKey Key { get; }
string FullName { get; }
string Label { get; }
double Value { get; }
string Append { get; }
double nValue { get; }
string nAppend { get; }
string Text { get; }
bool IsAlert { get; }
bool IsNumeric { get; }
void Update();
void Update(double value);
}
public class BaseMetric : iMetric
{
public BaseMetric(MetricKey key, DataType dataType, string label = null, bool round = false, double alertValue = 0, iConverter converter = null)
{
_converter = converter;
_round = round;
_alertValue = alertValue;
Key = key;
if (label == null)
{
FullName = key.GetFullName();
Label = key.GetLabel();
}
else
{
FullName = Label = label;
}
nAppend = Append = converter == null ? dataType.GetAppend() : converter.TargetType.GetAppend();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_alertColorTimer != null)
{
_alertColorTimer.Stop();
_alertColorTimer = null;
}
_converter = null;
}
_disposed = true;
}
}
~BaseMetric()
{
Dispose(false);
}
public virtual void Update() { }
public void Update(double value)
{
double _val = value;
if (_converter == null)
{
nValue = _val;
}
else if (_converter.IsDynamic)
{
double _nVal;
DataType _dataType;
_converter.Convert(ref _val, out _nVal, out _dataType);
nValue = _nVal;
Append = _dataType.GetAppend();
}
else
{
_converter.Convert(ref _val);
nValue = _val;
}
Value = _val;
if (_alertValue > 0 && _alertValue <= nValue)
{
if (!IsAlert)
{
IsAlert = true;
}
}
else if (IsAlert)
{
IsAlert = false;
}
Text = string.Format(
"{0:#,##0.##}{1}",
_val.Round(_round),
Append
);
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private MetricKey _key { get; set; }
public MetricKey Key
{
get
{
return _key;
}
protected set
{
_key = value;
NotifyPropertyChanged("Key");
}
}
private string _fullName { get; set; }
public string FullName
{
get
{
return _fullName;
}
protected set
{
_fullName = value;
NotifyPropertyChanged("FullName");
}
}
private string _label { get; set; }
public string Label
{
get
{
return _label;
}
protected set
{
_label = value;
NotifyPropertyChanged("Label");
}
}
private double _value { get; set; }
public double Value
{
get
{
return _value;
}
protected set
{
_value = value;
NotifyPropertyChanged("Value");
}
}
private string _append { get; set; }
public string Append
{
get
{
return _append;
}
protected set
{
_append = value;
NotifyPropertyChanged("Append");
}
}
private double _nValue { get; set; }
public double nValue
{
get
{
return _nValue;
}
set
{
_nValue = value;
NotifyPropertyChanged("nValue");
}
}
private string _nAppend { get; set; }
public string nAppend
{
get
{
return _nAppend;
}
set
{
_nAppend = value;
NotifyPropertyChanged("nAppend");
}
}
private string _text { get; set; }
public string Text
{
get
{
return _text;
}
protected set
{
_text = value;
NotifyPropertyChanged("Text");
}
}
private bool _isAlert { get; set; }
public bool IsAlert
{
get
{
return _isAlert;
}
protected set
{
_isAlert = value;
NotifyPropertyChanged("IsAlert");
if (value)
{
_alertColorFlag = false;
if (Framework.Settings.Instance.AlertBlink)
{
_alertColorTimer = new DispatcherTimer(DispatcherPriority.Normal, App.Current.Dispatcher);
_alertColorTimer.Interval = TimeSpan.FromSeconds(0.5d);
_alertColorTimer.Tick += new EventHandler(AlertColorTimer_Tick);
_alertColorTimer.Start();
}
}
else if (_alertColorTimer != null)
{
_alertColorTimer.Stop();
_alertColorTimer = null;
}
}
}
public virtual bool IsNumeric
{
get { return true; }
}
public string AlertColor
{
get
{
return _alertColorFlag ? Framework.Settings.Instance.FontColor : Framework.Settings.Instance.AlertFontColor;
}
}
private DispatcherTimer _alertColorTimer;
private void AlertColorTimer_Tick(object sender, EventArgs e)
{
_alertColorFlag = !_alertColorFlag;
NotifyPropertyChanged("AlertColor");
}
private bool _alertColorFlag = false;
protected iConverter _converter { get; set; }
protected bool _round { get; set; }
protected double _alertValue { get; set; }
private bool _disposed { get; set; } = false;
}
public class OHMMetric : BaseMetric
{
public OHMMetric(ISensor sensor, MetricKey key, DataType dataType, string label = null, bool round = false, double alertValue = 0, iConverter converter = null) : base(key, dataType, label, round, alertValue, converter)
{
_sensor = sensor;
}
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_disposed)
{
if (disposing)
{
_sensor = null;
}
_disposed = true;
}
}
~OHMMetric()
{
Dispose(false);
}
public override void Update()
{
if (_sensor.Value.HasValue)
{
Update(_sensor.Value.Value);
}
else
{
Text = "No Value";
}
}
private ISensor _sensor { get; set; }
private bool _disposed { get; set; } = false;
}
public class GPUVRAMMLoadMetric : BaseMetric
{
public GPUVRAMMLoadMetric(ISensor memoryUsedSensor, ISensor memoryTotalSensor, MetricKey key, DataType dataType, string label = null, bool round = false, double alertValue = 0, iConverter converter = null) : base(key, dataType, label, round, alertValue, converter)
{
_memoryUsedSensor = memoryUsedSensor;
_memoryTotalSensor = memoryTotalSensor;
}
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_disposed)
{
if (disposing)
{
_memoryUsedSensor = null;
_memoryTotalSensor = null;
}
_disposed = true;
}
}
~GPUVRAMMLoadMetric()
{
Dispose(false);
}
public override void Update()
{
if (_memoryUsedSensor.Value.HasValue && _memoryTotalSensor.Value.HasValue)
{
float load = _memoryUsedSensor.Value.Value / _memoryTotalSensor.Value.Value * 100f;
Update(load);
}
else
{
Text = "No Value";
}
}
private ISensor _memoryUsedSensor { get; set; }
private ISensor _memoryTotalSensor { get; set; }
private bool _disposed { get; set; } = false;
}
public class IPMetric : BaseMetric
{
public IPMetric(string ipAddress, MetricKey key, DataType dataType, string label = null, bool round = false, double alertValue = 0, iConverter converter = null) : base(key, dataType, label, round, alertValue, converter)
{
Text = ipAddress;
}
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~IPMetric()
{
Dispose(false);
}
public override bool IsNumeric
{
get { return false; }
}
}
public class PCMetric : BaseMetric
{
public PCMetric(PerformanceCounter counter, MetricKey key, DataType dataType, string label = null, bool round = false, double alertValue = 0, iConverter converter = null) : base(key, dataType, label, round, alertValue, converter)
{
_counter = counter;
}
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_disposed)
{
if (disposing)
{
if (_counter != null)
{
_counter.Dispose();
_counter = null;
}
}
_disposed = true;
}
}
~PCMetric()
{
Dispose(false);
}
public override void Update()
{
Update(_counter.NextValue());
}
private PerformanceCounter _counter { get; set; }
private bool _disposed { get; set; } = false;
}
[Serializable]
public enum MonitorType : byte
{
CPU,
RAM,
GPU,
HD,
Network
}
[JsonObject(MemberSerialization.OptIn)]
public class MonitorConfig : INotifyPropertyChanged, ICloneable
{
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MonitorConfig Clone()
{
MonitorConfig _clone = (MonitorConfig)MemberwiseClone();
_clone.Hardware = _clone.Hardware.Select(h => h.Clone()).ToArray();
_clone.Params = _clone.Params.Select(p => p.Clone()).ToArray();
if (_clone.HardwareOC != null)
{
_clone.HardwareOC = new ObservableCollection<HardwareConfig>(_clone.HardwareOC.Select(h => h.Clone()));
}
return _clone;
}
object ICloneable.Clone()
{
return Clone();
}
private MonitorType _type { get; set; }
[JsonProperty]
public MonitorType Type
{
get
{
return _type;
}
set
{
_type = value;
NotifyPropertyChanged("Type");
}
}
private bool _enabled { get; set; }
[JsonProperty]
public bool Enabled
{
get
{
return _enabled;
}
set
{
_enabled = value;
NotifyPropertyChanged("Enabled");
}
}
private byte _order { get; set; }
[JsonProperty]
public byte Order
{
get
{
return _order;
}
set
{
_order = value;
NotifyPropertyChanged("Order");
}
}
private HardwareConfig[] _hardware { get; set; }
[JsonProperty]
public HardwareConfig[] Hardware
{
get
{
return _hardware;
}
set
{
_hardware = value;
NotifyPropertyChanged("Hardware");
}
}
private ObservableCollection<HardwareConfig> _hardwareOC { get; set; }
public ObservableCollection<HardwareConfig> HardwareOC
{
get
{
return _hardwareOC;
}
set
{
_hardwareOC = value;
NotifyPropertyChanged("HardwareOC");
}
}
private MetricConfig[] _metrics { get; set; }
[JsonProperty]
public MetricConfig[] Metrics
{
get
{
return _metrics;
}
set
{
_metrics = value;
NotifyPropertyChanged("Metrics");
}
}
private ConfigParam[] _params { get; set; }
[JsonProperty]
public ConfigParam[] Params
{
get
{
return _params;
}
set
{
_params = value;
NotifyPropertyChanged("Params");
}
}
public string Name
{
get
{
return Type.GetDescription();
}
}
public static MonitorConfig[] CheckConfig(MonitorConfig[] config)
{
MonitorConfig[] _default = Default;
if (config == null)
{
return _default;
}
config = (
from def in _default
join rec in config on def.Type equals rec.Type into merged
from newrec in merged.DefaultIfEmpty(def)
select newrec
).ToArray();
foreach (MonitorConfig _record in config)
{
MonitorConfig _defaultRecord = _default.Single(d => d.Type == _record.Type);
if (_record.Hardware == null)
{
_record.Hardware = _defaultRecord.Hardware;
}
if (_record.Metrics == null)
{
_record.Metrics = _defaultRecord.Metrics;
}
else
{
_record.Metrics = (
from def in _defaultRecord.Metrics
join metric in _record.Metrics on def.Key equals metric.Key into merged
from newmetric in merged.DefaultIfEmpty(def)
select newmetric
).ToArray();
}
if (_record.Params == null)
{
_record.Params = _defaultRecord.Params;
}
else
{
_record.Params = (
from def in _defaultRecord.Params
join param in _record.Params on def.Key equals param.Key into merged
from newparam in merged.DefaultIfEmpty(def)
select newparam
).ToArray();
}
}
return config;
}
public static MonitorConfig[] Default
{
get
{
return new MonitorConfig[5]
{
new MonitorConfig()
{
Type = MonitorType.CPU,
Enabled = true,
Order = 5,
Hardware = new HardwareConfig[0],
Metrics = new MetricConfig[6]
{
new MetricConfig(MetricKey.CPUClock, true),
new MetricConfig(MetricKey.CPUTemp, true),
new MetricConfig(MetricKey.CPUVoltage, true),
new MetricConfig(MetricKey.CPUFan, true),
new MetricConfig(MetricKey.CPULoad, true),
new MetricConfig(MetricKey.CPUCoreLoad, true)
},
Params = new ConfigParam[6]
{
ConfigParam.Defaults.HardwareNames,
ConfigParam.Defaults.RoundAll,
ConfigParam.Defaults.AllCoreClocks,
ConfigParam.Defaults.UseGHz,
ConfigParam.Defaults.UseFahrenheit,
ConfigParam.Defaults.TempAlert
}
},
new MonitorConfig()
{
Type = MonitorType.RAM,
Enabled = true,
Order = 4,
Hardware = new HardwareConfig[0],
Metrics = new MetricConfig[5]
{
new MetricConfig(MetricKey.RAMClock, true),
new MetricConfig(MetricKey.RAMVoltage, true),
new MetricConfig(MetricKey.RAMLoad, true),
new MetricConfig(MetricKey.RAMUsed, true),
new MetricConfig(MetricKey.RAMFree, true)
},
Params = new ConfigParam[2]
{
ConfigParam.Defaults.NoHardwareNames,
ConfigParam.Defaults.RoundAll
}
},
new MonitorConfig()
{
Type = MonitorType.GPU,
Enabled = true,
Order = 3,
Hardware = new HardwareConfig[0],
Metrics = new MetricConfig[7]
{
new MetricConfig(MetricKey.GPUCoreClock, true),
new MetricConfig(MetricKey.GPUVRAMClock, true),
new MetricConfig(MetricKey.GPUCoreLoad, true),
new MetricConfig(MetricKey.GPUVRAMLoad, true),
new MetricConfig(MetricKey.GPUVoltage, true),
new MetricConfig(MetricKey.GPUTemp, true),
new MetricConfig(MetricKey.GPUFan, true)
},
Params = new ConfigParam[5]
{
ConfigParam.Defaults.HardwareNames,
ConfigParam.Defaults.RoundAll,
ConfigParam.Defaults.UseGHz,
ConfigParam.Defaults.UseFahrenheit,
ConfigParam.Defaults.TempAlert
}
},
new MonitorConfig()
{
Type = MonitorType.HD,
Enabled = true,
Order = 2,
Hardware = new HardwareConfig[0],
Metrics = new MetricConfig[6]
{
new MetricConfig(MetricKey.DriveLoadBar, true),
new MetricConfig(MetricKey.DriveLoad, true),
new MetricConfig(MetricKey.DriveUsed, true),
new MetricConfig(MetricKey.DriveFree, true),
new MetricConfig(MetricKey.DriveRead, true),
new MetricConfig(MetricKey.DriveWrite, true)
},
Params = new ConfigParam[2]
{
ConfigParam.Defaults.RoundAll,
ConfigParam.Defaults.UsedSpaceAlert
}
},
new MonitorConfig()
{
Type = MonitorType.Network,
Enabled = true,
Order = 1,
Hardware = new HardwareConfig[0],
Metrics = new MetricConfig[4]
{
new MetricConfig(MetricKey.NetworkIP, true),
new MetricConfig(MetricKey.NetworkExtIP, false),
new MetricConfig(MetricKey.NetworkIn, true),
new MetricConfig(MetricKey.NetworkOut, true)
},
Params = new ConfigParam[5]
{
ConfigParam.Defaults.HardwareNames,
ConfigParam.Defaults.RoundAll,
ConfigParam.Defaults.UseBytes,
ConfigParam.Defaults.BandwidthInAlert,
ConfigParam.Defaults.BandwidthOutAlert
}
}
};
}
}
}
[JsonObject(MemberSerialization.OptIn)]
public class HardwareConfig : INotifyPropertyChanged, ICloneable
{
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public HardwareConfig Clone()
{
return (HardwareConfig)MemberwiseClone();
}
object ICloneable.Clone()
{
return Clone();
}
private string _id { get; set; }
[JsonProperty]
public string ID
{
get
{
return _id;
}
set
{
_id = value;
NotifyPropertyChanged("ID");
}
}
private string _name { get; set; }
[JsonProperty]
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
private string _actualName { get; set; }
[JsonProperty]
public string ActualName
{
get
{
return _actualName;
}
set
{
_actualName = value;
NotifyPropertyChanged("ActualName");
}
}
private bool _enabled { get; set; } = true;
[JsonProperty]
public bool Enabled
{
get
{
return _enabled;
}
set
{
_enabled = value;
NotifyPropertyChanged("Enabled");
}
}
private byte _order { get; set; } = 0;
[JsonProperty]
public byte Order
{
get
{
return _order;
}
set
{
_order = value;
NotifyPropertyChanged("Order");
}
}
}
[JsonObject(MemberSerialization.OptIn)]
public class MetricConfig : INotifyPropertyChanged, ICloneable
{
public MetricConfig() { }
public MetricConfig(MetricKey key, bool enabled)
{
Key = key;
Enabled = enabled;
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ConfigParam Clone()
{
return (ConfigParam)MemberwiseClone();
}
object ICloneable.Clone()
{
return Clone();
}
private MetricKey _key { get; set; }
[JsonProperty]
public MetricKey Key
{
get
{
return _key;
}
set
{
_key = value;
NotifyPropertyChanged("Key");
}
}
private bool _enabled { get; set; }
[JsonProperty]
public bool Enabled
{
get
{
return _enabled;
}
set
{
if (_enabled == value)
{
return;
}
_enabled = value;
NotifyPropertyChanged("Enabled");
}
}
public string Name
{
get
{
return Key.GetFullName();
}
}
}
[Serializable]
public enum MetricKey : byte
{
CPUClock = 0,
CPUTemp = 1,
CPUVoltage = 2,
CPUFan = 3,
CPULoad = 4,
CPUCoreLoad = 5,
RAMClock = 6,
RAMVoltage = 7,
RAMLoad = 8,
RAMUsed = 9,
RAMFree = 10,
GPUCoreClock = 11,
GPUVRAMClock = 12,
GPUCoreLoad = 13,
GPUVRAMLoad = 14,
GPUVoltage = 15,
GPUTemp = 16,
GPUFan = 17,
NetworkIP = 26,
NetworkExtIP = 27,
NetworkIn = 18,
NetworkOut = 19,
DriveLoadBar = 20,
DriveLoad = 21,
DriveUsed = 22,
DriveFree = 23,
DriveRead = 24,
DriveWrite = 25
}
[JsonObject(MemberSerialization.OptIn)]
public class ConfigParam : INotifyPropertyChanged, ICloneable
{
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ConfigParam Clone()
{
return (ConfigParam)MemberwiseClone();
}
object ICloneable.Clone()
{
return Clone();
}
private ParamKey _key { get; set; }
[JsonProperty]
public ParamKey Key
{
get
{
return _key;
}
set
{
_key = value;
NotifyPropertyChanged("Key");
}
}
private object _value { get; set; }
[JsonProperty]
public object Value
{
get
{
return _value;
}
set
{
if (value.GetType() == typeof(long))
{
_value = Convert.ToInt32(value);
}
else
{
_value = value;
}
NotifyPropertyChanged("Value");
}
}
public Type Type
{
get
{
return Value.GetType();
}
}
public string TypeString
{
get
{
return Type.ToString();
}
}
public string Name
{
get
{
switch (Key)
{
case ParamKey.HardwareNames:
return Resources.SettingsShowHardwareNames;
case ParamKey.UseFahrenheit:
return Resources.SettingsUseFahrenheit;
case ParamKey.AllCoreClocks:
return Resources.SettingsAllCoreClocks;
case ParamKey.CoreLoads:
return Resources.SettingsCoreLoads;
case ParamKey.TempAlert:
return Resources.SettingsTemperatureAlert;
case ParamKey.DriveDetails:
return Resources.SettingsShowDriveDetails;
case ParamKey.UsedSpaceAlert:
return Resources.SettingsUsedSpaceAlert;
case ParamKey.BandwidthInAlert:
return Resources.SettingsBandwidthInAlert;
case ParamKey.BandwidthOutAlert:
return Resources.SettingsBandwidthOutAlert;
case ParamKey.UseBytes:
return Resources.SettingsUseBytesPerSecond;
case ParamKey.RoundAll:
return Resources.SettingsRoundAllDecimals;
case ParamKey.DriveSpace:
return Resources.SettingsShowDriveSpace;
case ParamKey.DriveIO:
return Resources.SettingsShowDriveIO;
case ParamKey.UseGHz:
return Resources.SettingsUseGHz;
default:
return "Unknown";
}
}
}
public string Tooltip
{
get
{
switch (Key)
{
case ParamKey.HardwareNames:
return Resources.SettingsShowHardwareNamesTooltip;
case ParamKey.UseFahrenheit:
return Resources.SettingsUseFahrenheitTooltip;
case ParamKey.AllCoreClocks:
return Resources.SettingsAllCoreClocksTooltip;
case ParamKey.CoreLoads:
return Resources.SettingsCoreLoadsTooltip;
case ParamKey.TempAlert:
return Resources.SettingsTemperatureAlertTooltip;
case ParamKey.DriveDetails:
return Resources.SettingsDriveDetailsTooltip;
case ParamKey.UsedSpaceAlert:
return Resources.SettingsUsedSpaceAlertTooltip;
case ParamKey.BandwidthInAlert:
return Resources.SettingsBandwidthInAlertTooltip;
case ParamKey.BandwidthOutAlert:
return Resources.SettingsBandwidthOutAlertTooltip;
case ParamKey.UseBytes:
return Resources.SettingsUseBytesPerSecondTooltip;
case ParamKey.RoundAll:
return Resources.SettingsRoundAllDecimalsTooltip;
case ParamKey.DriveSpace:
return Resources.SettingsShowDriveSpaceTooltip;
case ParamKey.DriveIO:
return Resources.SettingsShowDriveIOTooltip;
case ParamKey.UseGHz:
return Resources.SettingsUseGHzTooltip;
default:
return "Unknown";
}
}
}
public static class Defaults
{
public static ConfigParam HardwareNames
{
get
{
return new ConfigParam() { Key = ParamKey.HardwareNames, Value = true };
}
}
public static ConfigParam NoHardwareNames
{
get
{
return new ConfigParam() { Key = ParamKey.HardwareNames, Value = false };
}
}
public static ConfigParam UseFahrenheit
{
get
{
return new ConfigParam() { Key = ParamKey.UseFahrenheit, Value = false };
}
}
public static ConfigParam AllCoreClocks
{
get
{
return new ConfigParam() { Key = ParamKey.AllCoreClocks, Value = false };
}
}
public static ConfigParam CoreLoads
{
get
{
return new ConfigParam() { Key = ParamKey.CoreLoads, Value = true };
}
}
public static ConfigParam TempAlert
{
get
{
return new ConfigParam() { Key = ParamKey.TempAlert, Value = 0 };
}
}
public static ConfigParam DriveDetails
{
get
{
return new ConfigParam() { Key = ParamKey.DriveDetails, Value = false };
}
}
public static ConfigParam UsedSpaceAlert
{
get
{
return new ConfigParam() { Key = ParamKey.UsedSpaceAlert, Value = 0 };
}
}
public static ConfigParam BandwidthInAlert
{
get
{
return new ConfigParam() { Key = ParamKey.BandwidthInAlert, Value = 0 };
}
}
public static ConfigParam BandwidthOutAlert
{
get
{
return new ConfigParam() { Key = ParamKey.BandwidthOutAlert, Value = 0 };
}
}
public static ConfigParam UseBytes
{
get
{
return new ConfigParam() { Key = ParamKey.UseBytes, Value = false };
}
}
public static ConfigParam RoundAll
{
get
{
return new ConfigParam() { Key = ParamKey.RoundAll, Value = false };
}
}
public static ConfigParam ShowDriveSpace
{
get
{
return new ConfigParam() { Key = ParamKey.DriveSpace, Value = true };
}
}
public static ConfigParam ShowDriveIO
{
get
{
return new ConfigParam() { Key = ParamKey.DriveIO, Value = true };
}
}
public static ConfigParam UseGHz
{
get
{
return new ConfigParam() { Key = ParamKey.UseGHz, Value = false };
}
}
}
}
[Serializable]
public enum ParamKey : byte
{
HardwareNames,
UseFahrenheit,
AllCoreClocks,
CoreLoads,
TempAlert,
DriveDetails,
UsedSpaceAlert,
BandwidthInAlert,
BandwidthOutAlert,
UseBytes,
RoundAll,
DriveSpace,
DriveIO,
UseGHz
}
public enum DataType : byte
{
Dynamic,
Bit,
Kilobit,
Megabit,
Gigabit,
Byte,
Kilobyte,
Megabyte,
Gigabyte,
bps,
kbps,
Mbps,
Gbps,
Bps,
kBps,
MBps,
GBps,
MHz,
GHz,
Voltage,
Percent,
RPM,
Celcius,
Fahrenheit,
IP
}
public interface iConverter
{
void Convert(ref double value);
void Convert(ref double value, out double normalized, out DataType targetType);
DataType TargetType { get; }
bool IsDynamic { get; }
}
public class CelciusToFahrenheit : iConverter
{
private CelciusToFahrenheit() { }
public void Convert(ref double value)
{
value = value * 1.8d + 32d;
}
public void Convert(ref double value, out double normalized, out DataType targetType)
{
Convert(ref value);
normalized = value;
targetType = TargetType;
}
public DataType TargetType
{
get
{
return DataType.Fahrenheit;
}
}
public bool IsDynamic
{
get
{
return false;
}
}
private static CelciusToFahrenheit _instance { get; set; } = null;
public static CelciusToFahrenheit Instance
{
get
{
if (_instance == null)
{
_instance = new CelciusToFahrenheit();
}
return _instance;
}
}
}
public class MHzToGHz : iConverter
{
private MHzToGHz() { }
public void Convert(ref double value)
{
value = value / 1000d;
}
public void Convert(ref double value, out double normalized, out DataType targetType)
{
Convert(ref value);
normalized = value;
targetType = TargetType;
}
public DataType TargetType
{
get
{
return DataType.GHz;
}
}
public bool IsDynamic
{
get
{
return false;
}
}
private static MHzToGHz _instance { get; set; } = null;
public static MHzToGHz Instance
{
get
{
if (_instance == null)
{
_instance = new MHzToGHz();
}
return _instance;
}
}
}
public class BitsPerSecondConverter : iConverter
{
private BitsPerSecondConverter() { }
public void Convert(ref double value)
{
double _normalized;
DataType _dataType;
Convert(ref value, out _normalized, out _dataType);
}
public void Convert(ref double value, out double normalized, out DataType targetType)
{
normalized = value /= 128d;
if (value < 1024d)
{
targetType = DataType.kbps;
return;
}
else if (value < 1048576d)
{
value /= 1024d;
targetType = DataType.Mbps;
return;
}
else
{
value /= 1048576d;
targetType = DataType.Gbps;
return;
}
}
public DataType TargetType
{
get
{
return DataType.kbps;
}
}
public bool IsDynamic
{
get
{
return true;
}
}
private static BitsPerSecondConverter _instance { get; set; } = null;
public static BitsPerSecondConverter Instance
{
get
{
if (_instance == null)
{
_instance = new BitsPerSecondConverter();
}
return _instance;
}
}
}
public class BytesPerSecondConverter : iConverter
{
private BytesPerSecondConverter() { }
public void Convert(ref double value)
{
double _normalized;
DataType _dataType;
Convert(ref value, out _normalized, out _dataType);
}
public void Convert(ref double value, out double normalized, out DataType targetType)
{
normalized = value /= 1024d;
if (value < 1024d)
{
targetType = DataType.kBps;
return;
}
else if (value < 1048576d)
{
value /= 1024d;
targetType = DataType.MBps;
return;
}
else
{
value /= 1048576d;
targetType = DataType.GBps;
return;
}
}
public DataType TargetType
{
get
{
return DataType.kBps;
}
}
public bool IsDynamic
{
get
{
return true;
}
}
private static BytesPerSecondConverter _instance { get; set; } = null;
public static BytesPerSecondConverter Instance
{
get
{
if (_instance == null)
{
_instance = new BytesPerSecondConverter();
}
return _instance;
}
}
}
public static class Extensions
{
public static bool IsEnabled(this MetricConfig[] metrics, MetricKey key)
{
return metrics.Any(m => m.Key == key && m.Enabled);
}
public static HardwareType[] GetHardwareTypes(this MonitorType type)
{
switch (type)
{
case MonitorType.CPU:
return new HardwareType[1] { HardwareType.Cpu };
case MonitorType.RAM:
return new HardwareType[1] { HardwareType.Memory };
case MonitorType.GPU:
return new HardwareType[2] { HardwareType.GpuNvidia, HardwareType.GpuAmd };
default:
throw new ArgumentException("Invalid MonitorType.");
}
}
public static string GetDescription(this MonitorType type)
{
switch (type)
{
case MonitorType.CPU:
return Resources.CPU;
case MonitorType.RAM:
return Resources.RAM;
case MonitorType.GPU:
return Resources.GPU;
case MonitorType.HD:
return Resources.Drives;
case MonitorType.Network:
return Resources.Network;
default:
throw new ArgumentException("Invalid MonitorType.");
}
}
public static T GetValue<T>(this ConfigParam[] parameters, ParamKey key)
{
return (T)parameters.Single(p => p.Key == key).Value;
}
public static string GetFullName(this MetricKey key)
{
switch (key)
{
case MetricKey.CPUClock:
return Resources.CPUClock;
case MetricKey.CPUTemp:
return Resources.CPUTemp;
case MetricKey.CPUVoltage:
return Resources.CPUVoltage;
case MetricKey.CPUFan:
return Resources.CPUFan;
case MetricKey.CPULoad:
return Resources.CPULoad;
case MetricKey.CPUCoreLoad:
return Resources.CPUCoreLoad;
case MetricKey.RAMClock:
return Resources.RAMClock;
case MetricKey.RAMVoltage:
return Resources.RAMVoltage;
case MetricKey.RAMLoad:
return Resources.RAMLoad;
case MetricKey.RAMUsed:
return Resources.RAMUsed;
case MetricKey.RAMFree:
return Resources.RAMFree;
case MetricKey.GPUCoreClock:
return Resources.GPUCoreClock;
case MetricKey.GPUVRAMClock:
return Resources.GPUVRAMClock;
case MetricKey.GPUCoreLoad:
return Resources.GPUCoreLoad;
case MetricKey.GPUVRAMLoad:
return Resources.GPUVRAMLoad;
case MetricKey.GPUVoltage:
return Resources.GPUVoltage;
case MetricKey.GPUTemp:
return Resources.GPUTemp;
case MetricKey.GPUFan:
return Resources.GPUFan;
case MetricKey.NetworkIP:
return Resources.NetworkIP;
case MetricKey.NetworkExtIP:
return Resources.NetworkExtIP;
case MetricKey.NetworkIn:
return Resources.NetworkIn;
case MetricKey.NetworkOut:
return Resources.NetworkOut;
case MetricKey.DriveLoadBar:
return Resources.DriveLoadBar;
case MetricKey.DriveLoad:
return Resources.DriveLoad;
case MetricKey.DriveUsed:
return Resources.DriveUsed;
case MetricKey.DriveFree:
return Resources.DriveFree;
case MetricKey.DriveRead:
return Resources.DriveRead;
case MetricKey.DriveWrite:
return Resources.DriveWrite;
default:
return "Unknown";
}
}
public static string GetLabel(this MetricKey key)
{
switch (key)
{
case MetricKey.CPUClock:
return Resources.CPUClockLabel;
case MetricKey.CPUTemp:
return Resources.CPUTempLabel;
case MetricKey.CPUVoltage:
return Resources.CPUVoltageLabel;
case MetricKey.CPUFan:
return Resources.CPUFanLabel;
case MetricKey.CPULoad:
return Resources.CPULoadLabel;
case MetricKey.CPUCoreLoad:
return Resources.CPUCoreLoadLabel;
case MetricKey.RAMClock:
return Resources.RAMClockLabel;
case MetricKey.RAMVoltage:
return Resources.RAMVoltageLabel;
case MetricKey.RAMLoad:
return Resources.RAMLoadLabel;
case MetricKey.RAMUsed:
return Resources.RAMUsedLabel;
case MetricKey.RAMFree:
return Resources.RAMFreeLabel;
case MetricKey.GPUCoreClock:
return Resources.GPUCoreClockLabel;
case MetricKey.GPUVRAMClock:
return Resources.GPUVRAMClockLabel;
case MetricKey.GPUCoreLoad:
return Resources.GPUCoreLoadLabel;
case MetricKey.GPUVRAMLoad:
return Resources.GPUVRAMLoadLabel;
case MetricKey.GPUVoltage:
return Resources.GPUVoltageLabel;
case MetricKey.GPUTemp:
return Resources.GPUTempLabel;
case MetricKey.GPUFan:
return Resources.GPUFanLabel;
case MetricKey.NetworkIP:
return Resources.NetworkIPLabel;
case MetricKey.NetworkExtIP:
return Resources.NetworkExtIPLabel;
case MetricKey.NetworkIn:
return Resources.NetworkInLabel;
case MetricKey.NetworkOut:
return Resources.NetworkOutLabel;
case MetricKey.DriveLoadBar:
return Resources.DriveLoadBarLabel;
case MetricKey.DriveLoad:
return Resources.DriveLoadLabel;
case MetricKey.DriveUsed:
return Resources.DriveUsedLabel;
case MetricKey.DriveFree:
return Resources.DriveFreeLabel;
case MetricKey.DriveRead:
return Resources.DriveReadLabel;
case MetricKey.DriveWrite:
return Resources.DriveWriteLabel;
default:
return "Unknown";
}
}
public static string GetAppend(this DataType type)
{
switch (type)
{
case DataType.Bit:
return " b";
case DataType.Kilobit:
return " kb";
case DataType.Megabit:
return " mb";
case DataType.Gigabit:
return " gb";
case DataType.Byte:
return " B";
case DataType.Kilobyte:
return " KB";
case DataType.Megabyte:
return " MB";
case DataType.Gigabyte:
return " GB";
case DataType.bps:
return " bps";
case DataType.kbps:
return " kbps";
case DataType.Mbps:
return " Mbps";
case DataType.Gbps:
return " Gbps";
case DataType.Bps:
return " B/s";
case DataType.kBps:
return " kB/s";
case DataType.MBps:
return " MB/s";
case DataType.GBps:
return " GB/s";
case DataType.MHz:
return " MHz";
case DataType.GHz:
return " GHz";
case DataType.Voltage:
return " V";
case DataType.Percent:
return "%";
case DataType.RPM:
return " RPM";
case DataType.Celcius:
return " C";
case DataType.Fahrenheit:
return " F";
case DataType.IP:
return string.Empty;
default:
throw new ArgumentException("Invalid DataType.");
}
}
public static double Round(this double value, bool doRound)
{
if (!doRound)
{
return value;
}
return Math.Round(value);
}
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Monitoring.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 27,239 |
```smalltalk
``` | /content/code_sandbox/SidebarDiagnostics/Properties/Resources.da.Designer.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 1 |
```smalltalk
//your_sha256_hash--------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//your_sha256_hash--------------
namespace SidebarDiagnostics.Framework {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SidebarDiagnostics.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Sidebar Diagnostics.
/// </summary>
public static string AppName {
get {
return ResourceManager.GetString("AppName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Apply.
/// </summary>
public static string ButtonApply {
get {
return ResourceManager.GetString("ButtonApply", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
public static string ButtonCancel {
get {
return ResourceManager.GetString("ButtonCancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Close.
/// </summary>
public static string ButtonClose {
get {
return ResourceManager.GetString("ButtonClose", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Donate.
/// </summary>
public static string ButtonDonate {
get {
return ResourceManager.GetString("ButtonDonate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Done.
/// </summary>
public static string ButtonDone {
get {
return ResourceManager.GetString("ButtonDone", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to GitHub.
/// </summary>
public static string ButtonGitHub {
get {
return ResourceManager.GetString("ButtonGitHub", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Graph.
/// </summary>
public static string ButtonGraph {
get {
return ResourceManager.GetString("ButtonGraph", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hide.
/// </summary>
public static string ButtonHide {
get {
return ResourceManager.GetString("ButtonHide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No.
/// </summary>
public static string ButtonNo {
get {
return ResourceManager.GetString("ButtonNo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reload.
/// </summary>
public static string ButtonReload {
get {
return ResourceManager.GetString("ButtonReload", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save.
/// </summary>
public static string ButtonSave {
get {
return ResourceManager.GetString("ButtonSave", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Settings.
/// </summary>
public static string ButtonSettings {
get {
return ResourceManager.GetString("ButtonSettings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show.
/// </summary>
public static string ButtonShow {
get {
return ResourceManager.GetString("ButtonShow", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skip.
/// </summary>
public static string ButtonSkip {
get {
return ResourceManager.GetString("ButtonSkip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Update.
/// </summary>
public static string ButtonUpdate {
get {
return ResourceManager.GetString("ButtonUpdate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Visibility.
/// </summary>
public static string ButtonVisibility {
get {
return ResourceManager.GetString("ButtonVisibility", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Yes.
/// </summary>
public static string ButtonYes {
get {
return ResourceManager.GetString("ButtonYes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change Log.
/// </summary>
public static string ChangeLogTitle {
get {
return ResourceManager.GetString("ChangeLogTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CPU.
/// </summary>
public static string CPU {
get {
return ResourceManager.GetString("CPU", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clock.
/// </summary>
public static string CPUClock {
get {
return ResourceManager.GetString("CPUClock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clock.
/// </summary>
public static string CPUClockLabel {
get {
return ResourceManager.GetString("CPUClockLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core Clock.
/// </summary>
public static string CPUCoreClock {
get {
return ResourceManager.GetString("CPUCoreClock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core.
/// </summary>
public static string CPUCoreClockLabel {
get {
return ResourceManager.GetString("CPUCoreClockLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core Load.
/// </summary>
public static string CPUCoreLoad {
get {
return ResourceManager.GetString("CPUCoreLoad", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core.
/// </summary>
public static string CPUCoreLoadLabel {
get {
return ResourceManager.GetString("CPUCoreLoadLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fan Usage.
/// </summary>
public static string CPUFan {
get {
return ResourceManager.GetString("CPUFan", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fan.
/// </summary>
public static string CPUFanLabel {
get {
return ResourceManager.GetString("CPUFanLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load.
/// </summary>
public static string CPULoad {
get {
return ResourceManager.GetString("CPULoad", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load.
/// </summary>
public static string CPULoadLabel {
get {
return ResourceManager.GetString("CPULoadLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Temperature.
/// </summary>
public static string CPUTemp {
get {
return ResourceManager.GetString("CPUTemp", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Temp.
/// </summary>
public static string CPUTempLabel {
get {
return ResourceManager.GetString("CPUTempLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Voltage.
/// </summary>
public static string CPUVoltage {
get {
return ResourceManager.GetString("CPUVoltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Voltage.
/// </summary>
public static string CPUVoltageLabel {
get {
return ResourceManager.GetString("CPUVoltageLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Free.
/// </summary>
public static string DriveFree {
get {
return ResourceManager.GetString("DriveFree", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Free.
/// </summary>
public static string DriveFreeLabel {
get {
return ResourceManager.GetString("DriveFreeLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load.
/// </summary>
public static string DriveLoad {
get {
return ResourceManager.GetString("DriveLoad", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load Bar.
/// </summary>
public static string DriveLoadBar {
get {
return ResourceManager.GetString("DriveLoadBar", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load.
/// </summary>
public static string DriveLoadBarLabel {
get {
return ResourceManager.GetString("DriveLoadBarLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load.
/// </summary>
public static string DriveLoadLabel {
get {
return ResourceManager.GetString("DriveLoadLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Read Rate.
/// </summary>
public static string DriveRead {
get {
return ResourceManager.GetString("DriveRead", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Read.
/// </summary>
public static string DriveReadLabel {
get {
return ResourceManager.GetString("DriveReadLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Drives.
/// </summary>
public static string Drives {
get {
return ResourceManager.GetString("Drives", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Used.
/// </summary>
public static string DriveUsed {
get {
return ResourceManager.GetString("DriveUsed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Used.
/// </summary>
public static string DriveUsedLabel {
get {
return ResourceManager.GetString("DriveUsedLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Write Rate.
/// </summary>
public static string DriveWrite {
get {
return ResourceManager.GetString("DriveWrite", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Write.
/// </summary>
public static string DriveWriteLabel {
get {
return ResourceManager.GetString("DriveWriteLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your Performance Counter cache is corrupted. Click OK to visit the wiki and fix this error..
/// </summary>
public static string ErrorPerformanceCounter {
get {
return ResourceManager.GetString("ErrorPerformanceCounter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sidebar Error.
/// </summary>
public static string ErrorTitle {
get {
return ResourceManager.GetString("ErrorTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to GPU.
/// </summary>
public static string GPU {
get {
return ResourceManager.GetString("GPU", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core Clock.
/// </summary>
public static string GPUCoreClock {
get {
return ResourceManager.GetString("GPUCoreClock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core.
/// </summary>
public static string GPUCoreClockLabel {
get {
return ResourceManager.GetString("GPUCoreClockLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core Load.
/// </summary>
public static string GPUCoreLoad {
get {
return ResourceManager.GetString("GPUCoreLoad", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Core.
/// </summary>
public static string GPUCoreLoadLabel {
get {
return ResourceManager.GetString("GPUCoreLoadLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fan Usage.
/// </summary>
public static string GPUFan {
get {
return ResourceManager.GetString("GPUFan", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fan.
/// </summary>
public static string GPUFanLabel {
get {
return ResourceManager.GetString("GPUFanLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Temperature.
/// </summary>
public static string GPUTemp {
get {
return ResourceManager.GetString("GPUTemp", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Temp.
/// </summary>
public static string GPUTempLabel {
get {
return ResourceManager.GetString("GPUTempLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Voltage.
/// </summary>
public static string GPUVoltage {
get {
return ResourceManager.GetString("GPUVoltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Voltage.
/// </summary>
public static string GPUVoltageLabel {
get {
return ResourceManager.GetString("GPUVoltageLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to VRAM Clock.
/// </summary>
public static string GPUVRAMClock {
get {
return ResourceManager.GetString("GPUVRAMClock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to VRAM.
/// </summary>
public static string GPUVRAMClockLabel {
get {
return ResourceManager.GetString("GPUVRAMClockLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to VRAM Load.
/// </summary>
public static string GPUVRAMLoad {
get {
return ResourceManager.GetString("GPUVRAMLoad", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to VRAM.
/// </summary>
public static string GPUVRAMLoadLabel {
get {
return ResourceManager.GetString("GPUVRAMLoadLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Config.
/// </summary>
public static string GraphConfigSectionTitle {
get {
return ResourceManager.GetString("GraphConfigSectionTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duration.
/// </summary>
public static string GraphDuration {
get {
return ResourceManager.GetString("GraphDuration", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minute.
/// </summary>
public static string GraphDurationMinute {
get {
return ResourceManager.GetString("GraphDurationMinute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minutes.
/// </summary>
public static string GraphDurationMinutes {
get {
return ResourceManager.GetString("GraphDurationMinutes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Seconds.
/// </summary>
public static string GraphDurationSeconds {
get {
return ResourceManager.GetString("GraphDurationSeconds", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hardware.
/// </summary>
public static string GraphHardware {
get {
return ResourceManager.GetString("GraphHardware", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Metrics.
/// </summary>
public static string GraphMetrics {
get {
return ResourceManager.GetString("GraphMetrics", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Monitor.
/// </summary>
public static string GraphMonitor {
get {
return ResourceManager.GetString("GraphMonitor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Graph.
/// </summary>
public static string GraphTitle {
get {
return ResourceManager.GetString("GraphTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please restart the app..
/// </summary>
public static string LanguageChangedText {
get {
return ResourceManager.GetString("LanguageChangedText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Language Changed.
/// </summary>
public static string LanguageChangedTitle {
get {
return ResourceManager.GetString("LanguageChangedTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Network.
/// </summary>
public static string Network {
get {
return ResourceManager.GetString("Network", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to External IP Address.
/// </summary>
public static string NetworkExtIP {
get {
return ResourceManager.GetString("NetworkExtIP", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ext.
/// </summary>
public static string NetworkExtIPLabel {
get {
return ResourceManager.GetString("NetworkExtIPLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bandwidth In.
/// </summary>
public static string NetworkIn {
get {
return ResourceManager.GetString("NetworkIn", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to In.
/// </summary>
public static string NetworkInLabel {
get {
return ResourceManager.GetString("NetworkInLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to IP Address.
/// </summary>
public static string NetworkIP {
get {
return ResourceManager.GetString("NetworkIP", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to IP.
/// </summary>
public static string NetworkIPLabel {
get {
return ResourceManager.GetString("NetworkIPLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bandwidth Out.
/// </summary>
public static string NetworkOut {
get {
return ResourceManager.GetString("NetworkOut", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Out.
/// </summary>
public static string NetworkOutLabel {
get {
return ResourceManager.GetString("NetworkOutLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to RAM.
/// </summary>
public static string RAM {
get {
return ResourceManager.GetString("RAM", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clock.
/// </summary>
public static string RAMClock {
get {
return ResourceManager.GetString("RAMClock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clock.
/// </summary>
public static string RAMClockLabel {
get {
return ResourceManager.GetString("RAMClockLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Free.
/// </summary>
public static string RAMFree {
get {
return ResourceManager.GetString("RAMFree", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Free.
/// </summary>
public static string RAMFreeLabel {
get {
return ResourceManager.GetString("RAMFreeLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load.
/// </summary>
public static string RAMLoad {
get {
return ResourceManager.GetString("RAMLoad", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Load.
/// </summary>
public static string RAMLoadLabel {
get {
return ResourceManager.GetString("RAMLoadLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Used.
/// </summary>
public static string RAMUsed {
get {
return ResourceManager.GetString("RAMUsed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Used.
/// </summary>
public static string RAMUsedLabel {
get {
return ResourceManager.GetString("RAMUsedLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Voltage.
/// </summary>
public static string RAMVoltage {
get {
return ResourceManager.GetString("RAMVoltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Voltage.
/// </summary>
public static string RAMVoltageLabel {
get {
return ResourceManager.GetString("RAMVoltageLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 24 Hour Clock.
/// </summary>
public static string Settings24HourClock {
get {
return ResourceManager.GetString("Settings24HourClock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changes the clock's time format to 24 hours..
/// </summary>
public static string Settings24HourClockTooltip {
get {
return ResourceManager.GetString("Settings24HourClockTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Advanced.
/// </summary>
public static string SettingsAdvancedTab {
get {
return ResourceManager.GetString("SettingsAdvancedTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alert Blink.
/// </summary>
public static string SettingsAlertBlink {
get {
return ResourceManager.GetString("SettingsAlertBlink", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Makes the alert text blink..
/// </summary>
public static string SettingsAlertBlinkTooltip {
get {
return ResourceManager.GetString("SettingsAlertBlinkTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alert Font Color.
/// </summary>
public static string SettingsAlertFontColor {
get {
return ResourceManager.GetString("SettingsAlertFontColor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Color of alert text..
/// </summary>
public static string SettingsAlertFontColorTooltip {
get {
return ResourceManager.GetString("SettingsAlertFontColorTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show All Core Clocks.
/// </summary>
public static string SettingsAllCoreClocks {
get {
return ResourceManager.GetString("SettingsAllCoreClocks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows the clock speeds of all cores not just the first..
/// </summary>
public static string SettingsAllCoreClocksTooltip {
get {
return ResourceManager.GetString("SettingsAllCoreClocksTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Always On Top.
/// </summary>
public static string SettingsAlwaysOnTop {
get {
return ResourceManager.GetString("SettingsAlwaysOnTop", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Makes the sidebar always on top of other windows..
/// </summary>
public static string SettingsAlwaysOnTopTooltip {
get {
return ResourceManager.GetString("SettingsAlwaysOnTopTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Auto Background Color.
/// </summary>
public static string SettingsAutoBackground {
get {
return ResourceManager.GetString("SettingsAutoBackground", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sets the background color to your Windows color settings..
/// </summary>
public static string SettingsAutoBackgroundTooltip {
get {
return ResourceManager.GetString("SettingsAutoBackgroundTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Auto Update.
/// </summary>
public static string SettingsAutoUpdate {
get {
return ResourceManager.GetString("SettingsAutoUpdate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updates the app automatically..
/// </summary>
public static string SettingsAutoUpdateTooltip {
get {
return ResourceManager.GetString("SettingsAutoUpdateTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Background Color.
/// </summary>
public static string SettingsBackgroundColor {
get {
return ResourceManager.GetString("SettingsBackgroundColor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Color of the background..
/// </summary>
public static string SettingsBackgroundColorTooltip {
get {
return ResourceManager.GetString("SettingsBackgroundColorTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Background Opacity.
/// </summary>
public static string SettingsBackgroundOpacity {
get {
return ResourceManager.GetString("SettingsBackgroundOpacity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opacity of the background..
/// </summary>
public static string SettingsBackgroundOpacityTooltip {
get {
return ResourceManager.GetString("SettingsBackgroundOpacityTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bandwidth In Alert.
/// </summary>
public static string SettingsBandwidthInAlert {
get {
return ResourceManager.GetString("SettingsBandwidthInAlert", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The kbps or kBps threshold at which bandwidth received alerts occur. Use 0 to disable..
/// </summary>
public static string SettingsBandwidthInAlertTooltip {
get {
return ResourceManager.GetString("SettingsBandwidthInAlertTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bandwidth Out Alert.
/// </summary>
public static string SettingsBandwidthOutAlert {
get {
return ResourceManager.GetString("SettingsBandwidthOutAlert", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The kbps or kBps threshold at which bandwidth sent alerts occur. Use 0 to disable..
/// </summary>
public static string SettingsBandwidthOutAlertTooltip {
get {
return ResourceManager.GetString("SettingsBandwidthOutAlertTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click Through.
/// </summary>
public static string SettingsClickThrough {
get {
return ResourceManager.GetString("SettingsClickThrough", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Makes mouse events pass through the window. Note this will prevent any interaction with the sidebar..
/// </summary>
public static string SettingsClickThroughTooltip {
get {
return ResourceManager.GetString("SettingsClickThroughTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collapse Menu Bar.
/// </summary>
public static string SettingsCollapseMenuBar {
get {
return ResourceManager.GetString("SettingsCollapseMenuBar", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removes the extra space at the top of the sidebar..
/// </summary>
public static string SettingsCollapseMenuBarTooltip {
get {
return ResourceManager.GetString("SettingsCollapseMenuBarTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Core Loads.
/// </summary>
public static string SettingsCoreLoads {
get {
return ResourceManager.GetString("SettingsCoreLoads", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows the percentage load of all cores..
/// </summary>
public static string SettingsCoreLoadsTooltip {
get {
return ResourceManager.GetString("SettingsCoreLoadsTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Customize.
/// </summary>
public static string SettingsCustomizeTab {
get {
return ResourceManager.GetString("SettingsCustomizeTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Date Format.
/// </summary>
public static string SettingsDateFormat {
get {
return ResourceManager.GetString("SettingsDateFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Disabled.
/// </summary>
public static string SettingsDateFormatDisabled {
get {
return ResourceManager.GetString("SettingsDateFormatDisabled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Format of the date below the clock..
/// </summary>
public static string SettingsDateFormatTooltip {
get {
return ResourceManager.GetString("SettingsDateFormatTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dock.
/// </summary>
public static string SettingsDock {
get {
return ResourceManager.GetString("SettingsDock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bottom.
/// </summary>
public static string SettingsDockBottom {
get {
return ResourceManager.GetString("SettingsDockBottom", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Left.
/// </summary>
public static string SettingsDockLeft {
get {
return ResourceManager.GetString("SettingsDockLeft", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Right.
/// </summary>
public static string SettingsDockRight {
get {
return ResourceManager.GetString("SettingsDockRight", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Which edge the sidebar will dock to..
/// </summary>
public static string SettingsDockTooltip {
get {
return ResourceManager.GetString("SettingsDockTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Top.
/// </summary>
public static string SettingsDockTop {
get {
return ResourceManager.GetString("SettingsDockTop", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows extra drive details as text..
/// </summary>
public static string SettingsDriveDetailsTooltip {
get {
return ResourceManager.GetString("SettingsDriveDetailsTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Font Color.
/// </summary>
public static string SettingsFontColor {
get {
return ResourceManager.GetString("SettingsFontColor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Color of text and icons..
/// </summary>
public static string SettingsFontColorTooltip {
get {
return ResourceManager.GetString("SettingsFontColorTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Font Size.
/// </summary>
public static string SettingsFontSize {
get {
return ResourceManager.GetString("SettingsFontSize", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Size of text and icons..
/// </summary>
public static string SettingsFontSizeTooltip {
get {
return ResourceManager.GetString("SettingsFontSizeTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to General.
/// </summary>
public static string SettingsGeneralTab {
get {
return ResourceManager.GetString("SettingsGeneralTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enabled.
/// </summary>
public static string SettingsHardwareColumn1 {
get {
return ResourceManager.GetString("SettingsHardwareColumn1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hardware.
/// </summary>
public static string SettingsHardwareColumn2 {
get {
return ResourceManager.GetString("SettingsHardwareColumn2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enables this hardware..
/// </summary>
public static string SettingsHardwareEnabledTooltip {
get {
return ResourceManager.GetString("SettingsHardwareEnabledTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit the name of this hardware..
/// </summary>
public static string SettingsHardwareNameTooltip {
get {
return ResourceManager.GetString("SettingsHardwareNameTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Horizontal Offset.
/// </summary>
public static string SettingsHorizontalOffset {
get {
return ResourceManager.GetString("SettingsHorizontalOffset", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Horizontal offset of the sidebar..
/// </summary>
public static string SettingsHorizontalOffsetTooltip {
get {
return ResourceManager.GetString("SettingsHorizontalOffsetTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Close.
/// </summary>
public static string SettingsHotkeyClose {
get {
return ResourceManager.GetString("SettingsHotkeyClose", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Switch Edge.
/// </summary>
public static string SettingsHotkeyCycleEdge {
get {
return ResourceManager.GetString("SettingsHotkeyCycleEdge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Switch Screen.
/// </summary>
public static string SettingsHotkeyCycleScreen {
get {
return ResourceManager.GetString("SettingsHotkeyCycleScreen", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hide.
/// </summary>
public static string SettingsHotkeyHide {
get {
return ResourceManager.GetString("SettingsHotkeyHide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reload.
/// </summary>
public static string SettingsHotkeyReload {
get {
return ResourceManager.GetString("SettingsHotkeyReload", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reserve Space.
/// </summary>
public static string SettingsHotkeyReserveSpace {
get {
return ResourceManager.GetString("SettingsHotkeyReserveSpace", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show.
/// </summary>
public static string SettingsHotkeyShow {
get {
return ResourceManager.GetString("SettingsHotkeyShow", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hotkeys.
/// </summary>
public static string SettingsHotkeysTab {
get {
return ResourceManager.GetString("SettingsHotkeysTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Toggle.
/// </summary>
public static string SettingsHotkeyToggle {
get {
return ResourceManager.GetString("SettingsHotkeyToggle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hide at Startup.
/// </summary>
public static string SettingsInitiallyHidden {
get {
return ResourceManager.GetString("SettingsInitiallyHidden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Makes the sidebar hide at startup..
/// </summary>
public static string SettingsInitiallyHiddenTooltip {
get {
return ResourceManager.GetString("SettingsInitiallyHiddenTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Language.
/// </summary>
public static string SettingsLanguage {
get {
return ResourceManager.GetString("SettingsLanguage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default.
/// </summary>
public static string SettingsLanguageDefault {
get {
return ResourceManager.GetString("SettingsLanguageDefault", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Current language of the app..
/// </summary>
public static string SettingsLanguageTooltip {
get {
return ResourceManager.GetString("SettingsLanguageTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Metrics:.
/// </summary>
public static string SettingsMetrics {
get {
return ResourceManager.GetString("SettingsMetrics", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enable or disable specific metrics..
/// </summary>
public static string SettingsMetricsTooltip {
get {
return ResourceManager.GetString("SettingsMetricsTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enables this monitor..
/// </summary>
public static string SettingsMonitorEnabledTooltip {
get {
return ResourceManager.GetString("SettingsMonitorEnabledTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enabled.
/// </summary>
public static string SettingsMonitorsColumn1 {
get {
return ResourceManager.GetString("SettingsMonitorsColumn1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Monitor.
/// </summary>
public static string SettingsMonitorsColumn2 {
get {
return ResourceManager.GetString("SettingsMonitorsColumn2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click a row to edit its settings..
/// </summary>
public static string SettingsMonitorsSubtitle1 {
get {
return ResourceManager.GetString("SettingsMonitorsSubtitle1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Drag a row to change its order..
/// </summary>
public static string SettingsMonitorsSubtitle2 {
get {
return ResourceManager.GetString("SettingsMonitorsSubtitle2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Monitors.
/// </summary>
public static string SettingsMonitorsTab {
get {
return ResourceManager.GetString("SettingsMonitorsTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Polling Interval.
/// </summary>
public static string SettingsPollingInterval {
get {
return ResourceManager.GetString("SettingsPollingInterval", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time between polling for data in milliseconds..
/// </summary>
public static string SettingsPollingIntervalTooltip {
get {
return ResourceManager.GetString("SettingsPollingIntervalTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reserve Space.
/// </summary>
public static string SettingsReserveSpace {
get {
return ResourceManager.GetString("SettingsReserveSpace", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reserves space in the work area for the sidebar..
/// </summary>
public static string SettingsReserveSpaceTooltip {
get {
return ResourceManager.GetString("SettingsReserveSpaceTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Round All Decimals.
/// </summary>
public static string SettingsRoundAllDecimals {
get {
return ResourceManager.GetString("SettingsRoundAllDecimals", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Round all decimal values to the nearest integer..
/// </summary>
public static string SettingsRoundAllDecimalsTooltip {
get {
return ResourceManager.GetString("SettingsRoundAllDecimalsTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Run at Startup.
/// </summary>
public static string SettingsRunAtStartup {
get {
return ResourceManager.GetString("SettingsRunAtStartup", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Runs the app when you first log in..
/// </summary>
public static string SettingsRunAtStartupTooltip {
get {
return ResourceManager.GetString("SettingsRunAtStartupTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Screen.
/// </summary>
public static string SettingsScreen {
get {
return ResourceManager.GetString("SettingsScreen", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Which screen the sidebar will be on..
/// </summary>
public static string SettingsScreenTooltip {
get {
return ResourceManager.GetString("SettingsScreenTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Clock.
/// </summary>
public static string SettingsShowClock {
get {
return ResourceManager.GetString("SettingsShowClock", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows the clock..
/// </summary>
public static string SettingsShowClockTooltip {
get {
return ResourceManager.GetString("SettingsShowClockTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Drive Details.
/// </summary>
public static string SettingsShowDriveDetails {
get {
return ResourceManager.GetString("SettingsShowDriveDetails", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Drive IO.
/// </summary>
public static string SettingsShowDriveIO {
get {
return ResourceManager.GetString("SettingsShowDriveIO", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows drive read and write speeds if drive details is enabled..
/// </summary>
public static string SettingsShowDriveIOTooltip {
get {
return ResourceManager.GetString("SettingsShowDriveIOTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Drive Space.
/// </summary>
public static string SettingsShowDriveSpace {
get {
return ResourceManager.GetString("SettingsShowDriveSpace", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows load percent, used space, and free space if drive details is enabled..
/// </summary>
public static string SettingsShowDriveSpaceTooltip {
get {
return ResourceManager.GetString("SettingsShowDriveSpaceTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Hardware Names.
/// </summary>
public static string SettingsShowHardwareNames {
get {
return ResourceManager.GetString("SettingsShowHardwareNames", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows hardware names..
/// </summary>
public static string SettingsShowHardwareNamesTooltip {
get {
return ResourceManager.GetString("SettingsShowHardwareNamesTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show PC Name.
/// </summary>
public static string SettingsShowMachineName {
get {
return ResourceManager.GetString("SettingsShowMachineName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows the name of the computer..
/// </summary>
public static string SettingsShowMachineNameTooltip {
get {
return ResourceManager.GetString("SettingsShowMachineNameTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Tray Icon.
/// </summary>
public static string SettingsShowTrayIcon {
get {
return ResourceManager.GetString("SettingsShowTrayIcon", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows the tray icon in the taskbar. This is sometimes required..
/// </summary>
public static string SettingsShowTrayIconTooltip {
get {
return ResourceManager.GetString("SettingsShowTrayIconTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sidebar Width.
/// </summary>
public static string SettingsSidebarWidth {
get {
return ResourceManager.GetString("SettingsSidebarWidth", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Width of the sidebar in pixels..
/// </summary>
public static string SettingsSidebarWidthTooltip {
get {
return ResourceManager.GetString("SettingsSidebarWidthTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Temperature Alert.
/// </summary>
public static string SettingsTemperatureAlert {
get {
return ResourceManager.GetString("SettingsTemperatureAlert", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The temperature threshold at which alerts occur. Use 0 to disable..
/// </summary>
public static string SettingsTemperatureAlertTooltip {
get {
return ResourceManager.GetString("SettingsTemperatureAlertTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Text Align.
/// </summary>
public static string SettingsTextAlign {
get {
return ResourceManager.GetString("SettingsTextAlign", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Left.
/// </summary>
public static string SettingsTextAlignLeft {
get {
return ResourceManager.GetString("SettingsTextAlignLeft", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Right.
/// </summary>
public static string SettingsTextAlignRight {
get {
return ResourceManager.GetString("SettingsTextAlignRight", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alignment of metric text..
/// </summary>
public static string SettingsTextAlignTooltip {
get {
return ResourceManager.GetString("SettingsTextAlignTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sidebar Settings.
/// </summary>
public static string SettingsTitle {
get {
return ResourceManager.GetString("SettingsTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Toolbar Mode.
/// </summary>
public static string SettingsToolbarMode {
get {
return ResourceManager.GetString("SettingsToolbarMode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hides the sidebar in alt-tab and makes it persist between virtual desktops..
/// </summary>
public static string SettingsToolbarModeTooltip {
get {
return ResourceManager.GetString("SettingsToolbarModeTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to UI Scale.
/// </summary>
public static string SettingsUIScale {
get {
return ResourceManager.GetString("SettingsUIScale", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scale of all windows and UI components..
/// </summary>
public static string SettingsUIScaleTooltip {
get {
return ResourceManager.GetString("SettingsUIScaleTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use Bytes Per Second.
/// </summary>
public static string SettingsUseBytesPerSecond {
get {
return ResourceManager.GetString("SettingsUseBytesPerSecond", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows bandwidth in bytes instead of bits per second..
/// </summary>
public static string SettingsUseBytesPerSecondTooltip {
get {
return ResourceManager.GetString("SettingsUseBytesPerSecondTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Used Space Alert.
/// </summary>
public static string SettingsUsedSpaceAlert {
get {
return ResourceManager.GetString("SettingsUsedSpaceAlert", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The percentage threshold at which used space alerts occur. Use 0 to disable..
/// </summary>
public static string SettingsUsedSpaceAlertTooltip {
get {
return ResourceManager.GetString("SettingsUsedSpaceAlertTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use Fahrenheit.
/// </summary>
public static string SettingsUseFahrenheit {
get {
return ResourceManager.GetString("SettingsUseFahrenheit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Temperatures for sensors and alerts will be in Fahrenheit instead of Celsius..
/// </summary>
public static string SettingsUseFahrenheitTooltip {
get {
return ResourceManager.GetString("SettingsUseFahrenheitTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use GHz.
/// </summary>
public static string SettingsUseGHz {
get {
return ResourceManager.GetString("SettingsUseGHz", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clock speeds will be in GHz instead of MHz..
/// </summary>
public static string SettingsUseGHzTooltip {
get {
return ResourceManager.GetString("SettingsUseGHzTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Vertical Offset.
/// </summary>
public static string SettingsVerticalOffset {
get {
return ResourceManager.GetString("SettingsVerticalOffset", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Vertical offset of the sidebar..
/// </summary>
public static string SettingsVerticalOffsetTooltip {
get {
return ResourceManager.GetString("SettingsVerticalOffsetTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Virtual Desktop.
/// </summary>
public static string SettingsVirtualDesktop {
get {
return ResourceManager.GetString("SettingsVirtualDesktop", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enables support for virtual desktops..
/// </summary>
public static string SettingsVirtualDesktopTooltip {
get {
return ResourceManager.GetString("SettingsVirtualDesktopTooltip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use the sliders and textboxes to move the sidebar to the correct position..
/// </summary>
public static string SetupCustomSubtitle {
get {
return ResourceManager.GetString("SetupCustomSubtitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom.
/// </summary>
public static string SetupCustomTitle {
get {
return ResourceManager.GetString("SetupCustomTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to If you want to customize the sidebar click the settings button..
/// </summary>
public static string SetupDoneSubtitle {
get {
return ResourceManager.GetString("SetupDoneSubtitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You can also access the settings via the gear icon at the top-right of the sidebar or via the tray icon in the taskbar..
/// </summary>
public static string SetupDoneText {
get {
return ResourceManager.GetString("SetupDoneText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Done!.
/// </summary>
public static string SetupDoneTitle {
get {
return ResourceManager.GetString("SetupDoneTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This is a quick setup to get the sidebar in the correct position..
/// </summary>
public static string SetupSubtitle {
get {
return ResourceManager.GetString("SetupSubtitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Is the sidebar visible and docked to the right edge of your primary monitor?.
/// </summary>
public static string SetupText {
get {
return ResourceManager.GetString("SetupText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Initial Setup.
/// </summary>
public static string SetupTitle {
get {
return ResourceManager.GetString("SetupTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sidebar.
/// </summary>
public static string Sidebar {
get {
return ResourceManager.GetString("Sidebar", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time.
/// </summary>
public static string Time {
get {
return ResourceManager.GetString("Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A fatal error occurred while trying to update. Auto update is now disabled..
/// </summary>
public static string UpdateErrorFatalText {
get {
return ResourceManager.GetString("UpdateErrorFatalText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to update. Check your internet connection..
/// </summary>
public static string UpdateErrorText {
get {
return ResourceManager.GetString("UpdateErrorText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Update Error.
/// </summary>
public static string UpdateErrorTitle {
get {
return ResourceManager.GetString("UpdateErrorTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have the latest version..
/// </summary>
public static string UpdateSuccessText {
get {
return ResourceManager.GetString("UpdateSuccessText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating.
/// </summary>
public static string UpdateTitle {
get {
return ResourceManager.GetString("UpdateTitle", resourceCulture);
}
}
}
}
``` | /content/code_sandbox/SidebarDiagnostics/Properties/Resources.Designer.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 12,774 |
```smalltalk
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sidebar Diagnostics")]
[assembly: AssemblyDescription("Sidebar Diagnostics")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sidebar Diagnostics")]
[assembly: AssemblyProduct("Sidebar Diagnostics")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.6.3.0")]
[assembly: AssemblyFileVersion("3.6.3.0")]
``` | /content/code_sandbox/SidebarDiagnostics/Properties/AssemblyInfo.cs | smalltalk | 2016-01-20T07:41:58 | 2024-08-16T15:40:57 | SidebarDiagnostics | ArcadeRenegade/SidebarDiagnostics | 2,273 | 456 |
```javascript
module.exports = {
'env': {
'browser': true,
'commonjs': true,
'es6': true,
'jquery': true,
'node': true
},
'extends': [
'eslint:recommended'
],
'globals': {
'angular': 'readonly',
'sails': 'readonly',
'Asset': 'readonly',
'Channel': 'readonly',
'Flavor': 'readonly',
'Version': 'readonly',
'AssetService': 'readonly',
'AuthService': 'readonly',
'AuthToken': 'readonly',
'ChannelService': 'readonly',
'FlavorService': 'readonly',
'PlatformService': 'readonly',
'UtilityService': 'readonly',
'VersionService': 'readonly',
'WindowsReleaseService': 'readonly'
}
};
``` | /content/code_sandbox/.eslintrc.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 181 |
```javascript
/**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`
* => `heroku scale`
*
*
* The same command-line arguments are supported, e.g.:
* `node app.js --silent --port=80 --prod`
*/
// Ensure we're in the project directory, so relative paths work as expected
// no matter where we actually lift from.
process.chdir(__dirname);
// Ensure a "sails" can be located:
(function() {
var sails;
try {
sails = require('sails');
} catch (e) {
console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.');
console.error('To do that, run `npm install sails`');
console.error('');
console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.');
console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,');
console.error('but if it doesn\'t, the app will run with the global sails instead!');
return;
}
// Try to get `rc` dependency
var rc;
try {
rc = require('rc');
} catch (e0) {
try {
rc = require('sails/node_modules/rc');
} catch (e1) {
console.error('Could not find dependency: `rc`.');
console.error('Your `.sailsrc` file(s) will be ignored.');
console.error('To resolve this, run:');
console.error('npm install rc --save');
rc = function () { return {}; };
}
}
// Start server
sails.lift(rc('sails'));
})();
``` | /content/code_sandbox/app.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 475 |
```javascript
/**
* Gruntfile
*
* This Node script is executed when you run `grunt` or `sails lift`.
* It's purpose is to load the Grunt tasks in your project's `tasks`
* folder, and allow you to add and remove tasks as you see fit.
* For more information on how this works, check out the `README.md`
* file that was generated in your `tasks` folder.
*
* WARNING:
* Unless you know what you're doing, you shouldn't change this file.
* Check out the `tasks` directory instead.
*/
module.exports = function(grunt) {
var loadGruntTasks = require('sails-hook-grunt/accessible/load-grunt-tasks');
// Load Grunt task configurations (from `tasks/config/`) and Grunt
// task registrations (from `tasks/register/`).
loadGruntTasks(__dirname, grunt);
};
``` | /content/code_sandbox/Gruntfile.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 190 |
```yaml
version: '2'
services:
web:
build: .
environment:
WEBSITE_TITLE: 'Test Title'
WEBSITE_HOME_CONTENT: 'Test Content'
WEBSITE_NAV_LOGO: ''
WEBSITE_APP_TITLE: 'Test App Title'
APP_USERNAME: username
APP_PASSWORD: password
DB_HOST: db
DB_PORT: 5432
DB_USERNAME: releaseserver
DB_NAME: releaseserver
DB_PASSWORD: secret
# DEKs should be 32 bytes long, and cryptographically random.
# You can generate such a key by running the following:
# require('crypto').randomBytes(32).toString('base64')
# PLEASE ENSURE THAT YOU CHANGE THIS VALUE IN PRODUCTION
DATA_ENCRYPTION_KEY: oIh0YgyxQbShuMjw4/laYcZnGKzvC3UniWFsqL0t4Zs=
# Recommended: 63 random alpha-numeric characters
# Generate using: path_to_url
TOKEN_SECRET: change_me_in_production
APP_URL: 'localhost:8080'
ASSETS_PATH: '/usr/src/electron-release-server/releases'
depends_on:
- db
ports:
- '8080:80'
entrypoint: ./scripts/wait.sh db:5432 -- npm start
volumes:
- ./releases:/usr/src/electron-release-server/releases
db:
image: postgres:11
environment:
POSTGRES_PASSWORD: secret
POSTGRES_USER: releaseserver
volumes:
- postgres:/var/lib/postgresql/data
volumes:
postgres:
``` | /content/code_sandbox/docker-compose.yml | yaml | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 360 |
```javascript
/**
* Docker environment settings
*/
module.exports = {
models: {
datastore: 'postgresql',
migrate: 'alter',
dataEncryptionKeys: {
// DEKs should be 32 bytes long, and cryptographically random.
// You can generate such a key by running the following:
// require('crypto').randomBytes(32).toString('base64')
default: process.env['DATA_ENCRYPTION_KEY'],
}
},
port: 80,
log: {
level: process.env['LOG_LEVEL']
},
auth: {
static: {
username: process.env['APP_USERNAME'],
password: process.env['APP_PASSWORD']
}
},
appUrl: process.env['APP_URL'],
datastores: {
postgresql: {
adapter: 'sails-postgresql',
host: process.env['DB_HOST'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[1].split(':')[0],
port: process.env['DB_PORT'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[1].split(':')[1].split('/')[0],
user: process.env['DB_USERNAME'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[0].split(':')[1].split('/')[2],
password: process.env['DB_PASSWORD'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[0].split(':')[2],
database: process.env['DB_NAME'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('/')[3]
}
},
jwt: {
// Recommended: 63 random alpha-numeric characters
// Generate using: path_to_url
token_secret: process.env['TOKEN_SECRET'],
},
files: {
dirname: process.env['ASSETS_PATH'] || '/tmp/',
},
session: {
// Recommended: 63 random alpha-numeric characters
// Generate using: path_to_url
secret: process.env['TOKEN_SECRET'],
database: process.env['DB_NAME'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('/')[3],
host: process.env['DB_HOST'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[1].split(':')[0],
user: process.env['DB_USERNAME'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[0].split(':')[1].split('/')[2],
password: process.env['DB_PASSWORD'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[0].split(':')[2],
port: process.env['DB_PORT'] || process.env['DATABASE_URL'] && process.env['DATABASE_URL'].split('@')[1].split(':')[1].split('/')[0]
}
};
``` | /content/code_sandbox/config/docker.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 601 |
```javascript
/**
* Session Configuration
* (sails.config.session)
*
* Sails session integration leans heavily on the great work already done by
* Express, but also unifies Socket.io with the Connect session store. It uses
* Connect's cookie parser to normalize configuration differences between Express
* and Socket.io and hooks into Sails' middleware interpreter to allow you to access
* and auto-save to `req.session` with Socket.io the same way you would with Express.
*
* For more information on configuring the session, check out:
* path_to_url#!/documentation/reference/sails.config/sails.config.session.html
*/
module.exports.session = {
// XXX: Enable this if you are using postgres as your database
// If so, be sure to run the sql command detailed here: path_to_url
// // uncomment if you use v2land-sails-pg-session
// postgresql: {
// adapter: 'v2land-sails-pg-session',
// host: 'localhost',
// user: 'electron_release_server_user',
// password: 'MySecurePassword',
// database: 'electron_release_server'
// }
// // uncomment if you use sails-pg-session
// postgresql: {
// adapter: 'sails-pg-session',
// host: 'localhost',
// user: 'electron_release_server_user',
// password: 'MySecurePassword',
// database: 'electron_release_server'
// }
};
``` | /content/code_sandbox/config/session.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 308 |
```javascript
/**
* Internationalization / Localization Settings
* (sails.config.i18n)
*
* If your app will touch people from all over the world, i18n (or internationalization)
* may be an important part of your international strategy.
*
*
* For more informationom i18n in Sails, check out:
* path_to_url#!/documentation/concepts/Internationalization
*
* For a complete list of i18n options, see:
* path_to_url#list-of-configuration-options
*
*
*/
module.exports.i18n = {
/***************************************************************************
* *
* Which locales are supported? *
* *
***************************************************************************/
// locales: ['en', 'es', 'fr', 'de'],
/****************************************************************************
* *
* What is the default locale for the site? Note that this setting will be *
* overridden for any request that sends an "Accept-Language" header (i.e. *
* most browsers), but it's still useful if you need to localize the *
* response for requests made by non-browser clients (e.g. cURL). *
* *
****************************************************************************/
// defaultLocale: 'en',
/****************************************************************************
* *
* Automatically add new keys to locale (translation) files when they are *
* encountered during a request? *
* *
****************************************************************************/
// updateFiles: false,
/****************************************************************************
* *
* Path (relative to app root) of directory to store locale (translation) *
* files in. *
* *
****************************************************************************/
// localesDirectory: '/config/locales'
};
``` | /content/code_sandbox/config/i18n.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 353 |
```javascript
/**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* path_to_url#!/documentation/concepts/ORM
*/
module.exports.models = {
// Your app's default datastore. i.e. the name of one of your app's datastores (see `config/datastores.js`)
// The former `connection` model setting is now `datastore`. This sets the datastore
// that models will use, unless overridden directly in the model file in `api/models`.
datastore: 'postgresql',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See path_to_url#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
migrate: 'alter',
schema: true,
// These settings make the .update(), .create() and .createEach()
// work like they did in 0.12, by returning records in the callback.
// This is pretty ineffecient, so if you don't _always_ need this feature, you
// should turn these off and instead chain `.meta({fetch: true})` onto the
// individual calls where you _do_ need records returned.
fetchRecordsOnUpdate: true,
fetchRecordsOnCreate: true,
fetchRecordsOnCreateEach: true,
// Fetching records on destroy was experimental, but if you were using it,
// uncomment the next line.
// fetchRecordsOnDestroy: true,
// Because you can't have the old `connection` setting at the same time as the new
// `datastore` setting, we'll set it to `null` here. When you merge this file into your
// existing `config/models.js` file, just remove any reference to `connection`.
connection: null,
// These attributes will be added to all of your models. When you create a new Sails 1.0
// app with "sails new", a similar configuration will be generated for you.
attributes: {
// In Sails 1.0, the `autoCreatedAt` and `autoUpdatedAt` model settings
// have been removed. Instead, you choose which attributes (if any) to use as
// timestamps. By default, "sails new" will generate these two attributes as numbers,
// giving you the most flexibility. But for compatibility with your existing project,
// we'll define them as strings.
createdAt: { type: 'string', autoCreatedAt: true, },
updatedAt: { type: 'string', autoUpdatedAt: true, },
},
};
``` | /content/code_sandbox/config/models.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 606 |
```javascript
/**
* HTTP Server Settings
* (sails.config.http)
*
* Configuration for the underlying HTTP server in Sails.
* Only applies to HTTP requests (not WebSockets)
*
* For more information on configuration, check out:
* path_to_url#!/documentation/reference/sails.config/sails.config.http.html
*/
module.exports.http = {
/****************************************************************************
* *
* Express middleware to use for every Sails request. To add custom *
* middleware to the mix, add a function to the middleware config object and *
* add its key to the "order" array. The $custom key is reserved for *
* backwards-compatibility with Sails v0.9.x apps that use the *
* `customMiddleware` config option. *
* *
****************************************************************************/
// middleware: {
/***************************************************************************
* *
* The order in which middleware should be run for HTTP request. (the Sails *
* router is invoked by the "router" middleware below.) *
* *
***************************************************************************/
// order: [
// 'startRequestTimer',
// 'cookieParser',
// 'session',
// 'myRequestLogger',
// 'bodyParser',
// 'handleBodyParserError',
// 'compress',
// 'methodOverride',
// 'poweredBy',
// '$custom',
// 'router',
// 'www',
// 'favicon',
// '404',
// '500'
// ],
/****************************************************************************
* *
* Example custom middleware; logs each request to the console. *
* *
****************************************************************************/
// myRequestLogger: function (req, res, next) {
// console.log("Requested :: ", req.method, req.url);
// return next();
// }
/***************************************************************************
* *
* The body parser that will handle incoming multipart HTTP requests. By *
* default as of v0.10, Sails uses *
* [skipper](path_to_url See *
* path_to_url for other options. *
* *
***************************************************************************/
// bodyParser: require('skipper')
// },
/***************************************************************************
* *
* The number of seconds to cache flat files on disk being served by *
* Express static middleware (by default, these files are in `.tmp/public`) *
* *
* The HTTP static cache is only active in a 'production' environment, *
* since that's the only time Express will cache flat-files. *
* *
***************************************************************************/
cache: 30
};
``` | /content/code_sandbox/config/http.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 576 |
```javascript
/**
* Blueprint API Configuration
* (sails.config.blueprints)
*
* These settings are for the global configuration of blueprint routes and
* request options (which impact the behavior of blueprint actions).
*
* You may also override any of these settings on a per-controller basis
* by defining a '_config' key in your controller defintion, and assigning it
* a configuration object with overrides for the settings in this file.
* A lot of the configuration options below affect so-called "CRUD methods",
* or your controllers' `find`, `create`, `update`, and `destroy` actions.
*
* It's important to realize that, even if you haven't defined these yourself, as long as
* a model exists with the same name as the controller, Sails will respond with built-in CRUD
* logic in the form of a JSON API, including support for sort, pagination, and filtering.
*
* For more information on the blueprint API, check out:
* path_to_url#!/documentation/reference/blueprint-api
*
* For more information on the settings in this file, see:
* path_to_url#!/documentation/reference/sails.config/sails.config.blueprints.html
*
*/
module.exports.blueprints = {
/***************************************************************************
* *
* Action routes speed up the backend development workflow by *
* eliminating the need to manually bind routes. When enabled, GET, POST, *
* PUT, and DELETE routes will be generated for every one of a controller's *
* actions. *
* *
* If an `index` action exists, additional naked routes will be created for *
* it. Finally, all `actions` blueprints support an optional path *
* parameter, `id`, for convenience. *
* *
* `actions` are enabled by default, and can be OK for production-- *
* however, if you'd like to continue to use controller/action autorouting *
* in a production deployment, you must take great care not to *
* inadvertently expose unsafe/unintentional controller logic to GET *
* requests. *
* *
***************************************************************************/
actions: true,
/***************************************************************************
* *
* RESTful routes (`sails.config.blueprints.rest`) *
* *
* REST blueprints are the automatically generated routes Sails uses to *
* expose a conventional REST API on top of a controller's `find`, *
* `create`, `update`, and `destroy` actions. *
* *
* For example, a BoatController with `rest` enabled generates the *
* following routes: *
* ::::::::::::::::::::::::::::::::::::::::::::::::::::::: *
* GET /boat -> BoatController.find *
* GET /boat/:id -> BoatController.findOne *
* POST /boat -> BoatController.create *
* PUT /boat/:id -> BoatController.update *
* DELETE /boat/:id -> BoatController.destroy *
* *
* `rest` blueprint routes are enabled by default, and are suitable for use *
* in a production scenario, as long you take standard security precautions *
* (combine w/ policies, etc.) *
* *
***************************************************************************/
// rest: true,
/***************************************************************************
* *
* Shortcut routes are simple helpers to provide access to a *
* controller's CRUD methods from your browser's URL bar. When enabled, *
* GET, POST, PUT, and DELETE routes will be generated for the *
* controller's`find`, `create`, `update`, and `destroy` actions. *
* *
* `shortcuts` are enabled by default, but should be disabled in *
* production. *
* *
***************************************************************************/
// shortcuts: true,
/***************************************************************************
* *
* An optional mount path for all blueprint routes on a controller, *
* including `rest`, `actions`, and `shortcuts`. This allows you to take *
* advantage of blueprint routing, even if you need to namespace your API *
* methods. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
***************************************************************************/
prefix: '/api',
/***************************************************************************
* *
* An optional mount path for all REST blueprint routes on a controller. *
* And it do not include `actions` and `shortcuts` routes. *
* This allows you to take advantage of REST blueprint routing, *
* even if you need to namespace your RESTful API methods *
* *
***************************************************************************/
// restPrefix: '',
/***************************************************************************
* *
* Whether to pluralize controller names in blueprint routes. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
* For example, REST blueprints for `FooController` with `pluralize` *
* enabled: *
* GET /foos/:id? *
* POST /foos *
* PUT /foos/:id? *
* DELETE /foos/:id? *
* *
***************************************************************************/
// pluralize: false,
/***************************************************************************
* *
* Whether the blueprint controllers should populate model fetches with *
* data from other models which are linked by associations *
* *
* If you have a lot of data in one-to-many associations, leaving this on *
* may result in very heavy api calls *
* *
***************************************************************************/
// populate: true,
/****************************************************************************
* *
* Whether to run Model.watch() in the find and findOne blueprint actions. *
* Can be overridden on a per-model basis. *
* *
****************************************************************************/
// autoWatch: true,
/****************************************************************************
* *
* The default number of records to show in the response from a "find" *
* action. Doubles as the default size of populated arrays if populate is *
* true. *
* *
****************************************************************************/
// defaultLimit: 30
};
``` | /content/code_sandbox/config/blueprints.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 1,354 |
```javascript
/**
* Available release flavors
*
* These flavors will be created by the app on startup.
*/
module.exports.flavors = [
'default'
];
``` | /content/code_sandbox/config/flavors.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 32 |
```javascript
/**
* Available release channels
*
* These channels will be created by the app on startup.
*
* Ordered by descending stability.
*/
module.exports.channels = [
'stable',
'rc',
'beta',
'alpha'
];
``` | /content/code_sandbox/config/channels.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 50 |
```javascript
/**
* Built-in Log Configuration
* (sails.config.log)
*
* Configure the log level for your app, as well as the transport
* (Underneath the covers, Sails uses Winston for logging, which
* allows for some pretty neat custom transports/adapters for log messages)
*
* For more information on the Sails logger, check out:
* path_to_url#!/documentation/concepts/Logging
*/
module.exports.log = {
/***************************************************************************
* *
* Valid `level` configs: i.e. the minimum log level to capture with *
* sails.log.*() *
* *
* The order of precedence for log levels from lowest to highest is: *
* silly, verbose, info, debug, warn, error *
* *
* You may also set the level to "silent" to suppress all logs. *
* *
***************************************************************************/
// level: 'info'
};
``` | /content/code_sandbox/config/log.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 201 |
```javascript
/**
* File options
* Options which relate to filesystem storage of assets
*/
module.exports.files = {
// Maximum allowed file size in bytes
// Defaults to 500MB
maxBytes: 524288000,
// The fs directory name at which files will be kept
dirname: ''
};
``` | /content/code_sandbox/config/files.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 66 |
```javascript
/**
* View Engine Configuration
* (sails.config.views)
*
* Server-sent views are a classic and effective way to get your app up
* and running. Views are normally served from controllers. Below, you can
* configure your templating language/framework of choice and configure
* Sails' layout support.
*
* For more information on views and layouts, check out:
* path_to_url#!/documentation/concepts/Views
*/
module.exports.views = {
/****************************************************************************
* *
* View engine (aka template language) to use for your app's *server-side* *
* views *
* *
* Sails+Express supports all view engines which implement TJ Holowaychuk's *
* `consolidate.js`, including, but not limited to: *
* *
* ejs, pug, handlebars, mustache underscore, hogan, haml, haml-coffee, *
* dust atpl, eco, ect, jazz, jqtpl, JUST, liquor, QEJS, swig, templayed, *
* toffee, walrus, & whiskers *
* *
* For more options, check out the docs: *
* path_to_url#engine *
* *
****************************************************************************/
extension: 'pug',
getRenderFn: function () {
// Import `consolidate`.
var consolidate = require('consolidate');
// Return the rendering function for Pug.
return consolidate.pug;
},
layout: false,
/**
* How many releases are retrieve from the API at a time
*/
pageSize: 50
};
``` | /content/code_sandbox/config/views.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 362 |
```javascript
/**
* Policy Mappings
* (sails.config.policies)
*
* Policies are simple functions which run **before** your controllers.
* You can apply one or more policies to a given controller, or protect
* its actions individually.
*
* Any policy file (e.g. `api/policies/authenticated.js`) can be accessed
* below by its filename, minus the extension, (e.g. "authenticated")
*
* For more information on how policies work, see:
* path_to_url#!/documentation/concepts/Policies
*
* For more information on configuring policies, check out:
* path_to_url#!/documentation/reference/sails.config/sails.config.policies.html
*/
module.exports.policies = {
/***************************************************************************
* *
* Default policy for all controllers and actions (`true` allows public *
* access) *
* *
***************************************************************************/
'*': true,
AssetController: {
create: 'authToken',
update: 'authToken',
destroy: 'authToken',
download: 'noCache'
},
ChannelController: {
create: 'authToken',
update: 'authToken',
destroy: 'authToken'
},
FlavorController: {
create: 'authToken',
update: 'authToken',
destroy: 'authToken'
},
VersionController: {
create: 'authToken',
update: 'authToken',
destroy: 'authToken',
availability: 'authToken',
redirect: 'noCache',
general: 'noCache',
windows: 'noCache',
releaseNotes: 'noCache'
}
};
``` | /content/code_sandbox/config/policies.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 344 |
```javascript
/**
* Cross-Site Request Forgery Protection Settings
* (sails.config.csrf)
*
* CSRF tokens are like a tracking chip. While a session tells the server that a user
* "is who they say they are", a csrf token tells the server "you are where you say you are".
*
* When enabled, all non-GET requeststo the Sails server must be accompanied by
* a special token, identified as the '_csrf' parameter.
*
* This option protects your Sails app against cross-site request forgery (or CSRF) attacks.
* A would-be attacker needs not only a user's session cookie, but also this timestamped,
* secret CSRF token, which is refreshed/granted when the user visits a URL on your app's domain.
*
* This allows us to have certainty that our users' requests haven't been hijacked,
* and that the requests they're making are intentional and legitimate.
*
* This token has a short-lived expiration timeline, and must be acquired by either:
*
* (a) For traditional view-driven web apps:
* Fetching it from one of your views, where it may be accessed as
* a local variable, e.g.:
* <form>
* <input type="hidden" name="_csrf" value="<%= _csrf %>" />
* </form>
*
* or (b) For AJAX/Socket-heavy and/or single-page apps:
* Sending a GET request to the `/csrfToken` route, where it will be returned
* as JSON, e.g.:
* { _csrf: 'ajg4JD(JGdajhLJALHDa' }
*
*
* Enabling this option requires managing the token in your front-end app.
* For traditional web apps, it's as easy as passing the data from a view into a form action.
* In AJAX/Socket-heavy apps, just send a GET request to the /csrfToken route to get a valid token.
*
* For more information on CSRF, check out:
* path_to_url
*
* For more information on this configuration file, including info on CSRF + CORS, see:
* path_to_url#!/documentation/reference/sails.config/sails.config.csrf.html
*
*/
/****************************************************************************
* *
* Enabled CSRF protection for your site? *
* *
****************************************************************************/
// module.exports.csrf = false;
/****************************************************************************
* *
* You may also specify more fine-grained settings for CSRF, including the *
* domains which are allowed to request the CSRF token via AJAX. These *
* settings override the general CORS settings in your config/cors.js file. *
* *
****************************************************************************/
// module.exports.csrf = {
// grantTokenViaAjax: true,
// origin: ''
// }
``` | /content/code_sandbox/config/csrf.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 580 |
```javascript
/**
* THIS FILE WAS ADDED AUTOMATICALLY by the Sails 1.0 app migration tool.
*/
module.exports.datastores = {
// In previous versions, datastores (then called 'connections') would only be loaded
// if a model was actually using them. Starting with Sails 1.0, _all_ configured
// datastores will be loaded, regardless of use. So we'll only include datastores in
// this file that were actually being used. Your original `connections` config is
// still available as `config/connections-old.js.txt`.
};
``` | /content/code_sandbox/config/datastores.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 130 |
```javascript
/**
* Bootstrap
* (sails.config.bootstrap)
*
* An asynchronous bootstrap function that runs before your Sails app gets lifted.
* This gives you an opportunity to set up your data model, run jobs, or perform some special logic.
*
* For more information on bootstrapping your app, check out:
* path_to_url#!/documentation/reference/sails.config/sails.config.bootstrap.html
*/
const mapSeries = require('async/mapSeries');
const waterfall = require('async/waterfall');
const series = require('async/series');
module.exports.bootstrap = done => {
series([
// Create configured channels in database
cb => mapSeries(sails.config.channels, (name, next) => {
waterfall([
next => {
Channel
.find(name)
.exec(next);
},
(result, next) => {
if (result.length) return next();
Channel
.create({ name })
.exec(next);
}
], next);
}, cb),
// Populate existing versions without availability date using version creation date
cb => Version
.find({ availability: null })
.then(versions => mapSeries(
versions,
({ id, createdAt }, next) => {
Version
.update(id, { availability: createdAt })
.exec(next)
},
cb
)),
// Create configured flavors in database
cb => mapSeries(sails.config.flavors, (name, next) => {
waterfall([
next => {
Flavor
.find(name)
.exec(next);
},
(result, next) => {
if (result.length) return next();
Flavor
.create({ name })
.exec(next);
}
], next);
}, cb),
// Update existing versions and associated assets in database with default flavor data
cb => Version
.update(
{ flavor: null },
{ flavor: 'default' }
)
.exec((err, updatedVersions) => mapSeries(
updatedVersions,
({ name, id }, next) => {
Asset
.update(
{ version: name },
{ version: id }
)
.exec(next)
},
cb
))
], done);
};
``` | /content/code_sandbox/config/bootstrap.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 478 |
```javascript
/**
* Global Variable Configuration
* (sails.config.globals)
*
* Configure which global variables which will be exposed
* automatically by Sails.
*
* For more information on configuration, check out:
* path_to_url#!/documentation/reference/sails.config/sails.config.globals.html
*/
module.exports.globals = {
/****************************************************************************
* *
* Expose the lodash installed in Sails core as a global variable. If this *
* is disabled, like any other node module you can always run npm install *
* lodash --save, then var _ = require('lodash') at the top of any file. *
* *
****************************************************************************/
_: require('lodash'),
/****************************************************************************
* *
* Expose the async installed in Sails core as a global variable. If this is *
* disabled, like any other node module you can always run npm install async *
* --save, then var async = require('async') at the top of any file. *
* *
****************************************************************************/
async: require('async'),
/****************************************************************************
* *
* Expose the sails instance representing your app. If this is disabled, you *
* can still get access via req._sails. *
* *
****************************************************************************/
sails: true,
/****************************************************************************
* *
* Expose each of your app's services as global variables (using their *
* "globalId"). E.g. a service defined in api/models/NaturalLanguage.js *
* would have a globalId of NaturalLanguage by default. If this is disabled, *
* you can still access your services via sails.services.* *
* *
****************************************************************************/
// services: true,
/****************************************************************************
* *
* Expose each of your app's models as global variables (using their *
* "globalId"). E.g. a model defined in api/models/User.js would have a *
* globalId of User by default. If this is disabled, you can still access *
* your models via sails.models.*. *
* *
****************************************************************************/
models: true
};
``` | /content/code_sandbox/config/globals.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 466 |
```javascript
/**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `path_to_url`
* might match an image file: `/assets/images/foo.jpg`
*
* Finally, if those don't match either, the default 404 handler is triggered.
* See `api/responses/notFound.js` to adjust your app's 404 logic.
*
* Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
* flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or
* CoffeeScript for the front-end.
*
* For more information on configuring custom routes, check out:
* path_to_url#!/documentation/concepts/Routes/RouteTargetSyntax.html
*/
module.exports.routes = {
'/': { view: 'homepage' },
'/home': { view: 'homepage' },
'/releases/:channel?': { view: 'homepage' },
'/admin': { view: 'homepage' },
'/auth/login': { view: 'homepage' },
'/auth/logout': { view: 'homepage' },
'PUT /version/availability/:version/:timestamp': 'VersionController.availability',
'GET /download/latest/:platform?': 'AssetController.download',
'GET /download/channel/:channel/:platform?': 'AssetController.download',
'GET /download/:version/:platform?/:filename?': {
controller: 'AssetController',
action: 'download',
// This is important since it allows matching with filenames.
skipAssets: false
},
'GET /download/flavor/:flavor/latest/:platform?': 'AssetController.download',
'GET /download/flavor/:flavor/channel/:channel/:platform?': 'AssetController.download',
'GET /download/flavor/:flavor/:version/:platform?/:filename?': {
controller: 'AssetController',
action: 'download',
// This is important since it allows matching with filenames.
skipAssets: false
},
'GET /update': 'VersionController.redirect',
'GET /update/:platform/latest-mac.yml': 'VersionController.electronUpdaterMac',
'GET /update/:platform/:channel-mac.yml': 'VersionController.electronUpdaterMac',
'GET /update/:platform/latest.yml': 'VersionController.electronUpdaterWin',
'GET /update/:platform/:channel.yml': 'VersionController.electronUpdaterWin',
'GET /update/:platform/:version': 'VersionController.general',
'GET /update/:platform/:channel/latest.yml': 'VersionController.electronUpdaterWin',
'GET /update/:platform/:channel/latest-mac.yml': 'VersionController.electronUpdaterMac',
'GET /update/:platform/:version/RELEASES': 'VersionController.windows',
'GET /update/:platform/:version/:channel/RELEASES': 'VersionController.windows',
'GET /update/:platform/:version/:channel': 'VersionController.general',
'GET /update/flavor/:flavor/:platform/:version/:channel?': 'VersionController.general',
'GET /update/flavor/:flavor/:platform/:version/RELEASES': 'VersionController.windows',
'GET /update/flavor/:flavor/:platform/:version/:channel/RELEASES': 'VersionController.windows',
'GET /update/flavor/:flavor/:platform/latest.yml': 'VersionController.electronUpdaterWin',
'GET /update/flavor/:flavor/:platform/:channel.yml': 'VersionController.electronUpdaterWin',
'GET /update/flavor/:flavor/:platform/:channel/latest.yml': 'VersionController.electronUpdaterWin',
'GET /update/flavor/:flavor/:platform/latest-mac.yml': 'VersionController.electronUpdaterMac',
'GET /update/flavor/:flavor/:platform/:channel-mac.yml': 'VersionController.electronUpdaterMac',
'GET /update/flavor/:flavor/:platform/:channel/latest-mac.yml': 'VersionController.electronUpdaterMac',
'GET /notes/:version/:flavor?': 'VersionController.releaseNotes',
'GET /versions/sorted': 'VersionController.list',
'GET /channels/sorted': 'ChannelController.list'
};
``` | /content/code_sandbox/config/routes.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 952 |
```javascript
/**
* Development environment settings
*
* This file can include shared settings for a development team,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
/***************************************************************************
* Set the default database connection for models in the development *
* environment (see config/datastores.js and config/models.js ) *
***************************************************************************/
models: {
datastore: 'postgresql'
}
};
``` | /content/code_sandbox/config/env/development.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 147 |
```javascript
/**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
/***************************************************************************
* Set the default database connection for models in the production *
* environment (see config/datastores.js and config/models.js ) *
***************************************************************************/
models: {
datastore: 'postgresql',
migrate: 'safe'
},
/***************************************************************************
* Set the port in the production environment to 80 *
***************************************************************************/
port: 5014,
/***************************************************************************
* Set the log level in production environment to "silent" *
***************************************************************************/
// log: {
// level: "silent"
// }
// auth: {
// secret: 'temppass'
// }
};
``` | /content/code_sandbox/config/env/production.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 235 |
```javascript
/**
* WebSocket Server Settings
* (sails.config.sockets)
*
* These settings provide transparent access to the options for Sails'
* encapsulated WebSocket server, as well as some additional Sails-specific
* configuration layered on top.
*
* For more information on sockets configuration, including advanced config options, see:
* path_to_url#!/documentation/reference/sails.config/sails.config.sockets.html
*/
module.exports.sockets = {
/***************************************************************************
* *
* Node.js (and consequently Sails.js) apps scale horizontally. It's a *
* powerful, efficient approach, but it involves a tiny bit of planning. At *
* scale, you'll want to be able to copy your app onto multiple Sails.js *
* servers and throw them behind a load balancer. *
* *
* One of the big challenges of scaling an application is that these sorts *
* of clustered deployments cannot share memory, since they are on *
* physically different machines. On top of that, there is no guarantee *
* that a user will "stick" with the same server between requests (whether *
* HTTP or sockets), since the load balancer will route each request to the *
* Sails server with the most available resources. However that means that *
* all room/pubsub/socket processing and shared memory has to be offloaded *
* to a shared, remote messaging queue (usually Redis) *
* *
* Luckily, Socket.io (and consequently Sails.js) apps support Redis for *
* sockets by default. To enable a remote redis pubsub server, uncomment *
* the config below. *
* *
* Worth mentioning is that, if `adapter` config is `redis`, but host/port *
* is left unset, Sails will try to connect to redis running on localhost *
* via port 6379 *
* *
***************************************************************************/
// adapter: 'memory',
//
// -OR-
//
// adapter: 'redis',
// host: '127.0.0.1',
// port: 6379,
// db: 'sails',
// pass: '<redis auth password>',
/***************************************************************************
* *
* Whether to expose a 'get /__getcookie' route with CORS support that sets *
* a cookie (this is used by the sails.io.js socket client to get access to *
* a 3rd party cookie and to enable sessions). *
* *
* Warning: Currently in this scenario, CORS settings apply to interpreted *
* requests sent via a socket.io connection that used this cookie to *
* connect, even for non-browser clients! (e.g. iOS apps, toasters, node.js *
* unit tests) *
* *
***************************************************************************/
// grant3rdPartyCookie: true,
/***************************************************************************
* *
* `beforeConnect` *
* *
* This custom beforeConnect function will be run each time BEFORE a new *
* socket is allowed to connect, when the initial socket.io handshake is *
* performed with the server. *
* *
* By default, when a socket tries to connect, Sails allows it, every time. *
* (much in the same way any HTTP request is allowed to reach your routes. *
* If no valid cookie was sent, a temporary session will be created for the *
* connecting socket. *
* *
* If the cookie sent as part of the connection request doesn't match any *
* known user session, a new user session is created for it. *
* *
* In most cases, the user would already have a cookie since they loaded *
* the socket.io client and the initial HTML page you're building. *
* *
* However, in the case of cross-domain requests, it is possible to receive *
* a connection upgrade request WITHOUT A COOKIE (for certain transports) *
* In this case, there is no way to keep track of the requesting user *
* between requests, since there is no identifying information to link *
* him/her with a session. The sails.io.js client solves this by connecting *
* to a CORS/jsonp endpoint first to get a 3rd party cookie(fortunately this*
* works, even in Safari), then opening the connection. *
* *
* You can also pass along a ?cookie query parameter to the upgrade url, *
* which Sails will use in the absence of a proper cookie e.g. (when *
* connecting from the client): *
* io.sails.connect('path_to_url *
* *
* Finally note that the user's cookie is NOT (and will never be) accessible*
* from client-side javascript. Using HTTP-only cookies is crucial for your *
* app's security. *
* *
***************************************************************************/
// beforeConnect: function(handshake, cb) {
// // `true` allows the connection
// return cb(null, true);
//
// // (`false` would reject the connection)
// },
/***************************************************************************
* *
* `afterDisconnect` *
* *
* This custom afterDisconnect function will be run each time a socket *
* disconnects *
* *
***************************************************************************/
// afterDisconnect: function(session, socket, cb) {
// // By default: do nothing.
// return cb();
// },
/***************************************************************************
* *
* `transports` *
* *
* A array of allowed transport methods which the clients will try to use. *
* On server environments that don't support sticky sessions, the "polling" *
* transport should be disabled. *
* *
***************************************************************************/
// transports: ["polling", "websocket"]
};
``` | /content/code_sandbox/config/sockets.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 1,293 |
```scss
// Darkly 3.3.5
// Bootswatch
// -----------------------------------------------------
$web-font-path: "path_to_url" !default;
@import url($web-font-path);
// Navbar =====================================================================
.navbar {
border-width: 0;
&-default {
.badge {
background-color: #fff;
color: $navbar-default-bg;
}
}
&-inverse {
.badge {
background-color: #fff;
color: $navbar-inverse-bg;
}
}
&-brand {
line-height: 1;
}
&-form {
.form-control {
background-color: white;
&:focus {
border-color: white;
}
}
}
}
// Buttons ====================================================================
.btn {
border-width: 2px;
}
.btn:active {
@include box-shadow(none);
}
.btn-group.open .dropdown-toggle {
@include box-shadow(none);
}
// Typography =================================================================
.text-primary,
.text-primary:hover {
color: lighten($brand-primary, 10%);
}
.text-success,
.text-success:hover {
color: $brand-success;
}
.text-danger,
.text-danger:hover {
color: $brand-danger;
}
.text-warning,
.text-warning:hover {
color: $brand-warning;
}
.text-info,
.text-info:hover {
color: $brand-info;
}
// Tables =====================================================================
table,
.table {
a:not(.btn) {
text-decoration: underline;
}
.dropdown-menu a {
text-decoration: none;
}
.success,
.warning,
.danger,
.info {
color: #fff;
> th > a,
> td > a,
> a {
color: #fff;
}
}
> thead > tr > th,
> tbody > tr > th,
> tfoot > tr > th,
> thead > tr > td,
> tbody > tr > td,
> tfoot > tr > td {
border: none;
}
&-bordered > thead > tr > th,
&-bordered > tbody > tr > th,
&-bordered > tfoot > tr > th,
&-bordered > thead > tr > td,
&-bordered > tbody > tr > td,
&-bordered > tfoot > tr > td {
border: 1px solid $table-border-color;
}
}
// Forms ======================================================================
input,
textarea {
color: $input-color;
}
.form-control,
input,
textarea {
border: 2px hidden transparent;
@include box-shadow(none);
&:focus {
@include box-shadow(none);
}
}
.has-warning {
.help-block,
.control-label,
.radio,
.checkbox,
.radio-inline,
.checkbox-inline,
&.radio label,
&.checkbox label,
&.radio-inline label,
&.checkbox-inline label,
.form-control-feedback {
color: $brand-warning;
}
.form-control,
.form-control:focus {
@include box-shadow(none);
}
.input-group-addon {
border-color: $brand-warning;
}
}
.has-error {
.help-block,
.control-label,
.radio,
.checkbox,
.radio-inline,
.checkbox-inline,
&.radio label,
&.checkbox label,
&.radio-inline label,
&.checkbox-inline label,
.form-control-feedback {
color: $brand-danger;
}
.form-control,
.form-control:focus {
@include box-shadow(none);
}
.input-group-addon {
border-color: $brand-danger;
}
}
.has-success {
.help-block,
.control-label,
.radio,
.checkbox,
.radio-inline,
.checkbox-inline,
&.radio label,
&.checkbox label,
&.radio-inline label,
&.checkbox-inline label,
.form-control-feedback {
color: $brand-success;
}
.form-control,
.form-control:focus {
@include box-shadow(none);
}
.input-group-addon {
border-color: $brand-success;
}
}
.input-group-addon {
color: $text-color;
}
// Navs =======================================================================
.nav {
.open > a,
.open > a:hover,
.open > a:focus {
border-color: $nav-tabs-border-color;
}
}
.nav-tabs > li > a,
.nav-pills > li > a {
color: #fff;
}
.pager {
a,
a:hover {
color: #fff;
}
.disabled {
& > a,
& > a:hover,
& > a:focus,
& > span {
background-color: $pagination-disabled-bg;
}
}
}
.breadcrumb a {
color: #fff;
}
// Indicators =================================================================
.close {
text-decoration: none;
text-shadow: none;
opacity: 0.4;
&:hover,
&:focus {
opacity: 1;
}
}
.alert {
.alert-link {
color: #fff;
text-decoration: underline;
}
}
// Progress bars ==============================================================
.progress {
height: 10px;
@include box-shadow(none);
.progress-bar {
font-size: 10px;
line-height: 10px;
}
}
// Containers =================================================================
.well {
@include box-shadow(none);
}
a.list-group-item {
&.active,
&.active:hover,
&.active:focus {
border-color: $list-group-border;
}
&-success {
&.active {
background-color: $state-success-bg;
}
&.active:hover,
&.active:focus {
background-color: darken($state-success-bg, 5%);
}
}
&-warning {
&.active {
background-color: $state-warning-bg;
}
&.active:hover,
&.active:focus {
background-color: darken($state-warning-bg, 5%);
}
}
&-danger {
&.active {
background-color: $state-danger-bg;
}
&.active:hover,
&.active:focus {
background-color: darken($state-danger-bg, 5%);
}
}
}
.popover {
color: $text-color;
}
.panel-default > .panel-heading {
background-color: $panel-footer-bg;
}
``` | /content/code_sandbox/assets/styles/_bootswatch.scss | scss | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 1,391 |
```scss
$icon-font-path: '../bower_components/bootstrap-sass-official/assets/fonts/bootstrap/';
// Override the default flatly brand colour
$brand-primary: #088dd9 !default;
$brand-danger: $brand-primary !default;
$navbar-default-link-hover-color: #ccc !default;
$border-radius-base: 0 !default;
$border-radius-large: 0 !default;
$border-radius-small: 0 !default;
``` | /content/code_sandbox/assets/styles/_variable_override.scss | scss | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 90 |
```scss
.text-gray {
color: $gray-light;
}
.text-capitalize {
text-transform: capitalize;
}
.text-color-lock {
color: darken(desaturate($brand-primary, 50), 10);
}
.pointer {
cursor: pointer;
}
.release-notes {
white-space: pre;
font-size: 13px !important;
}
.timestamp {
font-size: 13px !important;
}
// Input label position
.form-horizontal .control-label {
padding-top: 0;
}
.padding-20-0 {
padding: 20px 0;
}
.padding-top-20 {
padding-top: 20px;
}
// Input status colours
.form-control,
input,
textarea {
border-style: solid;
}
.has-success {
.form-control,
.form-control:focus {
border-color: $brand-success;
color: $brand-success;
}
}
.is-warning {
color: $brand-warning;
}
.has-warning {
.form-control,
.form-control:focus {
border-color: $brand-warning;
color: $brand-warning;
}
}
.has-error {
.form-control,
.form-control:focus {
border-color: $brand-danger;
color: $brand-danger;
}
}
// Fix radio & checkbox input positioning
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
margin-left: 0;
}
// Navbar Logo
.navbar-logo {
padding: 10px 15px;
height: 60px;
}
.browsehappy {
background: #ccc;
color: #000;
margin: 0.2em 0;
padding: 0.2em 0;
}
// Custom page footer
.footer {
border-top: 1px solid #333;
color: #777;
margin: 30px 0;
padding-top: 10px;
}
// Panel header button
.modal-header-button {
margin-right: -16px;
margin-top: -9px;
}
// Modal footnote
.modal-footer-note {
float: left;
font-style: italic;
height: 45px;
line-height: 45px;
text-align: left;
.progress {
height: 45px;
.progress-bar {
font-size: 14px;
line-height: 45px;
}
}
}
// Editable table
.table-custom {
td {
vertical-align: middle !important;
text-align: center;
}
}
.editable-wrap {
display: inline-block;
margin: 0;
white-space: nowrap;
width: 100%;
.editable-controls,
.editable-error {
margin-bottom: 4px;
}
.editable-controls {
& > input,
& > select,
& > textarea {
margin-bottom: 0;
}
}
.editable-input {
display: inline-block;
}
}
.editable-buttons {
display: inline-block;
vertical-align: top;
button {
margin-left: 5px;
}
}
.editable-input.editable-has-buttons {
width: auto;
}
.editable-bstime {
.editable-input input[type=text] {
width: 46px;
}
.well-small {
margin-bottom: 0;
padding: 10px;
}
}
.editable-range output {
display: inline-block;
min-width: 30px;
text-align: center;
vertical-align: top;
}
.editable-color input[type=color] {
width: 50px;
}
.editable-checkbox label span,
.editable-checklist label span,
.editable-radiolist label span {
margin-left: 7px;
margin-right: 10px;
}
.editable-hide {
display: none !important;
}
.editable-click,
a.editable-click {
border-bottom: dashed 1px $brand-info;
color: $brand-info;
text-decoration: none;
}
.editable-click:hover,
a.editable-click:hover {
border-bottom-color: darken($brand-info, 15);
color: darken($brand-info, 15);
text-decoration: none;
}
.editable-empty,
.editable-empty:hover,
.editable-empty:focus,
a.editable-empty,
a.editable-empty:hover,
a.editable-empty:focus,
.empty-cell {
color: $brand-danger;
font-style: italic;
text-decoration: none;
}
input[type="number"].ng-valid {
border-color: green;
color: green;
}
input[type="number"].ng-invalid {
border-color: red;
color: red;
}
.download-btn {
margin-right: 10px;
margin-bottom: 10px;
}
.btn-group .btn {
margin-right: 5px;
}
``` | /content/code_sandbox/assets/styles/_custom.scss | scss | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 1,028 |
```scss
@import '_variable_override.scss';
@import '_variables.scss';
// bower:scss
@import '../bower_components/bootstrap-sass-official/assets/stylesheets/_bootstrap.scss';
// endbower
@import '_bootswatch.scss';
@import '_custom.scss';
``` | /content/code_sandbox/assets/styles/importer.scss | scss | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 55 |
```javascript
angular.module('app', [
'app.core',
'app.admin',
'app.home',
'app.releases'
])
.config(['$routeProvider', '$locationProvider', 'NotificationProvider',
function($routeProvider, $locationProvider, NotificationProvider) {
$routeProvider.otherwise({
redirectTo: '/home'
});
// Use the HTML5 History API
$locationProvider.html5Mode(true);
NotificationProvider.setOptions({
positionX: 'left',
positionY: 'bottom'
});
}
])
.run(['editableOptions', 'editableThemes',
function(editableOptions, editableThemes) {
editableThemes.bs3.inputClass = 'input-sm';
editableThemes.bs3.buttonsClass = 'btn-sm';
editableThemes.bs3.controlsTpl = '<div class="editable-controls"></div>';
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
}
])
.controller('MainController', ['$scope', 'AuthService',
function($scope, AuthService) {
$scope.isAuthenticated = AuthService.isAuthenticated;
}
]);
``` | /content/code_sandbox/assets/js/main.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 239 |
```javascript
angular.module('app.core', [
'app.core.dependencies',
'app.core.auth',
'app.core.data',
'app.core.nav'
]);
``` | /content/code_sandbox/assets/js/core/core.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 34 |
```javascript
angular.module('app.core.nav', [])
.controller('NavController', ['$scope', 'Session', function($scope, Session) {
$scope.Session = Session;
$scope.shouldHideNavMobile = true;
$scope.toggleNavMobile = function() {
$scope.shouldHideNavMobile = !$scope.shouldHideNavMobile;
};
$scope.hideNavMobile = function() {
$scope.shouldHideNavMobile = true;
};
}]);
``` | /content/code_sandbox/assets/js/core/nav-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 96 |
```javascript
angular.module('app.core.data', [
'app.core.data.service'
])
.run(['DataService',
function(DataService) {
DataService.initialize();
}
]);
``` | /content/code_sandbox/assets/js/core/data/data.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 38 |
```scss
$bootstrap-sass-asset-helper: false !default;
// Darkly 3.3.6
// Variables
// --------------------------------------------------
//== Colors
//
//## Gray and brand colors for use across Bootstrap.
$gray-base: #000 !default;
$gray-darker: lighten($gray-base, 13.5%) !default; // #222
$gray-dark: #303030 !default; // #333
$gray: #464545 !default;
$gray-light: #999 !default; // #999
$gray-lighter: #ebebeb !default; // #eee
$brand-primary: #375a7f !default;
$brand-success: #00bc8c !default;
$brand-info: #3498db !default;
$brand-warning: #f39c12 !default;
$brand-danger: #e74c3c !default;
//== Scaffolding
//
//## Settings for some of the most global styles.
//** Background color for `<body>`.
$body-bg: $gray-darker !default;
//** Global text color on `<body>`.
$text-color: #fff !default;
//** Global textual link color.
$link-color: desaturate(lighten($brand-success, 10%), 10%) !default;
//** Link hover color set via `darken()` function.
$link-hover-color: $link-color !default;
//** Link hover decoration.
$link-hover-decoration: underline !default;
//== Typography
//
//## Font, line-height, and color for body text, headings, and more.
$font-family-sans-serif: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif !default;
$font-family-serif: Georgia, "Times New Roman", Times, serif !default;
//** Default monospace fonts for `<code>`, `<kbd>`, and `<pre>`.
$font-family-monospace: Menlo, Monaco, Consolas, "Courier New", monospace !default;
$font-family-base: $font-family-sans-serif !default;
$font-size-base: 15px !default;
$font-size-large: ceil(($font-size-base * 1.25)) !default; // ~18px
$font-size-small: ceil(($font-size-base * 0.85)) !default; // ~12px
$font-size-h1: floor(($font-size-base * 2.6)) !default; // ~36px
$font-size-h2: floor(($font-size-base * 2.15)) !default; // ~30px
$font-size-h3: ceil(($font-size-base * 1.7)) !default; // ~24px
$font-size-h4: ceil(($font-size-base * 1.25)) !default; // ~18px
$font-size-h5: $font-size-base !default;
$font-size-h6: ceil(($font-size-base * 0.85)) !default; // ~12px
//** Unit-less `line-height` for use in components like buttons.
$line-height-base: 1.428571429 !default; // 20/14
//** Computed "line-height" (`font-size` * `line-height`) for use with `margin`, `padding`, etc.
$line-height-computed: floor(($font-size-base * $line-height-base)) !default; // ~20px
//** By default, this inherits from the `<body>`.
$headings-font-family: $font-family-base !default;
$headings-font-weight: 400 !default;
$headings-line-height: 1.1 !default;
$headings-color: inherit !default;
//== Iconography
//
//## Specify custom location and filename of the included Glyphicons icon font. Useful for those including Bootstrap via Bower.
//** Load fonts from this directory.
$icon-font-path: if($bootstrap-sass-asset-helper, "bootstrap/", "../fonts/bootstrap/") !default;
//** File name for all font files.
$icon-font-name: "glyphicons-halflings-regular" !default;
//** Element ID within SVG icon file.
$icon-font-svg-id: "glyphicons_halflingsregular" !default;
//== Components
//
//## Define common padding and border radius sizes and more. Values based on 14px text and 1.428 line-height (~20px to start).
$padding-base-vertical: 10px !default;
$padding-base-horizontal: 15px !default;
$padding-large-vertical: 18px !default;
$padding-large-horizontal: 27px !default;
$padding-small-vertical: 6px !default;
$padding-small-horizontal: 9px !default;
$padding-xs-vertical: 1px !default;
$padding-xs-horizontal: 5px !default;
$line-height-large: 1.3333333 !default; // extra decimals for Win 8.1 Chrome
$line-height-small: 1.5 !default;
$border-radius-base: 4px !default;
$border-radius-large: 6px !default;
$border-radius-small: 3px !default;
//** Global color for active items (e.g., navs or dropdowns).
$component-active-color: #fff !default;
//** Global background color for active items (e.g., navs or dropdowns).
$component-active-bg: $brand-primary !default;
//** Width of the `border` for generating carets that indicator dropdowns.
$caret-width-base: 4px !default;
//** Carets increase slightly in size for larger components.
$caret-width-large: 5px !default;
//== Tables
//
//## Customizes the `.table` component with basic values, each used across all table variations.
//** Padding for `<th>`s and `<td>`s.
$table-cell-padding: 8px !default;
//** Padding for cells in `.table-condensed`.
$table-condensed-cell-padding: 5px !default;
//** Default background color used for all tables.
$table-bg: transparent !default;
//** Background color used for `.table-striped`.
$table-bg-accent: lighten($gray-dark, 5%) !default;
//** Background color used for `.table-hover`.
$table-bg-hover: $gray !default;
$table-bg-active: $table-bg-hover !default;
//** Border color for table and cell borders.
$table-border-color: $gray !default;
//== Buttons
//
//## For each of Bootstrap's buttons, define text, background and border color.
$btn-font-weight: normal !default;
$btn-default-color: $text-color !default;
$btn-default-bg: $gray !default;
$btn-default-border: $btn-default-bg !default;
$btn-primary-color: #fff !default;
$btn-primary-bg: $brand-primary !default;
$btn-primary-border: $btn-primary-bg !default;
$btn-success-color: $btn-primary-color !default;
$btn-success-bg: $brand-success !default;
$btn-success-border: $btn-success-bg !default;
$btn-info-color: $btn-success-color !default;
$btn-info-bg: $brand-info !default;
$btn-info-border: $btn-info-bg !default;
$btn-warning-color: $btn-success-color !default;
$btn-warning-bg: $brand-warning !default;
$btn-warning-border: $btn-warning-bg !default;
$btn-danger-color: $btn-success-color !default;
$btn-danger-bg: $brand-danger !default;
$btn-danger-border: $btn-danger-bg !default;
$btn-link-disabled-color: $gray-light !default;
// Allows for customizing button radius independently from global border radius
$btn-border-radius-base: $border-radius-base !default;
$btn-border-radius-large: $border-radius-large !default;
$btn-border-radius-small: $border-radius-small !default;
//== Forms
//
//##
//** `<input>` background color
$input-bg: #fff !default;
//** `<input disabled>` background color
$input-bg-disabled: $gray-lighter !default;
//** Text color for `<input>`s
$input-color: $gray !default;
//** `<input>` border color
$input-border: #f1f1f1 !default;
// TODO: Rename `$input-border-radius` to `$input-border-radius-base` in v4
//** Default `.form-control` border radius
// This has no effect on `<select>`s in some browsers, due to the limited stylability of `<select>`s in CSS.
$input-border-radius: $border-radius-base !default;
//** Large `.form-control` border radius
$input-border-radius-large: $border-radius-large !default;
//** Small `.form-control` border radius
$input-border-radius-small: $border-radius-small !default;
//** Border color for inputs on focus
$input-border-focus: #fff !default;
//** Placeholder text color
$input-color-placeholder: $gray-light !default;
//** Default `.form-control` height
$input-height-base: ($line-height-computed + ($padding-base-vertical * 2) + 4) !default;
//** Large `.form-control` height
$input-height-large: (ceil($font-size-large * $line-height-large) + ($padding-large-vertical * 2) + 4) !default;
//** Small `.form-control` height
$input-height-small: (floor($font-size-small * $line-height-small) + ($padding-small-vertical * 2) + 4) !default;
//** `.form-group` margin
$form-group-margin-bottom: 15px !default;
$legend-color: $text-color !default;
$legend-border-color: transparent !default;
//** Background color for textual input addons
$input-group-addon-bg: $gray !default;
//** Border color for textual input addons
$input-group-addon-border-color: transparent !default;
//** Disabled cursor for form controls and buttons.
$cursor-disabled: not-allowed !default;
//== Dropdowns
//
//## Dropdown menu container and contents.
//** Background for the dropdown menu.
$dropdown-bg: $gray-dark !default;
//** Dropdown menu `border-color`.
$dropdown-border: rgba(0, 0, 0, 0.15) !default;
//** Dropdown menu `border-color` **for IE8**.
$dropdown-fallback-border: #ccc !default;
//** Divider color for between dropdown items.
$dropdown-divider-bg: $gray !default;
//** Dropdown link text color.
$dropdown-link-color: $gray-lighter !default;
//** Hover color for dropdown links.
$dropdown-link-hover-color: #fff !default;
//** Hover background for dropdown links.
$dropdown-link-hover-bg: $component-active-bg !default;
//** Active dropdown menu item text color.
$dropdown-link-active-color: #fff !default;
//** Active dropdown menu item background color.
$dropdown-link-active-bg: $component-active-bg !default;
//** Disabled dropdown menu item background color.
$dropdown-link-disabled-color: $gray-light !default;
//** Text color for headers within dropdown menus.
$dropdown-header-color: $gray-light !default;
//** Deprecated `$dropdown-caret-color` as of v3.1.0
$dropdown-caret-color: #000 !default;
//-- Z-index master list
//
// Warning: Avoid customizing these values. They're used for a bird's eye view
// of components dependent on the z-axis and are designed to all work together.
//
// Note: These variables are not generated into the Customizer.
$zindex-navbar: 1000 !default;
$zindex-dropdown: 1000 !default;
$zindex-popover: 1060 !default;
$zindex-tooltip: 1070 !default;
$zindex-navbar-fixed: 1030 !default;
$zindex-modal-background: 1040 !default;
$zindex-modal: 1050 !default;
//== Media queries breakpoints
//
//## Define the breakpoints at which your layout will change, adapting to different screen sizes.
// Extra small screen / phone
//** Deprecated `$screen-xs` as of v3.0.1
$screen-xs: 480px !default;
//** Deprecated `$screen-xs-min` as of v3.2.0
$screen-xs-min: $screen-xs !default;
//** Deprecated `$screen-phone` as of v3.0.1
$screen-phone: $screen-xs-min !default;
// Small screen / tablet
//** Deprecated `$screen-sm` as of v3.0.1
$screen-sm: 768px !default;
$screen-sm-min: $screen-sm !default;
//** Deprecated `$screen-tablet` as of v3.0.1
$screen-tablet: $screen-sm-min !default;
// Medium screen / desktop
//** Deprecated `$screen-md` as of v3.0.1
$screen-md: 992px !default;
$screen-md-min: $screen-md !default;
//** Deprecated `$screen-desktop` as of v3.0.1
$screen-desktop: $screen-md-min !default;
// Large screen / wide desktop
//** Deprecated `$screen-lg` as of v3.0.1
$screen-lg: 1200px !default;
$screen-lg-min: $screen-lg !default;
//** Deprecated `$screen-lg-desktop` as of v3.0.1
$screen-lg-desktop: $screen-lg-min !default;
// So media queries don't overlap when required, provide a maximum
$screen-xs-max: ($screen-sm-min - 1) !default;
$screen-sm-max: ($screen-md-min - 1) !default;
$screen-md-max: ($screen-lg-min - 1) !default;
//== Grid system
//
//## Define your custom responsive grid.
//** Number of columns in the grid.
$grid-columns: 12 !default;
//** Padding between columns. Gets divided in half for the left and right.
$grid-gutter-width: 30px !default;
// Navbar collapse
//** Point at which the navbar becomes uncollapsed.
$grid-float-breakpoint: $screen-sm-min !default;
//** Point at which the navbar begins collapsing.
$grid-float-breakpoint-max: ($grid-float-breakpoint - 1) !default;
//== Container sizes
//
//## Define the maximum width of `.container` for different screen sizes.
// Small screen / tablet
$container-tablet: (720px + $grid-gutter-width) !default;
//** For `$screen-sm-min` and up.
$container-sm: $container-tablet !default;
// Medium screen / desktop
$container-desktop: (940px + $grid-gutter-width) !default;
//** For `$screen-md-min` and up.
$container-md: $container-desktop !default;
// Large screen / wide desktop
$container-large-desktop: (1140px + $grid-gutter-width) !default;
//** For `$screen-lg-min` and up.
$container-lg: $container-large-desktop !default;
//== Navbar
//
//##
// Basics of a navbar
$navbar-height: 60px !default;
$navbar-margin-bottom: $line-height-computed !default;
$navbar-border-radius: $border-radius-base !default;
$navbar-padding-horizontal: floor(($grid-gutter-width / 2)) !default;
$navbar-padding-vertical: (($navbar-height - $line-height-computed) / 2) !default;
$navbar-collapse-max-height: 340px !default;
$navbar-default-color: #777 !default;
$navbar-default-bg: $brand-primary !default;
$navbar-default-border: transparent !default;
// Navbar links
$navbar-default-link-color: #fff !default;
$navbar-default-link-hover-color: $brand-success !default;
$navbar-default-link-hover-bg: transparent !default;
$navbar-default-link-active-color: #fff !default;
$navbar-default-link-active-bg: darken($navbar-default-bg, 10%) !default;
$navbar-default-link-disabled-color: #ccc !default;
$navbar-default-link-disabled-bg: transparent !default;
// Navbar brand label
$navbar-default-brand-color: $navbar-default-link-color !default;
$navbar-default-brand-hover-color: $navbar-default-link-hover-color !default;
$navbar-default-brand-hover-bg: transparent !default;
// Navbar toggle
$navbar-default-toggle-hover-bg: darken($navbar-default-bg, 10%) !default;
$navbar-default-toggle-icon-bar-bg: #fff !default;
$navbar-default-toggle-border-color: darken($navbar-default-bg, 10%) !default;
//=== Inverted navbar
// Reset inverted navbar basics
$navbar-inverse-color: #fff !default;
$navbar-inverse-bg: $brand-success !default;
$navbar-inverse-border: transparent !default;
// Inverted navbar links
$navbar-inverse-link-color: $navbar-inverse-color !default;
$navbar-inverse-link-hover-color: $brand-primary !default;
$navbar-inverse-link-hover-bg: transparent !default;
$navbar-inverse-link-active-color: $navbar-inverse-color !default;
$navbar-inverse-link-active-bg: darken($navbar-inverse-bg, 5%) !default;
$navbar-inverse-link-disabled-color: #aaa !default;
$navbar-inverse-link-disabled-bg: transparent !default;
// Inverted navbar brand label
$navbar-inverse-brand-color: $navbar-inverse-link-color !default;
$navbar-inverse-brand-hover-color: $navbar-inverse-link-hover-color !default;
$navbar-inverse-brand-hover-bg: transparent !default;
// Inverted navbar toggle
$navbar-inverse-toggle-hover-bg: darken($navbar-inverse-bg, 10%) !default;
$navbar-inverse-toggle-icon-bar-bg: #fff !default;
$navbar-inverse-toggle-border-color: darken($navbar-inverse-bg, 10%) !default;
//== Navs
//
//##
//=== Shared nav styles
$nav-link-padding: 10px 15px !default;
$nav-link-hover-bg: $gray-dark !default;
$nav-disabled-link-color: lighten($gray, 10%) !default;
$nav-disabled-link-hover-color: lighten($gray, 10%) !default;
//== Tabs
$nav-tabs-border-color: $gray !default;
$nav-tabs-link-hover-border-color: $gray !default;
$nav-tabs-active-link-hover-bg: $body-bg !default;
$nav-tabs-active-link-hover-color: $brand-success !default;
$nav-tabs-active-link-hover-border-color: $nav-tabs-link-hover-border-color !default;
$nav-tabs-justified-link-border-color: $gray-lighter !default;
$nav-tabs-justified-active-link-border-color: $body-bg !default;
//== Pills
$nav-pills-border-radius: $border-radius-base !default;
$nav-pills-active-link-hover-bg: $component-active-bg !default;
$nav-pills-active-link-hover-color: $component-active-color !default;
//== Pagination
//
//##
$pagination-color: #fff !default;
$pagination-bg: $brand-success !default;
$pagination-border: transparent !default;
$pagination-hover-color: #fff !default;
$pagination-hover-bg: lighten($brand-success, 6%) !default;
$pagination-hover-border: transparent !default;
$pagination-active-color: #fff !default;
$pagination-active-bg: lighten($brand-success, 6%) !default;
$pagination-active-border: transparent !default;
$pagination-disabled-color: #fff !default;
$pagination-disabled-bg: darken($brand-success, 15%) !default;
$pagination-disabled-border: transparent !default;
//== Pager
//
//##
$pager-bg: $pagination-bg !default;
$pager-border: $pagination-border !default;
$pager-border-radius: 15px !default;
$pager-hover-bg: $pagination-hover-bg !default;
$pager-active-bg: $pagination-active-bg !default;
$pager-active-color: $pagination-active-color !default;
$pager-disabled-color: #ddd !default;
//== Jumbotron
//
//##
$jumbotron-padding: 30px !default;
$jumbotron-color: inherit !default;
$jumbotron-bg: $gray-dark !default;
$jumbotron-heading-color: inherit !default;
$jumbotron-font-size: ceil(($font-size-base * 1.5)) !default;
$jumbotron-heading-font-size: ceil(($font-size-base * 4.5)) !default;
//== Form states and alerts
//
//## Define colors for form feedback states and, by default, alerts.
$state-success-text: #fff !default;
$state-success-bg: $brand-success !default;
$state-success-border: $brand-success !default;
$state-info-text: #fff !default;
$state-info-bg: $brand-info !default;
$state-info-border: $brand-info !default;
$state-warning-text: #fff !default;
$state-warning-bg: $brand-warning !default;
$state-warning-border: $brand-warning !default;
$state-danger-text: #fff !default;
$state-danger-bg: $brand-danger !default;
$state-danger-border: $brand-danger !default;
//== Tooltips
//
//##
//** Tooltip max width
$tooltip-max-width: 200px !default;
//** Tooltip text color
$tooltip-color: #fff !default;
//** Tooltip background color
$tooltip-bg: #000 !default;
$tooltip-opacity: 0.9 !default;
//** Tooltip arrow width
$tooltip-arrow-width: 5px !default;
//** Tooltip arrow color
$tooltip-arrow-color: $tooltip-bg !default;
//== Popovers
//
//##
//** Popover body background color
$popover-bg: $gray-dark !default;
//** Popover maximum width
$popover-max-width: 276px !default;
//** Popover border color
$popover-border-color: rgba(0, 0, 0, 0.2) !default;
//** Popover fallback border color
$popover-fallback-border-color: #999 !default;
//** Popover title background color
$popover-title-bg: darken($popover-bg, 3%) !default;
//** Popover arrow width
$popover-arrow-width: 10px !default;
//** Popover arrow color
$popover-arrow-color: $popover-bg !default;
//** Popover outer arrow width
$popover-arrow-outer-width: ($popover-arrow-width + 1) !default;
//** Popover outer arrow color
$popover-arrow-outer-color: fadein($popover-border-color, 5%) !default;
//** Popover outer arrow fallback color
$popover-arrow-outer-fallback-color: darken($popover-fallback-border-color, 20%) !default;
//== Labels
//
//##
//** Default label background color
$label-default-bg: $gray !default;
//** Primary label background color
$label-primary-bg: $brand-primary !default;
//** Success label background color
$label-success-bg: $brand-success !default;
//** Info label background color
$label-info-bg: $brand-info !default;
//** Warning label background color
$label-warning-bg: $brand-warning !default;
//** Danger label background color
$label-danger-bg: $brand-danger !default;
//** Default label text color
$label-color: #fff !default;
//** Default text color of a linked label
$label-link-hover-color: #fff !default;
//== Modals
//
//##
//** Padding applied to the modal body
$modal-inner-padding: 20px !default;
//** Padding applied to the modal title
$modal-title-padding: 15px !default;
//** Modal title line-height
$modal-title-line-height: $line-height-base !default;
//** Background color of modal content area
$modal-content-bg: $gray-dark !default;
//** Modal content border color
$modal-content-border-color: rgba(0, 0, 0, 0.2) !default;
//** Modal content border color **for IE8**
$modal-content-fallback-border-color: #999 !default;
//** Modal backdrop background color
$modal-backdrop-bg: #000 !default;
//** Modal backdrop opacity
$modal-backdrop-opacity: 0.7 !default;
//** Modal header border color
$modal-header-border-color: $gray !default;
//** Modal footer border color
$modal-footer-border-color: $modal-header-border-color !default;
$modal-lg: 900px !default;
$modal-md: 600px !default;
$modal-sm: 300px !default;
//== Alerts
//
//## Define alert colors, border radius, and padding.
$alert-padding: 15px !default;
$alert-border-radius: $border-radius-base !default;
$alert-link-font-weight: bold !default;
$alert-success-bg: $state-success-bg !default;
$alert-success-text: $state-success-text !default;
$alert-success-border: $state-success-border !default;
$alert-info-bg: $state-info-bg !default;
$alert-info-text: $state-info-text !default;
$alert-info-border: $state-info-border !default;
$alert-warning-bg: $state-warning-bg !default;
$alert-warning-text: $state-warning-text !default;
$alert-warning-border: $state-warning-border !default;
$alert-danger-bg: $state-danger-bg !default;
$alert-danger-text: $state-danger-text !default;
$alert-danger-border: $state-danger-border !default;
//== Progress bars
//
//##
//** Background color of the whole progress component
$progress-bg: $gray-lighter !default;
//** Progress bar text color
$progress-bar-color: #fff !default;
//** Variable for setting rounded corners on progress bar.
$progress-border-radius: $border-radius-base !default;
//** Default progress bar color
$progress-bar-bg: $brand-primary !default;
//** Success progress bar color
$progress-bar-success-bg: $brand-success !default;
//** Warning progress bar color
$progress-bar-warning-bg: $brand-warning !default;
//** Danger progress bar color
$progress-bar-danger-bg: $brand-danger !default;
//** Info progress bar color
$progress-bar-info-bg: $brand-info !default;
//== List group
//
//##
//** Background color on `.list-group-item`
$list-group-bg: $gray-dark !default;
//** `.list-group-item` border color
$list-group-border: $gray !default;
//** List group border radius
$list-group-border-radius: $border-radius-base !default;
//** Background color of single list items on hover
$list-group-hover-bg: transparent !default;
//** Text color of active list items
$list-group-active-color: $component-active-color !default;
//** Background color of active list items
$list-group-active-bg: $component-active-bg !default;
//** Border color of active list elements
$list-group-active-border: $list-group-active-bg !default;
//** Text color for content within active list items
$list-group-active-text-color: lighten($list-group-active-bg, 40%) !default;
//** Text color of disabled list items
$list-group-disabled-color: $gray-light !default;
//** Background color of disabled list items
$list-group-disabled-bg: $gray-lighter !default;
//** Text color for content within disabled list items
$list-group-disabled-text-color: $list-group-disabled-color !default;
$list-group-link-color: $link-color !default;
$list-group-link-hover-color: $list-group-link-color !default;
$list-group-link-heading-color: darken($link-color, 5%) !default;
//== Panels
//
//##
$panel-bg: $gray-dark !default;
$panel-body-padding: 15px !default;
$panel-heading-padding: 10px 15px !default;
$panel-footer-padding: $panel-heading-padding !default;
$panel-border-radius: $border-radius-base !default;
//** Border color for elements within panels
$panel-inner-border: $gray !default;
$panel-footer-bg: $gray !default;
$panel-default-text: $text-color !default;
$panel-default-border: $gray !default;
$panel-default-heading-bg: $gray-dark !default;
$panel-primary-text: #fff !default;
$panel-primary-border: $brand-primary !default;
$panel-primary-heading-bg: $brand-primary !default;
$panel-success-text: $state-success-text !default;
$panel-success-border: $state-success-border !default;
$panel-success-heading-bg: $state-success-bg !default;
$panel-info-text: $state-info-text !default;
$panel-info-border: $state-info-border !default;
$panel-info-heading-bg: $state-info-bg !default;
$panel-warning-text: $state-warning-text !default;
$panel-warning-border: $state-warning-border !default;
$panel-warning-heading-bg: $state-warning-bg !default;
$panel-danger-text: $state-danger-text !default;
$panel-danger-border: $state-danger-border !default;
$panel-danger-heading-bg: $state-danger-bg !default;
//== Thumbnails
//
//##
//** Padding around the thumbnail image
$thumbnail-padding: 2px !default;
//** Thumbnail background color
$thumbnail-bg: $body-bg !default;
//** Thumbnail border color
$thumbnail-border: $gray !default;
//** Thumbnail border radius
$thumbnail-border-radius: $border-radius-base !default;
//** Custom text color for thumbnail captions
$thumbnail-caption-color: $text-color !default;
//** Padding around the thumbnail caption
$thumbnail-caption-padding: 9px !default;
//== Wells
//
//##
$well-bg: $gray-dark !default;
$well-border: transparent !default;
//== Badges
//
//##
$badge-color: #fff !default;
//** Linked badge text color on hover
$badge-link-hover-color: #fff !default;
$badge-bg: $gray !default;
//** Badge text color in active nav link
$badge-active-color: $brand-primary !default;
//** Badge background color in active nav link
$badge-active-bg: #fff !default;
$badge-font-weight: bold !default;
$badge-line-height: 1 !default;
$badge-border-radius: 10px !default;
//== Breadcrumbs
//
//##
$breadcrumb-padding-vertical: 8px !default;
$breadcrumb-padding-horizontal: 15px !default;
//** Breadcrumb background color
$breadcrumb-bg: $gray !default;
//** Breadcrumb text color
$breadcrumb-color: $text-color !default;
//** Text color of current page in the breadcrumb
$breadcrumb-active-color: $gray-light !default;
//** Textual separator for between breadcrumb elements
$breadcrumb-separator: "/" !default;
//== Carousel
//
//##
$carousel-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6) !default;
$carousel-control-color: #fff !default;
$carousel-control-width: 15% !default;
$carousel-control-opacity: 0.5 !default;
$carousel-control-font-size: 20px !default;
$carousel-indicator-active-bg: #fff !default;
$carousel-indicator-border-color: #fff !default;
$carousel-caption-color: #fff !default;
//== Close
//
//##
$close-font-weight: bold !default;
$close-color: #fff !default;
$close-text-shadow: none !default;
//== Code
//
//##
$code-color: #c7254e !default;
$code-bg: #f9f2f4 !default;
$kbd-color: #fff !default;
$kbd-bg: #333 !default;
$pre-bg: $gray-lighter !default;
$pre-color: $gray-dark !default;
$pre-border-color: #ccc !default;
$pre-scrollable-max-height: 340px !default;
//== Type
//
//##
//** Horizontal offset for forms and lists.
$component-offset-horizontal: 180px !default;
//** Text muted color
$text-muted: $gray-light !default;
//** Abbreviations and acronyms border color
$abbr-border-color: $gray-light !default;
//** Headings small color
$headings-small-color: $gray-light !default;
//** Blockquote small color
$blockquote-small-color: $gray-light !default;
//** Blockquote font size
$blockquote-font-size: ($font-size-base * 1.25) !default;
//** Blockquote border color
$blockquote-border-color: $gray !default;
//** Page header border color
$page-header-border-color: transparent !default;
//** Width of horizontal description list titles
$dl-horizontal-offset: $component-offset-horizontal !default;
//** Point at which .dl-horizontal becomes horizontal
$dl-horizontal-breakpoint: $grid-float-breakpoint !default;
//** Horizontal line color.
$hr-border: $gray !default;
``` | /content/code_sandbox/assets/styles/_variables.scss | scss | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 7,334 |
```javascript
angular.module('app.core.dependencies', [
'ngRoute',
'ngAnimate',
'ngMessages',
'ngSanitize',
'ngFileUpload',
'ui-notification',
'ui.bootstrap',
'ng.deviceDetector',
'angular-confirm',
'PubSub',
'xeditable',
'angularMoment'
]);
``` | /content/code_sandbox/assets/js/core/dependencies/dependencies.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 74 |
```javascript
angular.module('app.core.auth', [
'app.core.auth.service',
'app.core.auth.login',
'app.core.auth.logout',
'angular-jwt'
]).constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
loginFailed: 'auth-login-failed',
logoutSuccess: 'auth-logout-success',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
})
.directive('authToolbar', function() {
return {
restrict: 'E',
templateUrl: '/templates/auth-toolbar.html'
};
})
.config(['$httpProvider', 'jwtInterceptorProvider',
function($httpProvider, jwtInterceptorProvider) {
// Please note we're annotating the function so that the $injector works when the file is minified
jwtInterceptorProvider.tokenGetter = ['AuthService', function(AuthService) {
return AuthService.getToken();
}];
$httpProvider.interceptors.push('jwtInterceptor');
}
])
.run(['$rootScope', 'AUTH_EVENTS', 'AuthService', 'Notification', '$location',
function($rootScope, AUTH_EVENTS, AuthService, Notification, $location) {
$rootScope.$on('$routeChangeStart', function(event, next) {
// Consider whether to redirect the request if it is unauthorized
if (
next.data &&
next.data.private
) {
if (!AuthService.isAuthenticated()) {
console.log('Unauthorized request, redirecting...');
event.preventDefault();
// User is not logged in
$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
Notification.error({
title: 'Unauthorized',
message: 'Please login'
});
// Redirect the user to the login page
$location.path('/auth/login');
}
}
});
}
]);
``` | /content/code_sandbox/assets/js/core/auth/auth.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 389 |
```javascript
angular.module('app.core.auth.service', [
'ngStorage'
])
.service('AuthService', ['$rootScope', 'AUTH_EVENTS', '$http', '$localStorage', '$q', 'jwtHelper',
function($rootScope, AUTH_EVENTS, $http, $localStorage, $q, jwtHelper) {
var self = this;
self.getToken = function() {
return $localStorage.token;
};
self.login = function(credentials) {
var defer = $q.defer();
$http
.post('/api/auth/login', credentials)
.then(function(res) {
if (!res.data || !_.isString(res.data.token)) {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
return defer.reject({
data: 'Expected a token in server response.'
});
}
var tokenContents = jwtHelper.decodeToken(res.data.token);
if (!_.isObjectLike(tokenContents)) {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
return defer.reject({
data: 'Invalid token received.'
});
}
$localStorage.token = res.data.token;
$localStorage.tokenContents = tokenContents;
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
defer.resolve(true);
}, function(err) {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
defer.reject(err);
});
return defer.promise;
};
self.isAuthenticated = function() {
var token = $localStorage.tokenContents;
return (_.isObjectLike(token) && _.has(token, 'sub'));
};
self.logout = function() {
delete $localStorage.token;
delete $localStorage.tokenContents;
$rootScope.$broadcast(AUTH_EVENTS.logoutSuccess);
};
}
]);
``` | /content/code_sandbox/assets/js/core/auth/auth-service.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 354 |
```javascript
angular.module('app.core.auth.login', [
'ngStorage',
'ngRoute'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/auth/login', {
templateUrl: 'js/core/auth/login/login.html',
controller: 'LoginController',
data: {
private: false
}
});
}])
.controller('LoginController', ['$scope', 'Notification', 'AuthService', '$location',
function($scope, Notification, AuthService, $location) {
if (AuthService.isAuthenticated()) {
$location.path('/admin');
}
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function(credentials) {
AuthService.login(credentials).then(function(user) {
Notification.success({
message: 'Login Successful'
});
$location.path('/admin');
}, function(err) {
const notificationObject = {
title: err.statusText || 'Unable to login',
message: err.data || 'Invalid Credentials'
};
Notification.error(notificationObject);
});
};
}
]);
``` | /content/code_sandbox/assets/js/core/auth/login/login-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 231 |
```javascript
angular.module('app.core.data.service', [
'ngSails'
])
.service('DataService', [
'$sails', '$q', '$log', '$http', 'Notification', 'Upload', 'PubSub',
'AuthService',
function(
$sails, $q, $log, $http, Notification, Upload, PubSub,
AuthService
) {
var self = this;
/**
* Main Data object, containing all of the version objects and their
* nested assets
* @type {array}
*/
self.data = [];
var UNKNOWN_ERROR_MESSAGE = 'An Unkown Error Occurred.';
/**
* A relation between valid platforms & their pretty names
* @type {Array}
*/
self.availablePlatforms = {
windows_64: 'Windows 64 bit',
windows_32: 'Windows 32 bit',
osx_64: 'OS X 64 bit Intel',
osx_arm64: 'OS X 64 bit ARM',
linux_64: 'Linux 64 bit',
linux_32: 'Linux 32 bit'
};
self.filetypes = {
windows_64: ['.exe', '.msi'],
windows_32: ['.exe', '.msi'],
osx_64: ['.dmg', '.pkg', '.mas'],
osx_arm64: ['.dmg', '.pkg', '.mas'],
linux_64: ['.deb', '.gz', '.rpm', '.AppImage'],
linux_32: ['.deb', '.gz', '.rpm', '.AppImage']
};
/**
* Compare version objects using semantic versioning.
* Pass to Array.sort for a descending array
* @param {Object} v1 Version object one
* @param {Object} v2 Version object two
* @return {-1|0|1} Whether one is is less than or greater
*/
self.compareVersion = function(v1, v2) {
return -compareVersions(v1.name, v2.name);
};
/**
* Sort version data in descending order
*/
self.sortVersions = function() {
self.data.sort(self.compareVersion);
};
/**
* Shows an appropriate error notification method for every invalid
* attribute.
* @param {Object} response A response object returned by sails after a
* erroneous blueprint request.
*/
var showAttributeWarnings = function(response) {
if (!_.has(response, 'data.invalidAttributes')) {
return;
}
_.forEach(response.data.invalidAttributes,
function(attribute, attributeName) {
let warningMessage = '';
_.forEach(attribute, function(attributeError) {
warningMessage += (attributeError.message || '') + '<br />';
});
Notification.warning({
title: 'Invalid attribute: ' + attributeName,
message: warningMessage
});
});
};
/**
* Shows notifications detailing the various errors described by the
* response object
* @param {Object} response A response object returned by sails after a
* erroneous request.
* @param {String} errorTitle The string to be used as a title for the
* main error notification.
*/
var showErrors = function(response, errorTitle) {
if (!response) {
return Notification.error({
title: errorTitle,
message: UNKNOWN_ERROR_MESSAGE
});
}
Notification.error({
title: errorTitle,
message: response.summary || UNKNOWN_ERROR_MESSAGE
});
showAttributeWarnings(response);
};
/**
* Creates a version using the api.
* Requires authentication (token is auto-injected).
* @param {Object} version A object containing all of the parameters
* we would like to create the version with.
* @return {Promise} A promise which is resolve/rejected as
* soon as we know the result of the operation
* Contains the response object.
*/
self.createVersion = function(version) {
if (!version) {
throw new Error('A version object is required for creation');
}
const errorTitle = 'Unable to Create Version';
if (!version.availability) {
Notification.error({
title: errorTitle,
message: 'Availability date must be greater than or equal to the current date'
});
return $q.reject();
}
// Due to an API change in Sails/Waterline, the primary key values must be specified directly.
var version_for_request = version;
version_for_request.channel = version_for_request.channel.name;
version_for_request.flavor = version_for_request.flavor.name;
version_for_request.id = `${version_for_request.name}_${version_for_request.flavor}`;
return $http.post('/api/version', version_for_request)
.then(function(response) {
Notification.success('Version Created Successfully.');
return response;
}, function(response) {
showErrors(response, errorTitle);
return $q.reject(response);
});
};
/**
* Creates a flavor using the api.
* Requires authentication (token is auto-injected).
* @param {Object} flavor A object containing all of the parameters
* we would like to create the flavor with.
* @return {Promise} A promise which is resolve/rejected as
* soon as we know the result of the operation
* Contains the response object.
*/
self.createFlavor = flavor => {
if (!flavor) {
throw new Error('A flavor object is required for creation');
}
return $http.post('/api/flavor', flavor)
.then(
response => {
Notification.success('Flavor Created Successfully.');
return response;
},
response => {
showErrors(response, 'Unable to Create Flavor');
return $q.reject(response);
}
);
};
/**
* Updates a version using the api.
* Requires authentication (token is auto-injected).
* @param {Object} version A object containing all of the parameters
* we would like to update the version with.
* @return {Promise} A promise which is resolve/rejected as
* soon as we know the result of the operation
* Contains the response object.
*/
self.updateVersion = function(version) {
if (!version) {
throw new Error('A version object is required for updating');
}
const errorTitle = 'Unable to Update Version';
if (!version.availability) {
Notification.error({
title: errorTitle,
message: 'Availability date must be greater than or equal to the version creation date'
});
return $q.reject();
}
// Due to an API change in Sails/Waterline, the primary key values must be specified directly.
var version_for_request = _.omit(version, ['assets']);
version_for_request.channel = version_for_request.channel.name;
version_for_request.flavor = version_for_request.flavor.name;
return $http.post(
'/api/version/' + version.id,
version_for_request
)
.then(function(response) {
Notification.success('Version Updated Successfully.');
return response;
}, function(response) {
showErrors(response, errorTitle);
return $q.reject(response);
});
};
/**
* Deletes a version using the api.
* Requires authentication (token is auto-injected).
* @param {Object} versionId The id of the version that we would
* like to delete.
* @return {Promise} A promise which is resolve/rejected as
* soon as we know the result of the operation
* Contains the response object.
*/
self.deleteVersion = versionId => {
if (!versionId) {
throw new Error('A version id is required for deletion');
}
return $http.delete('/api/version/' + versionId)
.then(function success(response) {
Notification.success('Version Deleted Successfully.');
return response;
}, function error(response) {
var errorTitle = 'Unable to Delete Version';
showErrors(response, errorTitle);
return $q.reject(response);
});
};
/**
* Normalize the version object returned by sails over SocketIO.
* Note: Sails will not populate related models on update
* Specifically:
* - The channel parameter will sometimes only contain the channel name.
* - The assets parameter will not be included if empty.
* - The availability parameter will sometimes be dated before the createdAt date.
* @param {Object} version Unnormalized version object
* @return {Object} Normalized version object
*/
var normalizeVersion = function(version) {
if (!version) {
return;
}
if (_.isString(version.channel)) {
version.channel = {
name: version.channel
};
}
if (typeof version.flavor === 'string') {
version.flavor = {
name: version.flavor
};
}
if (!_.isArrayLike(version.assets)) {
version.assets = [];
}
if (new Date(version.availability) < new Date(version.createdAt)) {
version.availability = version.createdAt;
}
return version;
};
// Process new versions/modified pushed from the server over SocketIO
$sails.on('version', function(msg) {
if (!msg) {
return;
}
const version = normalizeVersion(msg.data || msg.previous);
var index;
const notificationMessage = version ? `${version.name} (${version.flavor.name})` : '';
if (msg.verb === 'created') {
self.data.unshift(version);
self.sortVersions();
$log.log('Sails sent a new version.');
Notification({
title: 'New Version Available',
message: notificationMessage
});
} else if (msg.verb === 'updated') {
Notification({
title: 'Version Updated',
message: notificationMessage
});
index = _.findIndex(self.data, {
id: version.id // Sails sends back the old id for us
});
if (index > -1) {
if (!version.assets || !version.assets.length) {
version.assets = self.data[index].assets;
}
self.data[index] = version;
}
$log.log('Sails updated a version.');
} else if (msg.verb === 'destroyed') {
index = _.findIndex(self.data, {
id: version.id
});
if (index > -1) {
self.data.splice(index, 1);
}
Notification({
title: 'Version Deleted',
message: notificationMessage
});
$log.log('Sails removed a version.');
}
PubSub.publish('data-change');
});
// Process create/delete events on flavors pushed from the server over SocketIO
$sails.on('flavor', msg => {
if (!msg) {
return;
}
if (msg.verb === 'created') {
$log.log('Sails sent a new flavor.');
self.availableFlavors = [msg.data.name, ...self.availableFlavors].sort();
Notification({
title: 'New Flavor Available',
message: msg.data.name
});
} else if (msg.verb === 'destroyed') {
$log.log('Sails removed a flavor.');
self.availableFlavors = self.availableFlavors
.filter(flavor => flavor !== msg.previous.name);
Notification({
title: 'Flavor Deleted',
message: msg.previous.name
});
}
PubSub.publish('data-change');
});
/**
* Creates a asset using the api, this handles the file upload, as part of
* the process.
* Requires authentication (token is auto-injected).
* @param {Object} asset A object containing all of the parameters
* we would like to create the asset with.
* @param {Object} versionId The id of the version that we would
* like to add this asset to.
* @return {Promise} A promise which is resolve/rejected as
* soon as we know the result of the operation
* Contains the response object.
*/
self.createAsset = function(asset, versionId) {
if (!asset) {
throw new Error('A asset object is required for creation');
}
if (!versionId) {
throw new Error('A version id is required for creation');
}
var deferred = $q.defer();
asset.upload = Upload.upload({
url: '/api/asset',
data: _.merge({
token: AuthService.getToken(),
version: versionId
}, asset)
});
asset.upload.then(function success(response) {
// Resolve the promise immediately as we already know it succeeded
deferred.resolve(response);
Notification.success({
message: 'Asset Created Successfully.'
});
}, function error(response) {
// Reject the promise immediately as we already know it failed
deferred.reject(response);
var errorTitle = 'Unable to Create Asset';
showErrors(response, errorTitle);
}, function progress(evt) {
// Math.min is to fix IE which reports 200% sometimes
asset.file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
return deferred.promise;
};
/**
* Updates a asset using the api.
* Requires authentication (token is auto-injected).
* @param {Object} asset A object containing all of the parameters we
* would like to update this asset with.
* Updating the asset's name is not an issue like
* with Versions, because assets are identified in
* the database by their id.
* @return {Promise} A promise which is resolve/rejected as soon as
* we know the result of the operation
* Contains the response object.
*/
self.updateAsset = function(asset) {
if (!asset) {
throw new Error('A asset object is required for updating');
}
if (!asset.id) {
throw new Error('The passed asset object must have been submitted to the database in order to be updated');
}
return $http.post('/api/asset/' + asset.id, asset)
.then(function(response) {
Notification.success('Asset Updated Successfully.');
return response;
}, function(response) {
var errorTitle = 'Unable to Update Asset';
showErrors(response, errorTitle);
return $q.reject(response);
});
};
/**
* Deletes an asset using the api.
* Requires authentication (token is auto-injected).
* @param {Object} name The name of the asset that we would like to
* delete.
* @return {Promise} A promise which is resolve/rejected as soon
* as we know the result of the operation
* Contains the response object.
*/
self.deleteAsset = function(name) {
if (!name) {
throw new Error('A asset name is required for deletion');
}
return $http.delete('/api/asset/' + name)
.then(function success(response) {
Notification.success('Asset Deleted Successfully.');
return response;
}, function error(response) {
var errorTitle = 'Unable to Delete Asset';
showErrors(response, errorTitle);
return $q.reject(response);
});
};
/**
* Normalize the asset object returned by sails over SocketIO.
* Note: Sails will not populate related models on update
* Specifically:
* - The version parameter will sometimes only contain the version id.
* @param {Object} asset Unnormalized asset object
* @return {Object} Normalized asset object
*/
var normalizeAsset = function(asset) {
if (!asset) {
return;
}
if (_.isString(asset.version)) {
asset.version = {
id: asset.version
};
}
return asset;
};
// Process new asset/modified pushed from the server over SocketIO
$sails.on('asset', function(msg) {
if (!msg) {
return;
}
$log.log('Asset Received', msg);
const asset = normalizeAsset(msg.data);
if (!asset && msg.verb !== 'destroyed') {
$log.log('No asset provided with message. Reloading data.');
return self.initialize();
}
var notificationMessage = (asset || {}).name || '';
var versionIndex, index;
if (msg.verb === 'created') {
versionIndex = _.findIndex(self.data, {
id: asset.version.id // Sails sends the version
});
if (versionIndex === -1) {
// Our version of the database is out of sync from the remote, re-init
$log.log('Data out of sync, reloading.');
return self.initialize();
}
self.data[versionIndex].assets.unshift(asset);
Notification({
title: 'New Asset Available',
message: notificationMessage
});
$log.log('Sails sent a new asset.');
} else if (msg.verb === 'updated') {
versionIndex = _.findIndex(self.data, function(version) {
index = _.findIndex(version.assets, {
id: msg.id // Sails sends back the old id for us
});
return index !== -1;
});
if (versionIndex === -1 || index === -1) {
// Our version of the database is out of sync from the remote, re-init
$log.log('Data out of sync, reloading.');
return self.initialize();
}
self.data[versionIndex].assets[index] = asset;
Notification({
title: 'Asset Updated',
message: notificationMessage
});
$log.log('Sails updated an asset.');
} else if (msg.verb === 'destroyed') {
versionIndex = _.findIndex(self.data, function(version) {
$log.log('Searching Version:', version);
index = _.findIndex(version.assets, {
id: msg.id // Sails sends back the old id for us
});
$log.log('result:', index);
return index !== -1;
});
if (versionIndex === -1 || index === -1) {
// Our version of the database is out of sync from remote, re-init
$log.log('Data out of sync, reloading.');
return self.initialize();
}
if (index > -1) {
self.data[versionIndex].assets.splice(index, 1);
}
Notification({
title: 'Asset Deleted',
message: msg.previous.name || ''
});
$log.log('Sails removed an asset.');
}
PubSub.publish('data-change');
});
/**
* Retrieve & subscribe to all versions, channels, flavors & asset data.
* @return {Promise} Resolved once data has been retrieved
*/
self.initialize = function() {
self.currentPage = 0;
self.loading = true;
self.hasMore = false;
return Promise.all([
// Get the initial set of releases from the server.
$sails.get('/versions/sorted', {
page: self.currentPage
}),
// Get available channels
$sails.get('/channels/sorted'),
// Get available flavors
$sails.get('/api/flavor'),
// Only sent to watch for asset updates
$sails.get('/api/asset'),
// Only sent to watch for version updates
$sails.get('/api/version')
])
.then(function(responses) {
const versions = responses[0];
const channels = responses[1];
const flavors = responses[2];
self.data = versions.data.items;
self.availableChannels = channels.data;
self.availableFlavors = flavors.data.map(flavor => flavor.name).sort();
self.currentPage++;
self.hasMore = versions.data.total > self.data.length;
self.loading = false;
PubSub.publish('data-change');
});
};
/**
* Determines if a version is available
* @param {Object} version Version object.
* @return {Boolean} True if the version is available, otherwise false.
*/
self.checkAvailability = version => new Date(version.availability) <= new Date();
self.loadMoreVersions = function() {
if (self.loading) {
return;
}
self.loading = true;
return $sails.get('/versions/sorted', {
page: self.currentPage
})
.then(function(versions) {
self.data = self.data.concat(versions.data.items);
self.currentPage++;
self.hasMore = versions.data.total > self.data.length;
self.loading = false;
PubSub.publish('data-change');
});
};
/**
* Returns information about the latest release available for a given
* platform + architecture, channel and flavor.
* @param {String} platform Target platform (osx, windows, linux)
* @param {Array} archs Target architectures ('32', '64')
* @param {String} channel Target release channel
* @param {String} flavor Target flavor
* @return {Object} Latest release data object
*/
self.getLatestReleases = (platform, archs, channel, flavor) => {
if (!self.availableChannels) {
return;
}
var channelIndex = self.availableChannels.indexOf(channel);
if (channelIndex === -1) {
return;
}
var applicableChannels = self.availableChannels.slice(
0,
channelIndex + 1
);
if (!self.availableFlavors || !self.availableFlavors.includes(flavor)) {
return;
}
var versions = _
.chain(self.data)
.filter(self.checkAvailability)
.filter(function(version) {
var versionChannel = _.get(version, 'channel.name');
return applicableChannels.indexOf(versionChannel) !== -1;
})
.filter(version => version.flavor.name === flavor)
.value();
var latestReleases = {};
_.forEach(archs, function(arch) {
var platformName = platform + '_' + arch;
var filetypes = self.filetypes[platformName];
if (!filetypes) {
return;
}
_.forEach(versions, function(version) {
_.forEach(version.assets, function(asset) {
if (
asset.platform === platformName &&
filetypes.includes(asset.filetype)
) {
var matchedAsset = _.clone(asset);
matchedAsset.version = version.name;
matchedAsset.notes = version.notes;
matchedAsset.channel = _.get(version, 'channel.name');
matchedAsset.flavor = version.flavor.name;
latestReleases[arch] = matchedAsset;
return false;
}
});
if (latestReleases[arch]) {
return false;
}
});
});
// If no archs matched, return undefined
if (_.size(latestReleases) === 0) {
return;
}
return latestReleases;
};
}
]);
``` | /content/code_sandbox/assets/js/core/data/data-service.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 4,994 |
```javascript
angular.module('app.core.auth.logout', [
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/auth/logout', {
templateUrl: 'js/core/auth/logout/logout.html',
controller: 'LogoutController',
data: {
private: false
}
});
}])
.controller('LogoutController', ['Notification', 'AuthService', '$location',
function(Notification, AuthService, $location) {
AuthService.logout();
Notification.success({
message: 'Logout Successful'
});
$location.path('/auth/login');
}
]);
``` | /content/code_sandbox/assets/js/core/auth/logout/logout-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 124 |
```javascript
angular.module('app.home', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'js/home/home.html',
controller: 'HomeController as vm'
});
}])
.controller('HomeController', ['$scope', 'PubSub', 'DataService',
function($scope, PubSub, DataService) {
}
]);
``` | /content/code_sandbox/assets/js/home/home-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 83 |
```javascript
angular.module('app.admin', [
'app.admin.version-table',
'app.admin.add-flavor-modal',
'app.admin.add-version-modal',
'app.admin.add-version-asset-modal',
'app.admin.edit-version-modal',
'app.admin.edit-version-asset-modal'
]);
``` | /content/code_sandbox/assets/js/admin/admin.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 62 |
```javascript
angular.module('app.admin.version-table', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/admin', {
templateUrl: 'js/admin/version-table/version-table.html',
controller: 'AdminVersionTableController',
data: {
private: true
}
});
}])
.controller('AdminVersionTableController', ['$scope', 'Notification', 'DataService','$uibModal', 'PubSub',
function($scope, Notification, DataService, $uibModal, PubSub) {
$scope.flavor = 'all';
$scope.showAllFlavors = true;
$scope.availableFlavors = DataService.availableFlavors && ['all', ...DataService.availableFlavors];
$scope.versions = DataService.data;
$scope.hasMoreVersions = DataService.hasMore;
$scope.filterVersionsByFlavor = () => {
$scope.showAllFlavors = $scope.flavor === 'all';
$scope.versions = $scope.showAllFlavors
? DataService.data
: DataService.data.filter(version => version.flavor.name === $scope.flavor);
};
$scope.openEditModal = version => {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'js/admin/edit-version-modal/edit-version-modal.html',
controller: 'EditVersionModalController',
resolve: {
version: () => version
}
});
modalInstance.result.then(function() {}, function() {});
};
$scope.openAddVersionModal = function() {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'js/admin/add-version-modal/add-version-modal.html',
controller: 'AddVersionModalController'
});
modalInstance.result.then(function() {}, function() {});
};
$scope.openAddFlavorModal = () => {
const modalInstance = $uibModal.open({
animation: true,
templateUrl: 'js/admin/add-flavor-modal/add-flavor-modal.html',
controller: 'AddFlavorModalController'
});
modalInstance.result.then(() => {}, () => {});
};
$scope.loadMoreVersions = function () {
DataService.loadMoreVersions();
};
// Watch for changes to data content and update local data accordingly.
var uid1 = PubSub.subscribe('data-change', function() {
$scope.filterVersionsByFlavor();
$scope.hasMoreVersions = DataService.hasMore;
$scope.availableFlavors = DataService.availableFlavors && ['all', ...DataService.availableFlavors];
});
$scope.$on('$destroy', function() {
PubSub.unsubscribe(uid1);
});
}
]);
``` | /content/code_sandbox/assets/js/admin/version-table/version-table-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 549 |
```javascript
angular.module('app.admin.add-flavor-modal', [])
.controller('AddFlavorModalController', ['$scope', 'DataService', '$uibModalInstance',
($scope, DataService, $uibModalInstance) => {
$scope.flavor = {
name: ''
};
$scope.addFlavor = () => {
DataService.createFlavor($scope.flavor)
.then(
$uibModalInstance.close,
() => {}
);
};
$scope.closeModal = $uibModalInstance.dismiss;
}
]);
``` | /content/code_sandbox/assets/js/admin/add-flavor-modal/add-flavor-modal-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 110 |
```javascript
angular.module('app.admin.add-version-modal', [])
.controller('AddVersionModalController', ['$scope', '$http', 'DataService', 'Notification', '$uibModalInstance', 'PubSub', 'moment',
($scope, $http, DataService, Notification, $uibModalInstance, PubSub, moment) => {
$scope.availableChannels = DataService.availableChannels;
$scope.currentDateTime = moment().startOf('second').toDate();
$scope.availableFlavors = DataService.availableFlavors;
$scope.version = {
id: '',
name: '',
notes: '',
channel: {
name: DataService.availableChannels[0]
},
availability: $scope.currentDateTime,
flavor: {
name: 'default'
}
};
$scope.addVersion = function() {
DataService.createVersion($scope.version)
.then(function success(response) {
$uibModalInstance.close();
}, function error(response) {});
};
$scope.closeModal = function() {
$uibModalInstance.dismiss();
};
// Watch for changes to data content and update local data accordingly.
var uid1 = PubSub.subscribe('data-change', function() {
$scope.availableChannels = DataService.availableChannels;
$scope.availableFlavors = DataService.availableFlavors;
$scope.version = {
id: '',
name: '',
notes: '',
channel: {
name: DataService.availableChannels[0]
},
availability: $scope.currentDateTime,
flavor: {
name: 'default'
}
};
});
$scope.$on('$destroy', function() {
PubSub.unsubscribe(uid1);
});
}
]);
``` | /content/code_sandbox/assets/js/admin/add-version-modal/add-version-modal-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 346 |
```javascript
angular.module('app.admin.edit-version-asset-modal', [])
.controller('EditVersionAssetModalController', ['$scope', 'DataService', 'Notification', '$uibModalInstance', 'asset',
function($scope, DataService, Notification, $uibModalInstance, asset) {
$scope.DataService = DataService;
$scope.originalName = asset.name;
$scope.fileType = asset.filetype && asset.filetype[0] === '.'
? asset.filetype.replace('.', '')
: asset.filetype;
// Clone so not to polute the original
$scope.asset = _.cloneDeep(asset);
$scope.acceptEdit = function() {
if (!$scope.asset.name) {
$scope.asset.name = $scope.originalName;
}
DataService.updateAsset($scope.asset)
.then(function success(response) {
$uibModalInstance.close();
}, function error(response) {});
};
$scope.deleteAsset = function() {
DataService.deleteAsset(asset.id)
.then(function success(response) {
$uibModalInstance.close();
}, function error(response) {});
};
$scope.closeModal = function() {
$uibModalInstance.dismiss();
};
}
]);
``` | /content/code_sandbox/assets/js/admin/edit-version-asset-modal/edit-version-asset-modal-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 247 |
```javascript
angular.module('app.admin.edit-version-modal', [])
.controller('EditVersionModalController', ['$scope', 'DataService', 'Notification', '$uibModalInstance', '$uibModal', 'version', 'moment',
($scope, DataService, Notification, $uibModalInstance, $uibModal, version, moment) => {
$scope.DataService = DataService;
// Clone so not to polute the original
$scope.version = _.cloneDeep(version);
$scope.version.availability = new Date(version.availability);
$scope.createdAt = new Date(version.createdAt);
$scope.isAvailable = DataService.checkAvailability(version);
/**
* Updates the modal's knowlege of this version's assets from the one
* maintained by DataService (which should be up to date with the server
* because of SocketIO's awesomeness.
*/
var updateVersionAssets = function() {
var updatedVersion = _.find(DataService.data, {
id: version.id
});
if (!updatedVersion) {
// The version no longer exists
return $uibModalInstance.close();
}
$scope.version.assets = updatedVersion.assets;
};
$scope.openAddAssetModal = function() {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'js/admin/add-version-asset-modal/add-version-asset-modal.html',
controller: 'AddVersionAssetModalController',
resolve: {
version: () => version
}
});
modalInstance.result.then(function() {
// An asset should have been added, so we will update our modal's
// knowledge of the version.
updateVersionAssets();
}, function() {});
};
$scope.openEditAssetModal = function(asset) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'js/admin/edit-version-asset-modal/edit-version-asset-modal.html',
controller: 'EditVersionAssetModalController',
resolve: {
asset: function() {
return asset;
}
}
});
modalInstance.result.then(function() {
// An asset should have been modified or deleted, so we will update
// our modal's knowledge of the version.
updateVersionAssets();
}, function() {});
};
$scope.acceptEdit = function() {
DataService.updateVersion($scope.version)
.then(function success(response) {
$uibModalInstance.close();
}, () => {
if (!$scope.version.availability) {
$scope.version.availability = new Date(version.availability);
}
});
};
$scope.makeAvailable = () => {
const updatedVersion = {
...$scope.version,
availability: moment().startOf('second').toDate()
};
DataService
.updateVersion(updatedVersion)
.then($uibModalInstance.close, () => {});
};
$scope.deleteVersion = function() {
DataService.deleteVersion(version.id)
.then(function success(response) {
$uibModalInstance.close();
}, function error(response) {});
};
$scope.closeModal = function() {
$uibModalInstance.dismiss();
};
}
]);
``` | /content/code_sandbox/assets/js/admin/edit-version-modal/edit-version-modal-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 654 |
```javascript
angular.module('app.admin.add-version-asset-modal', [])
.controller('AddVersionAssetModalController', ['$scope', 'DataService', '$uibModalInstance', 'version',
($scope, DataService, $uibModalInstance, version) => {
$scope.DataService = DataService;
$scope.versionName = version.name;
$scope.versionIsAvailable = DataService.checkAvailability(version);
$scope.asset = {
name: '',
platform: '',
file: null
};
$scope.addAsset = function() {
if (!$scope.asset.name) {
delete $scope.asset.name;
}
DataService.createAsset($scope.asset, version.id)
.then(function success(response) {
$uibModalInstance.close();
}, function error(response) {
$uibModalInstance.dismiss();
});
};
$scope.updateAssetName = () => {
$scope.namePlaceholder = $scope.asset.file && $scope.asset.file.name;
};
$scope.closeModal = function() {
$uibModalInstance.dismiss();
};
}
]);
``` | /content/code_sandbox/assets/js/admin/add-version-asset-modal/add-version-asset-modal-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 218 |
```javascript
angular.module('app.releases', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/releases/:channel?/:flavor?', {
templateUrl: 'js/download/download.html',
controller: 'DownloadController as vm'
});
}])
.controller('DownloadController', [
'$scope', '$routeParams', '$route', 'PubSub', 'deviceDetector',
'DataService',
function(
$scope, $routeParams, $route, PubSub, deviceDetector, DataService
) {
var self = this;
self.showAllVersions = false;
$scope.hasMoreVersions = DataService.hasMore;
self.platform = deviceDetector.os;
if (self.platform === 'mac') {
self.platform = 'osx';
self.archs = ['64', 'arm64'];
} else {
self.archs = ['32', '64'];
}
self.setRouteParams = (channel, flavor) => {
$route.updateParams({
channel,
flavor
});
};
self.availablePlatforms = DataService.availablePlatforms;
self.filetypes = DataService.filetypes;
self.availableChannels = DataService.availableChannels;
self.availableFlavors = DataService.availableFlavors;
// Get selected channel from route or set to default (stable)
self.channel = $routeParams.channel || (self.availableChannels && self.availableChannels[0]) || 'stable';
// Get selected flavor from route or set to default (default)
self.flavor = $routeParams.flavor || 'default';
self.latestReleases = null;
self.downloadUrl = null;
self.getLatestReleases = function() {
self.setRouteParams(
self.channel,
self.flavor
);
self.latestReleases = DataService.getLatestReleases(
self.platform,
self.archs,
self.channel,
self.flavor
);
self.versions = DataService.data
.filter(DataService.checkAvailability)
.filter(version => version.flavor.name === self.flavor);
};
// Watch for changes to data content and update local data accordingly.
var uid1 = PubSub.subscribe('data-change', function() {
self.getLatestReleases();
self.availableChannels = DataService.availableChannels;
self.availableFlavors = DataService.availableFlavors;
$scope.hasMoreVersions = DataService.hasMore;
});
// Update knowledge of the latest available versions.
self.getLatestReleases();
self.download = function(asset, versionName, flavorName) {
if (!asset) {
return;
}
const { flavor, version, platform, name } = asset;
self.downloadUrl =
`/download/flavor/${flavorName || flavor}/${versionName || version}/${platform}/${name}`;
};
$scope.$on('$destroy', function() {
PubSub.unsubscribe(uid1);
});
$scope.loadMoreVersions = function () {
DataService.loadMoreVersions();
};
}
]);
``` | /content/code_sandbox/assets/js/download/download-controller.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 623 |
```javascript
/**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files.)
*/
// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
// to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
'styles/**/*.css'
];
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
'js/main.js',
// All of the rest of your client-side js files
// will be injected here in no particular order.
'js/**/*.js'
];
// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you. If you want to use pug, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file. Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
'templates/**/*.html'
];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(function(path) {
return '.tmp/public/' + path;
});
module.exports.jsFilesToInject = jsFilesToInject.map(function(path) {
return '.tmp/public/' + path;
});
module.exports.templateFilesToInject = templateFilesToInject.map(function(path) {
return 'assets/' + path;
});
``` | /content/code_sandbox/tasks/pipeline.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 448 |
```javascript
/**
* Precompiles Underscore templates to a `.jst` file.
*
* ---------------------------------------------------------------
*
* (i.e. basically it takes HTML files and turns them into tiny little
* javascript functions that you pass data to and return HTML. This can
* speed up template rendering on the client, and reduce bandwidth usage.)
*
* For usage docs see:
* path_to_url
*
*/
module.exports = function(grunt) {
grunt.config.set('jst', {
dev: {
// To use other sorts of templates, specify a regexp like the example below:
// options: {
// templateSettings: {
// interpolate: /\{\{(.+?)\}\}/g
// }
// },
// Note that the interpolate setting above is simply an example of overwriting lodash's
// default interpolation. If you want to parse templates with the default _.template behavior
// (i.e. using <div></div>), there's no need to overwrite `templateSettings.interpolate`.
files: {
// e.g.
// 'relative/path/from/gruntfile/to/compiled/template/destination' : ['relative/path/to/sourcefiles/**/*.html']
'.tmp/public/jst.js': require('../pipeline').templateFilesToInject
}
}
});
grunt.loadNpmTasks('grunt-contrib-jst');
};
``` | /content/code_sandbox/tasks/config/jst.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 306 |
```javascript
/**
* Concatenate files.
*
* ---------------------------------------------------------------
*
* Concatenates files javascript and css from a defined array. Creates concatenated files in
* .tmp/public/contact directory
* [concat](path_to_url
*
* For usage docs see:
* path_to_url
*/
module.exports = function(grunt) {
grunt.config.set('concat', {
js: {
src: require('../pipeline').jsFilesToInject,
dest: '.tmp/public/concat/production.js'
},
css: {
src: require('../pipeline').cssFilesToInject,
dest: '.tmp/public/concat/production.css'
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
};
``` | /content/code_sandbox/tasks/config/concat.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 153 |
```javascript
/**
* Compile CoffeeScript files to JavaScript.
*
* ---------------------------------------------------------------
*
* Compiles coffeeScript files from `assest/js` into Javascript and places them into
* `.tmp/public/js` directory.
*
* For usage docs see:
* path_to_url
*/
module.exports = function(grunt) {
grunt.config.set('coffee', {
dev: {
options: {
bare: true,
sourceMap: true,
sourceRoot: './'
},
files: [{
expand: true,
cwd: 'assets/js/',
src: ['**/*.coffee'],
dest: '.tmp/public/js/',
ext: '.js'
}, {
expand: true,
cwd: 'assets/js/',
src: ['**/*.coffee'],
dest: '.tmp/public/js/',
ext: '.js'
}]
}
});
grunt.loadNpmTasks('grunt-contrib-coffee');
};
``` | /content/code_sandbox/tasks/config/coffee.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 202 |
```javascript
/**
* Clean files and folders.
*
* ---------------------------------------------------------------
*
* This grunt task is configured to clean out the contents in the .tmp/public of your
* sails project.
*
* For usage docs see:
* path_to_url
*/
module.exports = function(grunt) {
grunt.config.set('clean', {
dev: ['.tmp/public/**'],
build: ['www']
});
grunt.loadNpmTasks('grunt-contrib-clean');
};
``` | /content/code_sandbox/tasks/config/clean.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 94 |
```javascript
/**
* Run predefined tasks whenever watched file patterns are added, changed or deleted.
*
* ---------------------------------------------------------------
*
* Watch for changes on
* - files in the `assets` folder
* - the `tasks/pipeline.js` file
* and re-run the appropriate tasks.
*
* For usage docs see:
* path_to_url
*
*/
module.exports = function(grunt) {
grunt.config.set('watch', {
api: {
// API files to watch:
files: ['api/**/*', '!**/node_modules/**']
},
assets: {
// Assets to watch:
files: ['assets/**/*', 'tasks/pipeline.js', '!**/node_modules/**'],
// When assets are changed:
tasks: ['syncAssets' , 'linkAssets']
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
};
``` | /content/code_sandbox/tasks/config/watch.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 189 |
```javascript
/**
* Minify files with UglifyJS.
*
* ---------------------------------------------------------------
*
* Minifies client-side javascript `assets`.
*
* For usage docs see:
* path_to_url
*
*/
module.exports = function(grunt) {
grunt.config.set('uglify', {
dist: {
src: ['.tmp/public/concat/production.js'],
dest: '.tmp/public/min/production.min.js'
}
});
grunt.loadNpmTasks('grunt-contrib-uglify-es');
};
``` | /content/code_sandbox/tasks/config/uglify.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 104 |
```javascript
/**
* Copy files and folders.
*
* ---------------------------------------------------------------
*
* # dev task config
* Copies all directories and files, exept coffescript and less fiels, from the sails
* assets folder into the .tmp/public directory.
*
* # build task config
* Copies all directories nd files from the .tmp/public directory into a www directory.
*
* For usage docs see:
* path_to_url
*/
module.exports = function(grunt) {
grunt.config.set('copy', {
dev: {
files: [{
expand: true,
cwd: './assets',
src: ['**/*.!(coffee|less)'],
dest: '.tmp/public'
}]
},
build: {
files: [{
expand: true,
cwd: '.tmp/public',
src: ['**/*'],
dest: 'www'
}]
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
};
``` | /content/code_sandbox/tasks/config/copy.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 204 |
```javascript
module.exports = function(grunt) {
grunt.config.set('pug', {
dev: {
options: {},
files: [{
expand: true,
cwd: 'assets/',
src: '**/*.pug',
dest: '.tmp/public/',
ext: '.html'
}]
}
});
grunt.loadNpmTasks('grunt-contrib-pug');
};
``` | /content/code_sandbox/tasks/config/pug.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 84 |
```javascript
module.exports = function(grunt) {
grunt.config.set('wiredep', {
task: {
// Point to the files that should be updated when
// you run 'grunt wiredep'
src: [
'views/**/*.pug', // .pug support...
],
// We need this line so injection is correct path
ignorePath: '../assets',
options: {
// See wiredep's configuration documentation for the options
// you may pass:
// path_to_url#configuration
}
}
});
grunt.loadNpmTasks('grunt-wiredep');
};
``` | /content/code_sandbox/tasks/config/wiredep.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 131 |
```javascript
/**
* A grunt task to keep directories in sync. It is very similar to grunt-contrib-copy
* but tries to copy only those files that has actually changed.
*
* ---------------------------------------------------------------
*
* Synchronize files from the `assets` folder to `.tmp/public`,
* smashing anything that's already there.
*
* For usage docs see:
* path_to_url
*
*/
module.exports = function(grunt) {
grunt.config.set('sync', {
dev: {
files: [{
cwd: './assets',
src: ['**/*.!(coffee)'],
dest: '.tmp/public'
}]
}
});
grunt.loadNpmTasks('grunt-sync');
};
``` | /content/code_sandbox/tasks/config/sync.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 143 |
```javascript
/**
* Compress CSS files.
*
* ---------------------------------------------------------------
*
* Minifies css files and places them into .tmp/public/min directory.
*
* For usage docs see:
* path_to_url
*/
module.exports = function(grunt) {
grunt.config.set('cssmin', {
dist: {
src: ['.tmp/public/concat/production.css'],
dest: '.tmp/public/min/production.min.css'
}
});
grunt.loadNpmTasks('grunt-contrib-cssmin');
};
``` | /content/code_sandbox/tasks/config/cssmin.js | javascript | 2016-02-28T10:06:53 | 2024-08-15T05:19:37 | electron-release-server | ArekSredzki/electron-release-server | 2,072 | 105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.