/// <summary>Sets the image list.</summary> /// <param name="list">The list.</param> /// <exception cref="Logic::ArgumentNullException">List is nullptr</exception> void DualComboBox::SetImageList(CImageList* list) { REQUIRED(list); // Replace image list Images = list; }
/// <summary>Populates the library from the string library</summary> /// <param name="data">Feedback data</param> /// <returns>Number of objects found</returns> /// <exception cref="Logic::ArgumentNullException">Worker data is null</exception> /// <exception cref="Logic::InvalidOperationException">String library is empty</exception> UINT ScriptObjectLibrary::Enumerate(WorkerData* data) { REQUIRED(data); // Ensure string library exists if (StringLib.Files.empty()) throw InvalidOperationException(HERE, L"String library has not been enumerated"); // Feedback data->SendFeedback(Cons::Heading, ProgressType::Operation, 1, L"Generating script objects from language files"); // Populate Clear(); Populate(data); // DEBUG: Console << "Discovered " << (int)Objects.size() << " script objects..." << ENDL; // Feedback number of conflicts if (Objects.size() - Lookup.size() > 1) // Always 1 less in lookup because old [THIS] intentionally removed data->SendFeedback(Cons::Error, ProgressType::Error, 2, VString(L"Unable to process %d script objects", Objects.size()-Lookup.size()-1)); // Feedback object count data->SendFeedback(ProgressType::Info, 2, VString(L"Loaded %d script objects", Lookup.size())); return Lookup.size(); }
/// <summary>Displays modal dialog</summary> /// <param name="w">Worker to monitor.</param> /// <returns></returns> /// <exception cref="Logic::ArgumentNullException">Worker is null</exception> INT_PTR ProgressDialog::DoModal(BackgroundWorker* w) { REQUIRED(w); Worker = w; return CDialogEx::DoModal(); }
/// <summary>Determines whether path has a given extension (case insensitive)</summary> /// <param name="ext">The extention preceeded by a dot</param> /// <returns></returns> /// <exception cref="Logic::ArgumentNullException">Path is null</exception> bool Path::HasExtension(const WCHAR* ext) const { REQUIRED(ext); // Optimization for usage with literals return StrCmpI(PathFindExtension(Buffer.get()), ext) == 0; }
/// <summary>Writes/encodes the specified buffer to the stream</summary> /// <param name="buffer">The buffer.</param> /// <param name="length">The length of the buffer.</param> /// <returns>Number of bytes written</returns> /// <exception cref="Logic::ArgumentNullException">Buffer is null</exception> /// <exception cref="Logic::NotSupportedException">Stream is not writeable</exception> /// <exception cref="Logic::IOException">An I/O error occurred</exception> DWORD EncryptedX3Stream::Write(const BYTE* buffer, DWORD length) { REQUIRED(buffer); DWORD keylen = 0; // Init: Generate key and write to first byte if (DECRYPT_KEY == 0 && length > 0) { // Verify position if (StreamDecorator::GetPosition() != 0) throw IOException(HERE, L"First write operation must be positioned at start of stream"); // Generate/write key DECRYPT_KEY = buffer[0] ^ DECRYPT_SEED; StreamDecorator::Write(&DECRYPT_KEY, 1); keylen = 1; } // Copy buffer so we can encode it ByteArrayPtr copy(new BYTE[length]); memcpy(copy.get(), buffer, length); // Encode + Write Encode(copy.get(), length); return StreamDecorator::Write(copy.get(), length) + keylen; }
/// <summary>Reads/decodes from the stream into the specified buffer.</summary> /// <param name="buffer">The destination buffer</param> /// <param name="length">The length of the buffer</param> /// <returns>Number of bytes read</returns> /// <exception cref="Logic::ArgumentNullException">Buffer is null</exception> /// <exception cref="Logic::NotSupportedException">Stream is not readable</exception> /// <exception cref="Logic::IOException">An I/O error occurred</exception> DWORD EncryptedX3Stream::Read(BYTE* buffer, DWORD length) { REQUIRED(buffer); // Init: Generate key from 1st byte if (DECRYPT_KEY == 0) { // Read first byte DWORD origin = StreamDecorator::GetPosition(); StreamDecorator::Seek(0, SeekOrigin::Begin); StreamDecorator::Read(&DECRYPT_KEY, 1); StreamDecorator::Seek(origin, SeekOrigin::Begin); // Generate key DECRYPT_KEY ^= DECRYPT_SEED; } // Skip reading first byte if (StreamDecorator::GetPosition() == 0) StreamDecorator::Seek(1, SeekOrigin::Begin); // Read+decode buffer DWORD bytesRead = StreamDecorator::Read(buffer, length); Encode(buffer, bytesRead); // Return length return bytesRead; }
bool InputManager::processKeyState(LSHandle* handle, LSMessage* msg, void* userData) { // {"get": string} VALIDATE_SCHEMA_AND_RETURN(handle, msg, SCHEMA_1(REQUIRED(get, string))); bool success = false; const char* keyString = NULL; QEvent::Type state = QEvent::None; LSError err; json_object* root = 0; LSErrorInit(&err); // get the text name of the key const char* str = LSMessageGetPayload(msg); if (!str) { g_debug("%s: Unable to get JSON payload from message", __PRETTY_FUNCTION__); return false; } root = json_tokener_parse(str); if (root && !is_error(root)) { // Get the key name from the msg -- the format will be {"get":"NAME"}, // where NAME is something like ringer, slider, etc keyString = json_object_get_string(json_object_object_get(root, "get")); if (keyString) { // lookup the state of the key Qt::Key key = stringToKey(keyString); state = getKeyState(key); success = true; } } json_object* response = 0; if (success) { response = createKeyJson(keyString, state); } else { response = json_object_new_object(); } json_object_object_add(response, "returnValue", json_object_new_boolean(success)); if (!LSMessageReply(handle, msg, json_object_to_json_string(response), &err)) { LSErrorPrint(&err, stderr); LSErrorFree(&err); } if (root && !is_error(root)) json_object_put(root); json_object_put(response); return true; }
/// <summary>Creates a MAX_PATH char array buffer containing a path</summary> /// <param name="path">The initial path</param> /// <returns></returns> /// <exception cref="Logic::ArgumentNullException">Path is null</exception> CharArrayPtr Path::Init(const WCHAR* path) { REQUIRED(path); CharArrayPtr ptr(new WCHAR[MAX_PATH+1]); StringCchCopy(ptr.get(), MAX_PATH, path); return ptr; }
/// <summary>Assigns the specified path</summary> /// <param name="path">The path</param> /// <returns>this</returns> /// <exception cref="Logic::ArgumentNullException">Path is null</exception> Path& Path::Assign(const WCHAR* path) { REQUIRED(path); // Ensure not self-assignment if (path != Buffer.get()) StringCchCopy(Buffer.get(), MAX_PATH, path); return *this; }
static bool cbComPalmImage2Status(LSHandle* lsHandle, LSMessage *message, void *user_data) { LSError lsError; LSErrorInit(&lsError); // {"serviceName": string, "connected": boolean} VALIDATE_SCHEMA_AND_RETURN(lsHandle, message, SCHEMA_2(REQUIRED(serviceName, string), REQUIRED(connected, boolean))); json_object * root = 0; const char* str = LSMessageGetPayload(message); if( !str ) return false; root = json_tokener_parse(str); if ((root == NULL) || (is_error(root))) { root = NULL; return true; } json_object * label = Utils::JsonGetObject(root,"connected"); if (label != NULL) { if (json_object_get_boolean(label) == true) { //image2 is available Settings::settings()->m_image2svcAvailable = true; } else { Settings::settings()->m_image2svcAvailable = false; } } else { Settings::settings()->m_image2svcAvailable = false; } json_object_put(root); return true; }
/// <summary>Creates a string reader from an input stream</summary> /// <param name="src">The input stream</param> /// <exception cref="Logic::ArgumentException">Stream is not readable</exception> /// <exception cref="Logic::ArgumentNullException">Stream is null</exception> /// <exception cref="Logic::IOException">An I/O error occurred</exception> StringReader::StringReader(StreamPtr src) : Input(src), Position(0), Buffer(nullptr), LineNum(1) { REQUIRED(src); // Ensure stream has read access if (!Input->CanRead()) throw ArgumentException(HERE, L"src", GuiString(ERR_NO_READ_ACCESS)); // Lookup stream length Length = Input->GetLength(); }
void recognized_function (const cpp_token *fname, unsigned int line, int kind, int have_arg_list) { struct partial_proto *partial; int i; struct fn_decl *fn; fn = lookup_std_proto ((const char *) NODE_NAME (fname->val.node), NODE_LEN (fname->val.node)); /* Remove the function from the list of required function. */ if (fn) { if (REQUIRED (fn)) required_unseen_count--; SET_SEEN (fn); } /* If we have a full prototype, we're done. */ if (have_arg_list) return; if (kind == 'I') /* don't edit inline function */ return; /* If the partial prototype was included from some other file, we don't need to patch it up (in this run). */ i = strlen (cur_file); if (i < inc_filename_length || strcmp (inc_filename, cur_file + (i - inc_filename_length)) != 0) return; if (fn == NULL) return; if (fn->params[0] == '\0') return; /* We only have a partial function declaration, so remember that we have to add a complete prototype. */ partial_count++; partial = obstack_alloc (&scan_file_obstack, sizeof (struct partial_proto)); partial->line_seen = line; partial->fn = fn; fn->partial = partial; partial->next = partial_proto_list; partial_proto_list = partial; if (verbose) { fprintf (stderr, "(%s: %s non-prototype function declaration.)\n", inc_filename, fn->fname); } }
/// <summary>Reads/decodes from the stream into the specified buffer.</summary> /// <param name="buffer">The destination buffer</param> /// <param name="length">The length of the buffer</param> /// <returns>Number of bytes read</returns> /// <exception cref="Logic::ArgumentNullException">Buffer is null</exception> /// <exception cref="Logic::NotSupportedException">Stream is not readable</exception> /// <exception cref="Logic::IOException">An I/O error occurred</exception> DWORD CatalogStream::Read(BYTE* buffer, DWORD length) { REQUIRED(buffer); // Preserve origin, fill buffer DWORD startPos = GetPosition(), bytesRead = StreamDecorator::Read(buffer, length); // Encode buffer + return Encode(buffer, bytesRead, startPos); return bytesRead; }
/// <summary>Writes/encodes the specified buffer to the stream</summary> /// <param name="buffer">The buffer.</param> /// <param name="length">The length of the buffer.</param> /// <returns>Number of bytes written</returns> /// <exception cref="Logic::ArgumentNullException">Buffer is null</exception> /// <exception cref="Logic::NotSupportedException">Stream is not writeable</exception> /// <exception cref="Logic::IOException">An I/O error occurred</exception> DWORD CatalogStream::Write(const BYTE* buffer, DWORD length) { REQUIRED(buffer); // Copy buffer so we can encode it ByteArrayPtr copy(new BYTE[length]); memcpy(copy.get(), buffer, length); // Encode + Write Encode(copy.get(), length, GetPosition()); return StreamDecorator::Write(copy.get(), length); }
static void recognized_macro (const char *fname) { /* The original include file defines fname as a macro. */ struct fn_decl *fn = lookup_std_proto (fname, strlen (fname)); /* Since fname is a macro, don't require a prototype for it. */ if (fn) { if (REQUIRED (fn)) required_unseen_count--; SET_SEEN (fn); } switch (special_file_handling) { case errno_h: if (strcmp (fname, "errno") == 0 && !seen_errno) seen_errno = 1, required_other--; break; case stdlib_h: if (strcmp (fname, "EXIT_FAILURE") == 0 && !seen_EXIT_FAILURE) seen_EXIT_FAILURE = 1, required_other--; if (strcmp (fname, "EXIT_SUCCESS") == 0 && !seen_EXIT_SUCCESS) seen_EXIT_SUCCESS = 1, required_other--; break; case sys_stat_h: if (fname[0] == 'S' && fname[1] == '_') { if (strcmp (fname, "S_IFBLK") == 0) seen_S_IFBLK++; else if (strcmp (fname, "S_ISBLK") == 0) seen_S_ISBLK++; else if (strcmp (fname, "S_IFCHR") == 0) seen_S_IFCHR++; else if (strcmp (fname, "S_ISCHR") == 0) seen_S_ISCHR++; else if (strcmp (fname, "S_IFDIR") == 0) seen_S_IFDIR++; else if (strcmp (fname, "S_ISDIR") == 0) seen_S_ISDIR++; else if (strcmp (fname, "S_IFIFO") == 0) seen_S_IFIFO++; else if (strcmp (fname, "S_ISFIFO") == 0) seen_S_ISFIFO++; else if (strcmp (fname, "S_IFLNK") == 0) seen_S_IFLNK++; else if (strcmp (fname, "S_ISLNK") == 0) seen_S_ISLNK++; else if (strcmp (fname, "S_IFREG") == 0) seen_S_IFREG++; else if (strcmp (fname, "S_ISREG") == 0) seen_S_ISREG++; } break; default: break; } }
/// <summary>Writes a revision</summary> /// <param name="r">Revision.</param> /// <param name="parent">root node.</param> /// <exception cref="Logic::ArgumentNullException">Parent is nullptr</exception> void BackupFileWriter::WriteRevision(const ScriptRevision& r, XmlElementPtr& parent) { REQUIRED(parent); // <revision title="third revision" date="2013-03-12 18:00:00" path="D:\X3 Albion Prelude\scripts\plugin.piracy.lib.logic.xml"> auto node = WriteElement(parent, L"revision"); WriteAttribute(node, L"title", r.Title); WriteAttribute(node, L"date", (LPCWSTR)r.Date.Format(L"%Y-%m-%d %H:%M:%S")); // yyyy-mm-dd hh:mm:ss WriteAttribute(node, L"path", r.FullPath.c_str()); // <scriptname>plugin.piracy.lib.logic</scriptname> // <version>102</version> // <game>X3TC</game> // <description>Piracy logic library</description> // <command>1019</command> // <text>* Validate Parameters...</text> WriteElement(node, L"scriptname", r.ScriptName); WriteElement(node, L"version", VString(L"%d", r.Version)); WriteElement(node, L"game", VersionString(r.Game, true)); WriteElement(node, L"description", r.Description); WriteElement(node, L"command", VString(L"%d", r.CommandID)); WriteElement(node, L"text", r.Content); }
/* * main */ int main(int argc, char *argv[]) { #ifdef _NDSTOOL_P_H if (sizeof(Header) != 0x200) { fprintf(stderr, "Header size %d != %d\n", sizeof(Header), 0x200); return 1; } #endif if (argc < 2) { Help(); return 0; } int num_actions = 0; int actions[MAX_ACTIONS]; /* * parse parameters to actions */ for (int a=1; a<argc; a++) { if (argv[a][0] == '-') { switch (argv[a][1]) { case 'i': // show information { ADDACTION(ACTION_SHOWINFO); OPTIONAL(ndsfilename); break; } case 'f': // fix header CRC { ADDACTION(ACTION_FIXHEADERCRC); OPTIONAL(ndsfilename); break; } case 's': // en-/decrypt secure area { ADDACTION(ACTION_ENCRYPTSECUREAREA); endecrypt_option = argv[a][2]; OPTIONAL(ndsfilename); break; } case 'l': // list files { ADDACTION(ACTION_LISTFILES); OPTIONAL(ndsfilename); break; } case 'x': // extract { ADDACTION(ACTION_EXTRACT); OPTIONAL(ndsfilename); break; } case 'w': // wildcard filemasks { while (1) { char *filemask = 0; OPTIONAL(filemask); if (!(filemasks[filemask_num] = filemask)) break; if (++filemask_num >= MAX_FILEMASKS) return 1; } break; } case 'c': // create { ADDACTION(ACTION_CREATE); OPTIONAL(ndsfilename); break; } // file root directory case 'd': REQUIRED(filerootdir); break; // ARM7 filename case '7': if (argv[a][2] == 'i') { REQUIRED(arm7ifilename); } else { REQUIRED(arm7filename); } break; // ARM9 filename case '9': if (argv[a][2] == 'i') { REQUIRED(arm9ifilename); } else { REQUIRED(arm9filename); } break; // hook ARM7 executable case 'k': { ADDACTION(ACTION_HOOK); OPTIONAL(ndsfilename); break; } case 't': REQUIRED(bannerfilename); bannertype = BANNER_BINARY; break; case 'b': bannertype = BANNER_IMAGE; REQUIRED(bannerfilename); REQUIRED(bannertext); break; case 'o': REQUIRED(logofilename); break; case 'h': // load header or header size REQUIRED(headerfilename_or_size); break; /*case 'u': // unique ID file REQUIRED(uniquefilename); break;*/ case 'u': // DSi title ID high word if (argc > a) titleidHigh = strtoul(argv[++a], 0, 16); break; case 'z': // SCFG access flags if (argc > a) scfgExtMask = strtoul(argv[++a], 0, 16); break; case 'a': // DSi access control flags if (argc > a) accessControl = strtoul(argv[++a], 0, 16); break; case 'p': // DSi application flags if (argc > a) appFlags = strtoul(argv[++a], 0, 16) & 0xFF; break; case 'v': // verbose for (char *p=argv[a]; *p; p++) if (*p == 'v') verbose++; OPTIONAL(romlistfilename); break; case 'n': // latency //compatibility = true; OPTIONAL_INT(latency1); OPTIONAL_INT(latency2); break; case 'r': // RAM address switch (argv[a][2]) { case '7': arm7RamAddress = (argc > a) ? strtoul(argv[++a], 0, 0) : 0; break; case '9': arm9RamAddress = (argc > a) ? strtoul(argv[++a], 0, 0) : 0; break; default: Help(argv[a]); return 1; } break; case 'e': // entry point switch (argv[a][2]) { case '7': arm7Entry = (argc > a) ? strtoul(argv[++a], 0, 0) : 0; break; case '9': arm9Entry = (argc > a) ? strtoul(argv[++a], 0, 0) : 0; break; default: Help(argv[a]); return 1; } break; case 'm': // maker code REQUIRED(makercode); break; case 'g': // game code REQUIRED(gamecode); OPTIONAL(makercode); OPTIONAL(title); OPTIONAL_INT(romversion); break; case 'y': // overlay table file / directory switch (argv[a][2]) { case '7': REQUIRED(arm7ovltablefilename); break; case '9': REQUIRED(arm9ovltablefilename); break; case 0: REQUIRED(overlaydir); break; default: Help(argv[a]); return 1; } break; case '?': // global or specific help { Help(argv[a][2] ? argv[a]+2 : 0); // 0=global help return 0; // do not perform any other actions } default: { Help(argv[a]); return 1; } } } else { //Help(); if (ndsfilename) { fprintf(stderr, "NDS filename is already given!\n"); return 1; } ndsfilename = argv[a]; break; } } Title(); /* * sanity checks */ if (gamecode) { if (strlen(gamecode) != 4) { fprintf(stderr, "Game code must be 4 characters!\n"); return 1; } for (int i=0; i<4; i++) if ((gamecode[i] >= 'a') && (gamecode[i] <= 'z')) { fprintf(stderr, "Warning: Gamecode contains lowercase characters.\n"); break; } if (gamecode[0] == 'A') { fprintf(stderr, "Warning: Gamecode starts with 'A', which might be used for another commercial product.\n"); } } if (makercode && (strlen(makercode) != 2)) { fprintf(stderr, "Maker code must be 2 characters!\n"); return 1; } if (title && (strlen(title) > 12)) { fprintf(stderr, "Title can be no more than 12 characters!\n"); return 1; } if (romversion > 255) { fprintf(stderr, "romversion can only be 0 - 255!\n"); return 1; } /* * perform actions */ int status = 0; for (int i=0; i<num_actions; i++) { //printf("action %d\n", actions[i]); switch (actions[i]) { case ACTION_SHOWINFO: ShowInfo(ndsfilename); break; case ACTION_FIXHEADERCRC: FixHeaderCRC(ndsfilename); break; case ACTION_EXTRACT: fNDS = fopen(ndsfilename, "rb"); if (!fNDS) { fprintf(stderr, "Cannot open file '%s'.\n", ndsfilename); exit(1); } fread(&header, 512, 1, fNDS); fclose(fNDS); printf("9i %s, 7i %s, unitcode %x\n",arm9ifilename,arm7ifilename, header.unitcode); if (arm9filename) Extract(arm9filename, true, 0x20, true, 0x2C, true); if (arm7filename) Extract(arm7filename, true, 0x30, true, 0x3C); if (header.unitcode & 2) { if (arm9ifilename) Extract(arm9ifilename, true, 0x1C0, true, 0x1CC, true); if (arm7ifilename) Extract(arm7ifilename, true, 0x1D0, true, 0x1DC); } if (bannerfilename) Extract(bannerfilename, true, 0x68, false, 0x840); if (headerfilename_or_size) Extract(headerfilename_or_size, false, 0x0, false, 0x200); if (logofilename) Extract(logofilename, false, 0xC0, false, 156); // *** bin only if (arm9ovltablefilename) Extract(arm9ovltablefilename, true, 0x50, true, 0x54); if (arm7ovltablefilename) Extract(arm7ovltablefilename, true, 0x58, true, 0x5C); if (overlaydir) ExtractOverlayFiles(); if (filerootdir) ExtractFiles(ndsfilename); break; case ACTION_CREATE: Create(); break; case ACTION_LISTFILES: filerootdir = 0; /*status =*/ ExtractFiles(ndsfilename); break; case ACTION_HOOK: { Hook(ndsfilename, arm7filename); break; } case ACTION_ENCRYPTSECUREAREA: { /*status =*/ EnDecryptSecureArea(ndsfilename, endecrypt_option); break; } } } return (status < 0) ? 1 : 0; }
// http://msdn.microsoft.com/en-us/library/ms725481.aspx bool TimeZoneService::cbGetTimeZoneFromEasData(LSHandle* lsHandle, LSMessage *message, void *user_data) { std::string reply; bool ret; LSError lsError; json_object* root = 0; json_object* label = 0; int easBias; EasSystemTime easStandardDate; int easStandardBias; EasSystemTime easDaylightDate; int easDaylightBias; LSErrorInit(&lsError); easBias = 0; easStandardDate.valid = false; easStandardBias = 0; easDaylightDate.valid = false; easDaylightBias = 0; // {"bias": integer, standardDate:{"year": integer, "month": integer, "dayOfWeek": integer, "day": integer, "hour": integer, "minute": integer, "second": integer}, "standardBias": integer, "daylightDate":{"year": integer, "month": integer, "dayOfWeek": integer, "day": integer, "hour": integer, "minute": integer, "second": integer}, "daylightBias": integer} VALIDATE_SCHEMA_AND_RETURN(lsHandle, message, SCHEMA_5(REQUIRED(bias, integer), NAKED_OBJECT_OPTIONAL_7(standardDate, year, integer, month, integer, dayOfWeek, integer, day, integer, hour, integer, minute, integer, second, integer), OPTIONAL(standardBias, integer), NAKED_OBJECT_OPTIONAL_7(daylightDate, year, integer, month, integer, dayOfWeek, integer, day, integer, hour, integer, minute, integer, second, integer),OPTIONAL(daylightBias, integer))); const char* payload = LSMessageGetPayload(message); if (!payload) { reply = "{\"returnValue\": false, " " \"errorText\": \"No payload specifed for message\"}"; goto Done; } root = json_tokener_parse(payload); if (!root || is_error(root)) { reply = "{\"returnValue\": false, " " \"errorText\": \"Cannot parse json payload\"}"; goto Done; } // bias. mandatory (everything else is optional) label = json_object_object_get(root, "bias"); if (!label || !json_object_is_type(label, json_type_int)) { reply = "{\"returnValue\": false, " " \"errorText\": \"bias value missing\"}"; goto Done; } easBias = json_object_get_int(label); // standard date label = json_object_object_get(root, "standardDate"); if (label && json_object_is_type(label, json_type_object)) readEasDate(label, easStandardDate); // standard bias label = json_object_object_get(root, "standardBias"); if (label && json_object_is_type(label, json_type_int)) easStandardBias = json_object_get_int(label); // daylight date label = json_object_object_get(root, "daylightDate"); if (label && json_object_is_type(label, json_type_object)) readEasDate(label, easDaylightDate); // daylight bias label = json_object_object_get(root, "daylightBias"); if (label && json_object_is_type(label, json_type_int)) easDaylightBias = json_object_get_int(label); // Both standard and daylight bias need to specified together, // otherwise both are invalid if (!easDaylightDate.valid) easStandardDate.valid = false; if (!easStandardDate.valid) easDaylightDate.valid = false; { // Get all timezones matching the current offset PrefsHandler* handler = PrefsFactory::instance()->getPrefsHandler("timeZone"); TimePrefsHandler* tzHandler = static_cast<TimePrefsHandler*>(handler); TimeZoneService* tzService = TimeZoneService::instance(); std::list<std::string> timeZones = tzHandler->getTimeZonesForOffset(-easBias); if (timeZones.empty()) { reply = "{\"returnValue\": false, " " \"errorText\": \"Failed to find any timezones with specified bias value\"}"; goto Done; } if (!easStandardDate.valid) { // No additional data available for refinement. Just use the // first timezone entry in the list json_object* obj = json_object_new_object(); json_object_object_add(obj, "returnValue", json_object_new_boolean(true)); json_object_object_add(obj, "timeZone", json_object_new_string(timeZones.begin()->c_str())); reply = json_object_to_json_string(obj); json_object_put(obj); goto Done; } else { time_t utcTime = time(NULL); struct tm* localTime = localtime(&utcTime); int currentYear = localTime->tm_year + 1900; updateEasDateDayOfMonth(easStandardDate, currentYear); updateEasDateDayOfMonth(easDaylightDate, currentYear); for (std::list<std::string>::const_iterator it = timeZones.begin(); it != timeZones.end(); ++it) { TimeZoneEntry tzEntry; tzEntry.tz = (*it); tzEntry.years.push_back(currentYear); TimeZoneResultList tzResultList = tzService->getTimeZoneRuleOne(tzEntry); if (tzResultList.empty()) continue; const TimeZoneResult& tzResult = tzResultList.front(); printf("For timezone: %s\n", tzEntry.tz.c_str()); printf("year: %d, utcOffset: %lld, dstOffset: %lld, dstStart: %lld, dstEnd: %lld\n", tzResult.year, tzResult.utcOffset, tzResult.dstOffset, tzResult.dstStart, tzResult.dstEnd); // Set this timezone as the current timezone, so that we can calculate when the // DST transitions occurs in seconds for the specified eas data setenv("TZ", tzEntry.tz.c_str(), 1); struct tm tzBrokenTime; tzBrokenTime.tm_sec = easStandardDate.second; tzBrokenTime.tm_min = easStandardDate.minute; tzBrokenTime.tm_hour = easStandardDate.hour; tzBrokenTime.tm_mday = easStandardDate.day; tzBrokenTime.tm_mon = easStandardDate.month - 1; tzBrokenTime.tm_year = currentYear - 1900; tzBrokenTime.tm_wday = 0; tzBrokenTime.tm_yday = 0; tzBrokenTime.tm_isdst = 1; time_t easStandardDateSeconds = ::mktime(&tzBrokenTime); tzBrokenTime.tm_sec = easDaylightDate.second; tzBrokenTime.tm_min = easDaylightDate.minute; tzBrokenTime.tm_hour = easDaylightDate.hour; tzBrokenTime.tm_mday = easDaylightDate.day; tzBrokenTime.tm_mon = easDaylightDate.month - 1; tzBrokenTime.tm_year = currentYear - 1900; tzBrokenTime.tm_wday = 0; tzBrokenTime.tm_yday = 0; tzBrokenTime.tm_isdst = 0; time_t easDaylightDateSeconds = ::mktime(&tzBrokenTime); printf("eas dstStart: %ld, dstEnd: %ld\n", easDaylightDateSeconds, easStandardDateSeconds); if (easStandardDateSeconds == tzResult.dstEnd && easDaylightDateSeconds == tzResult.dstStart) { // We have a winner json_object* obj = json_object_new_object(); json_object_object_add(obj, "returnValue", json_object_new_boolean(true)); json_object_object_add(obj, "timeZone", json_object_new_string(tzEntry.tz.c_str())); reply = json_object_to_json_string(obj); json_object_put(obj); goto Done; } } reply = "{\"returnValue\": false, " " \"errorText\": \"Failed to find any timezones with specified parametes\"}"; } } Done: ret = LSMessageReply(lsHandle, message, reply.c_str(), &lsError); if (!ret) LSErrorFree(&lsError); if (root && !is_error(root)) json_object_put(root); return true; }
/// <summary>Compares the path with another</summary> /// <param name="path">The path to compare against</param> /// <returns></returns> /// <exception cref="Logic::ArgumentNullException">Path is null</exception> int Path::Compare(const WCHAR* path) const { REQUIRED(path); return StrCmpI(Buffer.get(), path); }
/// <summary>Saves the document</summary> /// <param name="szPath">The new/existing path.</param> /// <returns></returns> BOOL ScriptDocument::OnSaveDocument(LPCTSTR szPath) { WorkerData data(Operation::LoadSaveDocument); try { REQUIRED(szPath); // Clear output pane theApp.GetMainWindow()->ClearOutputPane(Operation::LoadSaveDocument, true); // Feedback Console << Cons::UserAction << "Saving script: " << Path(szPath) << ENDL; data.SendFeedback(ProgressType::Operation, 0, VString(L"Saving script '%s'", szPath)); // Parse script ScriptParser parser(Script, Edit->GetAllLines(), Script.Game); // Compile if (parser.Successful) parser.Compile(); // Verified/Compiled OK: if (parser.Successful) { // IncrementVersion: if (PrefsLib.IncrementOnSave) Script.Version++; // Disable change detection DetectChanges(false, GetView()); // Write script ScriptFileWriter w(XFileInfo(szPath).OpenWrite()); w.Write(Script); w.Close(); // Re-Enable change detection DetectChanges(true, GetView()); // Remove 'Modified' flag SetModifiedFlag(FALSE); // Feedback data.SendFeedback(ProgressType::Succcess, 0, L"Script saved successfully"); // Auto-Commit: Commit if document part of project if (auto proj = ProjectDocument::GetActive()) if (PrefsLib.CommitOnSave && proj->Contains(FullPath)) OnCommitDocument(L"Automatic commit"); return TRUE; } else { // Display compiler output window theApp.GetMainWindow()->ActivateOutputPane(Operation::LoadSaveDocument, true); // DEBUG: Print tree //parser.Print(); // Feedback messages in output window for (const auto& err : parser.Errors) { Console << err << ENDL; // Feedback to output VString msg(L"%d: %s '%s'", err.Line, err.Message.c_str(), err.Text.c_str()); data.SendFeedback(ProgressType::Error, 1, msg); } // Feedback data.SendFeedback(Cons::Error, ProgressType::Failure, 0, L"Failed to save script"); return FALSE; } } catch (ExceptionBase& e) { Console.Log(HERE, e, VString(L"Failed to save script '%s'", szPath)); data.SendFeedback(Cons::Error, ProgressType::Failure, 0, L"Failed to save script"); return FALSE; } }
//static bool ImageServices::lsEzResize(LSHandle* lsHandle, LSMessage* message,void* user_data) { LSError lserror; LSErrorInit(&lserror); std::string errorText; json_object * root = NULL; json_object * label = NULL; const char* str; std::string srcfile; std::string destfile; std::string desttype; uint32_t destSizeW = 0; uint32_t destSizeH = 0; // {"src": string, "dest": string, "destType": string, "destSizeW": integer, "destSizeH": integer} VALIDATE_SCHEMA_AND_RETURN(lsHandle, message, SCHEMA_5(REQUIRED(src, string), REQUIRED(dest, string), REQUIRED(destType, string), REQUIRED(destSizeW, integer), REQUIRED(destSizeH, integer))); ImageServices * pImgSvc = instance(); if (pImgSvc == NULL) { errorText = "Image Service has not started"; goto Done_ezResize; } if (pImgSvc->isValid() == false) { errorText = "Image Service has not started (failed init)"; goto Done_ezResize; } str = LSMessageGetPayload( message ); if (!str) { errorText = "No payload provided"; goto Done_ezResize; } root = json_tokener_parse( str ); if (!root || is_error(root)) { errorText = "Malformed JSON detected in payload"; root = 0; goto Done_ezResize; } if (Utils::extractFromJson(root,"src",srcfile) == false) { errorText = "'src' parameter missing"; goto Done_ezResize; } if (Utils::extractFromJson(root,"dest",destfile) == false) { errorText = "'dest' parameter missing"; goto Done_ezResize; } if (Utils::extractFromJson(root,"destType",desttype) == false) { errorText = "'destType' parameter missing"; goto Done_ezResize; } if ((label = Utils::JsonGetObject(root,"destSizeW")) != NULL) { destSizeW = json_object_get_int(label); } else { errorText = "'destSizeW' missing"; goto Done_ezResize; } if ((label = Utils::JsonGetObject(root,"destSizeH")) != NULL) { destSizeH = json_object_get_int(label); } else { errorText = "'destSizeH' missing"; goto Done_ezResize; } (void)ImageServices::instance()->ezResize(srcfile, destfile, desttype.c_str(), destSizeW, destSizeH, errorText); Done_ezResize: if (root) json_object_put(root); json_object * reply = json_object_new_object(); json_object_object_add(reply, "subscribed", json_object_new_boolean(false)); if (errorText.size() > 0) { json_object_object_add(reply, "returnValue", json_object_new_boolean(false)); json_object_object_add(reply, "errorCode", json_object_new_string(errorText.c_str())); } else { json_object_object_add(reply, "returnValue", json_object_new_boolean(true)); } if (!LSMessageReply(lsHandle, message, json_object_to_json_string(reply), &lserror)) LSErrorFree (&lserror); json_object_put(reply); return true; }
static int validate_args(args_t * args) { assert(args != NULL); if (args->cmd == c_ERROR) { usage(false); UNEXPECTED("no command specified, please " "see --help for details\n"); return -1; } if (args->poffset == NULL) { UNEXPECTED("--partition-offset is required for all '%s' " "commands", args->short_name); return -1; } if (args->target == NULL) { UNEXPECTED("--target is required for all '%s' commands", args->short_name); return -1; } #define REQUIRED(name,cmd) ({ \ if (args->name == NULL) { \ UNEXPECTED("--%s is required for the --%s command", \ #name, #cmd); \ return -1; \ } \ }) #define UNSUPPORTED(name,cmd) ({ \ if (args->name != NULL) { \ UNEXPECTED("--%s is unsupported for the --%s command", \ #name, #cmd); \ return -1; \ } \ }) if (args->cmd == c_CREATE) { REQUIRED(size, create); REQUIRED(block, create); REQUIRED(target, create); UNSUPPORTED(offset, create); UNSUPPORTED(flags, create); UNSUPPORTED(value, create); UNSUPPORTED(pad, create); } else if (args->cmd == c_ADD) { REQUIRED(name, add); REQUIRED(flags, add); if (args->logical != f_LOGICAL) { REQUIRED(size, add); REQUIRED(offset, add); } UNSUPPORTED(block, add); UNSUPPORTED(value, add); } else if (args->cmd == c_DELETE) { REQUIRED(name, delete); UNSUPPORTED(size, delete); UNSUPPORTED(offset, delete); UNSUPPORTED(block, delete); UNSUPPORTED(flags, delete); UNSUPPORTED(value, delete); UNSUPPORTED(pad, delete); } else if (args->cmd == c_LIST) {
bool AmbientLightSensor::controlStatus(LSHandle *sh, LSMessage *message, void *ctx) { #if defined (TARGET_DEVICE) LSError lserror; LSErrorInit(&lserror); bool result = true; AmbientLightSensor *als = (AmbientLightSensor*)ctx; // {"subscribe":boolean, "disableALS" : boolean} VALIDATE_SCHEMA_AND_RETURN(sh, message, SCHEMA_2(REQUIRED(subscribe, boolean), REQUIRED(disableALS, boolean))); g_debug ("%s: received '%s;", __PRETTY_FUNCTION__, LSMessageGetPayload(message)); bool subscribed = false; result = LSSubscriptionProcess (sh, message, &subscribed, &lserror); if(!result) { LSErrorFree (&lserror); result = true; subscribed = false; } if (subscribed) { als->m_alsSubscriptions++; als->on (); bool disable = false; const char* str = LSMessageGetPayload(message); if (str) { json_object* root = json_tokener_parse(str); if (root && !is_error(root)) { result = true; disable = json_object_get_boolean(json_object_object_get(root, "disableALS")); json_object_put(root); } } if (disable) als->m_alsDisabled++; } int ptr = (als->m_alsPointer + als->m_alsSamplesNeeded - 1) % als->m_alsSamplesNeeded; gchar *status = g_strdup_printf ("{\"returnValue\":true,\"current\":%i,\"average\":%i,\"disabled\":%s,\"subscribed\":%s}", als->m_alsValue[ptr], als->m_alsSum / als->m_alsSamplesNeeded, als->m_alsDisabled > 0 ? "true" : "false", subscribed ? "true" : "false"); if (NULL != status) result = LSMessageReply(sh, message, status, &lserror); if(!result) { LSErrorPrint (&lserror, stderr); LSErrorFree (&lserror); } g_free(status); #endif return true; }
//static bool ImageServices::lsImageInfo(LSHandle* lsHandle, LSMessage* message,void* user_data) { LSError lserror; LSErrorInit(&lserror); std::string errorText; json_object * root = NULL; const char* str; std::string srcfile; int srcWidth; int srcHeight; int srcBpp; const char* srcType; // {"src": string} VALIDATE_SCHEMA_AND_RETURN(lsHandle, message, SCHEMA_1(REQUIRED(src, string))); ImageServices * pImgSvc = instance(); if (pImgSvc == NULL) { errorText = "Image Service has not started"; goto Done_lsImageInfo; } if (pImgSvc->isValid() == false) { errorText = "Image Service has not started (failed init)"; goto Done_lsImageInfo; } str = LSMessageGetPayload( message ); if (!str) { errorText = "No payload provided"; goto Done_lsImageInfo; } root = json_tokener_parse( str ); if (!root || is_error(root)) { errorText = "Malformed JSON detected in payload"; root = 0; goto Done_lsImageInfo; } if (Utils::extractFromJson(root,"src",srcfile) == false) { errorText = "'src' parameter missing"; goto Done_lsImageInfo; } { QImageReader reader(QString::fromStdString(srcfile)); if(!reader.canRead()) { errorText = reader.errorString().toStdString(); return false; goto Done_lsImageInfo; } srcWidth = reader.size().width(); srcHeight = reader.size().height(); // QImageReader probably won't return all of these, but just to make sure we cover all cases switch(reader.imageFormat()) { case QImage::Format_ARGB32_Premultiplied: case QImage::Format_ARGB32: case QImage::Format_RGB32: srcBpp = 32; break; case QImage::Format_RGB888: case QImage::Format_RGB666: case QImage::Format_ARGB8565_Premultiplied: case QImage::Format_ARGB6666_Premultiplied: case QImage::Format_ARGB8555_Premultiplied: srcBpp = 24; break; case QImage::Format_RGB444: case QImage::Format_ARGB4444_Premultiplied: case QImage::Format_RGB16: case QImage::Format_RGB555: srcBpp = 16; break; case QImage::Format_Indexed8: srcBpp = 8; break; case QImage::Format_Mono: case QImage::Format_MonoLSB: srcBpp = 1; break; default: srcBpp = 0; } srcType = reader.format(); // png/jpg etc } Done_lsImageInfo: if (root) json_object_put(root); json_object * reply = json_object_new_object(); json_object_object_add(reply, "subscribed", json_object_new_boolean(false)); if (errorText.size() > 0) { json_object_object_add(reply, "returnValue", json_object_new_boolean(false)); json_object_object_add(reply, "errorCode", json_object_new_string(errorText.c_str())); } else { json_object_object_add(reply, "returnValue", json_object_new_boolean(true)); json_object_object_add(reply, "width",json_object_new_int(srcWidth)); json_object_object_add(reply, "height",json_object_new_int(srcHeight)); json_object_object_add(reply, "bpp",json_object_new_int(srcBpp)); json_object_object_add(reply, "type", json_object_new_string(srcType)); } if (!LSMessageReply(lsHandle, message, json_object_to_json_string(reply), &lserror)) LSErrorFree (&lserror); json_object_put(reply); return true; }