text
stringlengths
54
60.6k
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <globals.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <iostream.h> #include "Instrument.h" #include "rt.h" #include "rtdefs.h" #include <notetags.h> #include <sndlibsupport.h> #include <bus.h> #include <assert.h> Instrument :: Instrument() { start = 0.0; dur = 0.0; cursamp = 0; chunksamps = 0; endsamp = 0; nsamps = 0; chunkstart = 0; output_offset = 0; sfile_on = 0; // default is no input soundfile fdIndex = NO_DEVICE_FDINDEX; fileOffset = 0; inputsr = 0.0; inputchans = 0; outputchans = 0; // FIXME: not clear we need inbuf - better to leave it on run method's stack? inbuf = NULL; outbuf = NULL; bus_config = NULL; if (tags_on) { pthread_mutex_lock(&pfieldLock); for (int i = 0; i < MAXPUPS; i++) // initialize this element pupdatevals[curtag][i] = NOPUPDATE; mytag = curtag++; if (curtag >= MAXPUPARR) curtag = 1; // wrap it around // 0 is reserved for all-note rtupdates pthread_mutex_unlock(&pfieldLock); } } Instrument :: ~Instrument() { if (sfile_on) gone(); // decrement input soundfile reference delete [] inbuf; delete [] outbuf; // FIXME: Also... // Call something that decrements refcount for bus_config, and if that // reaches zero, and is no longer the most recent for that instname, // then delete that bus_config node. } // Set the bus_config pointer to the right bus_config for this inst. // Then set the inputchans and outputchans members accordingly. // // Instruments *must* call this from within their makeINSTNAME method. E.g., // // WAVETABLE *inst = new WAVETABLE(); // inst->set_bus_config("WAVETABLE"); // void Instrument :: set_bus_config(const char *inst_name) { bus_config = get_bus_config(inst_name); inputchans = bus_config->in_count + bus_config->auxin_count; outputchans = bus_config->out_count + bus_config->auxout_count; } int Instrument :: init(float p[], short n_args) { cout << "You haven't defined an init member of your Instrument class!" << endl; return -1; } // Instruments *must* call this at the beginning of their run methods, // like this: // // Instrument::run(); // // This method allocates the instrument's private interleaved output buffer // and inits a buffer status array. // Note: We allocate here, rather than in ctor or init method, because this // will mean less memory overhead before the inst begins playing. // int Instrument :: run() { if (outbuf == NULL) outbuf = new BUFTYPE [RTBUFSAMPS * outputchans]; obufptr = outbuf; #ifdef NOTYET for (int i = 0; i < outputchans; i++) bufstatus[i] = 0; #endif return 0; } void Instrument :: exec() { run(); } // Replacement for the old rtaddout (in rtaddout.C, now removed). // This one copies (not adds) into the inst's outbuf. Later the // schedular calls the insts addout method to add outbuf into the // appropriate output buses. Inst's *must* call the class run method // before doing their own run stuff. (This is true even if they don't // use rtaddout.) // Assumes that <samps> contains exactly outputchans interleaved samples. // Returns outputchans (i.e., number of samples written). // int Instrument :: rtaddout(BUFTYPE samps[]) { for (int i = 0; i < outputchans; i++) *obufptr++ = samps[i]; } // Add signal from one channel of instrument's private interleaved buffer // into the specified output bus. // void Instrument :: addout(BusType bus_type, int bus) { int samp, endframe, src_chan, buses; short *bus_list; BufPtr src, dest; assert(bus >= 0 && bus < MAXBUS); if (bus_type == BUS_AUX_OUT) { dest = aux_buffer[bus]; buses = bus_config->auxout_count; bus_list = bus_config->auxout; } else { // BUS_OUT dest = out_buffer[bus]; buses = bus_config->out_count; bus_list = bus_config->out; } src_chan = -1; for (int i = 0; i < buses; i++) { if (bus_list[i] == bus) { src_chan = i; break; } } assert(src_chan != -1); assert(dest != NULL); endframe = output_offset + chunksamps; samp = src_chan; // FIXME: pthread_mutex_lock dest buffer for (int frame = output_offset; frame < endframe; frame++) { dest[frame] += outbuf[samp]; samp += outputchans; } // FIXME: pthread_mutex_unlock dest buffer } float Instrument :: getstart() { return start; } float Instrument :: getdur() { return dur; } int Instrument :: getendsamp() { return endsamp; } void Instrument :: setendsamp(int end) { endsamp = end; } void Instrument :: setchunk(int csamps) { chunksamps = csamps; } void Instrument :: setchunkstart(int csamps) { chunkstart = csamps; } void Instrument :: set_output_offset(int offset) { output_offset = offset; } // If the reference count on the file referenced by the instrument // reaches zero, close the input soundfile and set the state to // make sure this is obvious // void Instrument :: gone() { #ifdef DEBUG printf("Instrument::gone(this=0x%x): index %d refcount = %d\n", this, fdIndex, inputFileTable[fdIndex].refcount); #endif // BGG -- added this to prevent file closings in interactive mode // we don't know if a file will be referenced again in the future if (!rtInteractive) { if (fdIndex >= 0 && --inputFileTable[fdIndex].refcount <= 0) { if (inputFileTable[fdIndex].fd > 0) { #ifdef DEBUG printf("\tclosing fd %d\n", inputFileTable[fdIndex].fd); #endif clm_close(inputFileTable[fdIndex].fd); } if (inputFileTable[fdIndex].filename); free(inputFileTable[fdIndex].filename); inputFileTable[fdIndex].filename = NULL; inputFileTable[fdIndex].fd = NO_FD; inputFileTable[fdIndex].header_type = unsupported_sound_file; inputFileTable[fdIndex].data_format = snd_unsupported; inputFileTable[fdIndex].data_location = 0; inputFileTable[fdIndex].srate = 0.0; inputFileTable[fdIndex].chans = 0; inputFileTable[fdIndex].dur = 0.0; fdIndex = -1; } } } <commit_msg>Make rtaddout return number of samps written. Minor cleanup in addout method. Misc. reformatting for clarity.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <globals.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <iostream.h> #include "Instrument.h" #include "rt.h" #include "rtdefs.h" #include <notetags.h> #include <sndlibsupport.h> #include <bus.h> #include <assert.h> /* ----------------------------------------------------------- Instrument --- */ Instrument :: Instrument() { start = 0.0; dur = 0.0; cursamp = 0; chunksamps = 0; endsamp = 0; nsamps = 0; chunkstart = 0; output_offset = 0; sfile_on = 0; // default is no input soundfile fdIndex = NO_DEVICE_FDINDEX; fileOffset = 0; inputsr = 0.0; inputchans = 0; outputchans = 0; // FIXME: not clear we need inbuf - better to leave it on run method's stack? inbuf = NULL; outbuf = NULL; bus_config = NULL; if (tags_on) { pthread_mutex_lock(&pfieldLock); for (int i = 0; i < MAXPUPS; i++) // initialize this element pupdatevals[curtag][i] = NOPUPDATE; mytag = curtag++; if (curtag >= MAXPUPARR) curtag = 1; // wrap it around // 0 is reserved for all-note rtupdates pthread_mutex_unlock(&pfieldLock); } } /* ---------------------------------------------------------- ~Instrument --- */ Instrument :: ~Instrument() { if (sfile_on) gone(); // decrement input soundfile reference delete [] inbuf; delete [] outbuf; // FIXME: Also... // Call something that decrements refcount for bus_config, and if that // reaches zero, and is no longer the most recent for that instname, // then delete that bus_config node. } /* ------------------------------------------------------- set_bus_config --- */ /* Set the bus_config pointer to the right bus_config for this inst. Then set the inputchans and outputchans members accordingly. Instruments *must* call this from within their makeINSTNAME method. E.g., WAVETABLE *inst = new WAVETABLE(); inst->set_bus_config("WAVETABLE"); */ void Instrument :: set_bus_config(const char *inst_name) { bus_config = get_bus_config(inst_name); inputchans = bus_config->in_count + bus_config->auxin_count; outputchans = bus_config->out_count + bus_config->auxout_count; } /* ----------------------------------------------------------------- init --- */ int Instrument :: init(float p[], short n_args) { cout << "You haven't defined an init member of your Instrument class!" << endl; return -1; } /* ------------------------------------------------------------------ run --- */ /* Instruments *must* call this at the beginning of their run methods, like this: Instrument::run(); This method allocates the instrument's private interleaved output buffer and inits a buffer status array. Note: We allocate here, rather than in ctor or init method, because this will mean less memory overhead before the inst begins playing. */ int Instrument :: run() { if (outbuf == NULL) outbuf = new BUFTYPE [RTBUFSAMPS * outputchans]; obufptr = outbuf; #ifdef NOTYET for (int i = 0; i < outputchans; i++) bufstatus[i] = 0; #endif return 0; } /* ----------------------------------------------------------------- exec --- */ void Instrument :: exec() { run(); } /* ------------------------------------------------------------- rtaddout --- */ /* Replacement for the old rtaddout (in rtaddout.C, now removed). This one copies (not adds) into the inst's outbuf. Later the scheduler calls the insts addout method to add outbuf into the appropriate output buses. Inst's *must* call the class run method before doing their own run stuff. (This is true even if they don't use rtaddout.) Assumes that <samps> contains exactly outputchans interleaved samples. Returns outputchans (i.e., number of samples written). */ int Instrument :: rtaddout(BUFTYPE samps[]) { for (int i = 0; i < outputchans; i++) *obufptr++ = samps[i]; return outputchans; } /* --------------------------------------------------------------- addout --- */ /* Add signal from one channel of instrument's private interleaved buffer into the specified output bus. */ void Instrument :: addout(BusType bus_type, int bus) { int samp_index, endframe, src_chan, buses; short *bus_list; BufPtr src, dest; assert(bus >= 0 && bus < MAXBUS); if (bus_type == BUS_AUX_OUT) { dest = aux_buffer[bus]; buses = bus_config->auxout_count; bus_list = bus_config->auxout; } else { /* BUS_OUT */ dest = out_buffer[bus]; buses = bus_config->out_count; bus_list = bus_config->out; } src_chan = -1; for (int i = 0; i < buses; i++) { if (bus_list[i] == bus) { src_chan = i; break; } } assert(src_chan != -1); assert(dest != NULL); endframe = output_offset + chunksamps; samp_index = src_chan; // FIXME: pthread_mutex_lock dest buffer for (int frame = output_offset; frame < endframe; frame++) { dest[frame] += outbuf[samp_index]; samp_index += outputchans; } // FIXME: pthread_mutex_unlock dest buffer } /* ------------------------------------------------------------- getstart --- */ float Instrument :: getstart() { return start; } /* --------------------------------------------------------------- getdur --- */ float Instrument :: getdur() { return dur; } /* ----------------------------------------------------------- getendsamp --- */ int Instrument :: getendsamp() { return endsamp; } /* ----------------------------------------------------------- setendsamp --- */ void Instrument :: setendsamp(int end) { endsamp = end; } /* ------------------------------------------------------------- setchunk --- */ void Instrument :: setchunk(int csamps) { chunksamps = csamps; } /* -------------------------------------------------------- setchunkstart --- */ void Instrument :: setchunkstart(int csamps) { chunkstart = csamps; } /* ---------------------------------------------------- set_output_offset --- */ void Instrument :: set_output_offset(int offset) { output_offset = offset; } /* ----------------------------------------------------------------- gone --- */ /* If the reference count on the file referenced by the instrument reaches zero, close the input soundfile and set the state to make sure this is obvious. */ void Instrument :: gone() { #ifdef DEBUG printf("Instrument::gone(this=0x%x): index %d refcount = %d\n", this, fdIndex, inputFileTable[fdIndex].refcount); #endif // BGG -- added this to prevent file closings in interactive mode // we don't know if a file will be referenced again in the future if (!rtInteractive) { if (fdIndex >= 0 && --inputFileTable[fdIndex].refcount <= 0) { if (inputFileTable[fdIndex].fd > 0) { #ifdef DEBUG printf("\tclosing fd %d\n", inputFileTable[fdIndex].fd); #endif clm_close(inputFileTable[fdIndex].fd); } if (inputFileTable[fdIndex].filename); free(inputFileTable[fdIndex].filename); inputFileTable[fdIndex].filename = NULL; inputFileTable[fdIndex].fd = NO_FD; inputFileTable[fdIndex].header_type = unsupported_sound_file; inputFileTable[fdIndex].data_format = snd_unsupported; inputFileTable[fdIndex].data_location = 0; inputFileTable[fdIndex].srate = 0.0; inputFileTable[fdIndex].chans = 0; inputFileTable[fdIndex].dur = 0.0; fdIndex = -1; } } } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ /* The set_option function, called from a script, lets the user override default options (and those stored in the .rtcmixrc file). The options are kept in the <options> object (see Option.h). -JGG, 6/30/04 */ #include <RTcmix.h> #include <ugens.h> // for die() #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <Option.h> enum ParamType { AUDIO, PLAY, RECORD, CLOBBER, PRINT, REPORT_CLIPPING, CHECK_PEAKS, FULL_DUPLEX, EXIT_ON_ERROR, AUTO_LOAD, BUFFER_FRAMES, BUFFER_COUNT, DEVICE, INDEVICE, OUTDEVICE, MIDI_INDEVICE, MIDI_OUTDEVICE, DSOPATH, RCNAME }; #define OPT_STRLEN 128 struct Param { char arg[OPT_STRLEN]; ParamType type; bool value; // use false if not relevant, i.e. for key=value style }; static Param _param_list[] = { // These are key=value option strings. Please list these in the order in // which they appear in Option.h, to make it easier to compare. { kOptionAudio, AUDIO, false}, { kOptionPlay, PLAY, false}, { kOptionRecord, RECORD, false}, { kOptionClobber, CLOBBER, false}, { kOptionPrint, PRINT, false}, { kOptionReportClipping, REPORT_CLIPPING, false}, { kOptionCheckPeaks, CHECK_PEAKS, false}, { kOptionExitOnError, EXIT_ON_ERROR, false}, { kOptionAutoLoad, AUTO_LOAD, false}, { kOptionBufferFrames, BUFFER_FRAMES, false}, { kOptionBufferCount, BUFFER_COUNT, false}, { kOptionDevice, DEVICE, false}, { kOptionInDevice, INDEVICE, false}, { kOptionOutDevice, OUTDEVICE, false}, { kOptionMidiInDevice, MIDI_INDEVICE, false}, { kOptionMidiOutDevice, MIDI_OUTDEVICE, false}, { kOptionDSOPath, DSOPATH, false}, { kOptionRCName, RCNAME, false}, // These are old-style, single value, option strings. { "AUDIO_ON", AUDIO, true}, { "AUDIO_OFF", AUDIO, false}, { "RECORD_ON", RECORD, true}, { "RECORD_OFF", RECORD, false}, { "PLAY_ON", AUDIO, true}, { "PLAY_OFF", AUDIO, false}, { "CLOBBER_ON", CLOBBER, true}, { "CLOBBER_OFF", CLOBBER, false}, { "REPORT_CLIPPING_ON", REPORT_CLIPPING, true}, { "REPORT_CLIPPING_OFF", REPORT_CLIPPING, false}, { "CHECK_PEAKS_ON", CHECK_PEAKS, true}, { "CHECK_PEAKS_OFF", CHECK_PEAKS, false}, { "FULL_DUPLEX_ON", FULL_DUPLEX, true}, { "FULL_DUPLEX_OFF", FULL_DUPLEX, false}, }; static int _num_params = sizeof(_param_list) / sizeof(Param); //-------------------------------- _str_to_bool, _str_to_int, _str_to_double --- static int _str_to_bool(const char *str, bool &val) { if (strcasecmp(str, "yes") == 0 || strcasecmp(str, "true") == 0 || strcasecmp(str, "on") == 0) val = true; else if (strcasecmp(str, "no") == 0 || strcasecmp(str, "false") == 0 || strcasecmp(str, "off") == 0) val = false; else { val = false; return -1; } return 0; } static int _str_to_int(const char *str, int &val) { char *pos = NULL; long num = strtol(str, &pos, 10); if (*pos != 0) return -1; val = num; return 0; } static int _str_to_double(const char *str, double &val) { char *pos = NULL; errno = 0; val = strtod(str, &pos); if (errno != 0 || (val == 0.0 && pos == str)) return -1; return 0; } //--------------------------------------------------------- _set_full_duplex --- // The full duplex state has now been broken up into the <play> and <record> // options, used during audio setup. rtsetparams() checks <record>. static int _set_full_duplex(const bool full_duplex, const bool rtsetparams_called) { if (full_duplex && rtsetparams_called) return die("set_option", "Turn on full duplex BEFORE calling rtsetparams."); if (full_duplex) Option::record(true); else { // If not play, then record. bool state = Option::record() && !Option::play(); Option::record(state); } // Same check as above, for record. if (Option::record() && rtsetparams_called) return die("set_option", "Turn on record BEFORE calling rtsetparams."); return 0; } //---------------------------------------------------- _set_key_value_option --- static int _set_key_value_option(const char *key, const char *sval, const bool rtsetparams_called) { int type = -1; for (int j = 0; j < _num_params; j++) { if (strcasecmp(_param_list[j].arg, key) == 0) { type = _param_list[j].type; break; } } if (type == -1) return -1; if (sval == NULL) return die("set_option", "No value for \"%s\"", key); int status = 0; bool bval = false; int ival = 0; double dval = 0.0; switch (type) { case AUDIO: status = _str_to_bool(sval, bval); Option::audio(bval); break; case PLAY: status = _str_to_bool(sval, bval); Option::play(bval); break; case RECORD: status = _str_to_bool(sval, bval); Option::record(bval); if (Option::record() && rtsetparams_called) return die("set_option", "Turn on record BEFORE calling rtsetparams."); break; case CLOBBER: status = _str_to_bool(sval, bval); Option::clobber(bval); break; case PRINT: status = _str_to_bool(sval, bval); Option::print(bval); break; case REPORT_CLIPPING: status = _str_to_bool(sval, bval); Option::reportClipping(bval); break; case CHECK_PEAKS: status = _str_to_bool(sval, bval); Option::checkPeaks(bval); break; case EXIT_ON_ERROR: status = _str_to_bool(sval, bval); Option::exitOnError(bval); break; case AUTO_LOAD: status = _str_to_bool(sval, bval); Option::autoLoad(bval); break; case BUFFER_FRAMES: status = _str_to_int(sval, ival); if (status == 0) { if (ival <= 0) return die("set_option", "\"%s\" value must be > 0", key); Option::bufferFrames(ival); } break; case BUFFER_COUNT: status = _str_to_int(sval, ival); if (status == 0) { if (ival <= 0) return die("set_option", "\"%s\" value must be > 0", key); Option::bufferCount(ival); } break; case DEVICE: Option::device(sval); break; case INDEVICE: Option::inDevice(sval); break; case OUTDEVICE: Option::outDevice(sval); break; case MIDI_INDEVICE: Option::midiInDevice(sval); break; case MIDI_OUTDEVICE: Option::midiOutDevice(sval); break; case DSOPATH: Option::dsoPath(sval); break; case RCNAME: Option::rcName(sval); break; default: break; } if (status == -1) return die("set_option", "Trouble parsing value \"%s\"", sval); return status; } //-------------------------------------------------------- _set_value_option --- // This way of setting options is deprecated, in favor of the new key=value way. static int _set_value_option(const char *sval, const bool rtsetparams_called) { int type = -1; bool bval = false; for (int j = 0; j < _num_params; j++) { if (strcasecmp(_param_list[j].arg, sval) == 0) { type = _param_list[j].type; bval = _param_list[j].value; break; } } if (type == -1) return -1; switch (type) { case AUDIO: Option::play(bval); break; case RECORD: Option::record(bval); if (Option::record() && rtsetparams_called) return die("set_option", "Turn on record BEFORE calling rtsetparams."); break; case CLOBBER: Option::clobber(bval); break; case REPORT_CLIPPING: Option::reportClipping(bval); break; case CHECK_PEAKS: Option::checkPeaks(bval); break; case FULL_DUPLEX: if (_set_full_duplex(bval, rtsetparams_called) == -1) return -1; break; default: break; } return 0; } //--------------------------------------------------------------- _parse_arg --- static int _parse_arg(const char *arg, const bool rtsetparams_called) { // Strip white-space chars from text to the left of any '=' and between // the '=' and the next non-white space. The reason we don't strip the // whole string is to preserve options that must include spaces, such // as "MOTU 828". Store result into <opt>. int len = arg ? strlen(arg) : 0; if (len > OPT_STRLEN - 1) len = OPT_STRLEN - 1; char opt[OPT_STRLEN]; char *p = opt; int space_state = 0; for (int j = 0; j < len; j++) { if (space_state > 1) *p++ = arg[j]; else if (!isspace(arg[j])) { if (space_state == 1) space_state++; else if (arg[j] == '=') space_state = 1; *p++ = arg[j]; } } *p = '\0'; // Two styles of option string: a single "value" and a "key=value" pair. int status = 0; p = strchr(opt, '='); // check for "key=value" if (p) { *p++ = '\0'; // <opt> is now key only if (*p == '\0') // p now points to value string return die("set_option", "Missing value for key \"%s\"", opt); status = _set_key_value_option(opt, p, rtsetparams_called); } else // check for single "value" status = _set_value_option(opt, rtsetparams_called); if (status == -1) return die("set_option", "Unrecognized option \"%s\"", opt); return 0; } //--------------------------------------------------------------- set_option --- double RTcmix::set_option(float *p, int nargs, double pp[]) { for (int i = 0; i < nargs; i++) { char *arg = (char *) ((int) pp[i]); // cast pfield to string if (_parse_arg(arg, rtsetparams_called) == -1) return -1.0; } return 0.0; } <commit_msg>Comment changes.<commit_after>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ // The set_option function, called from a script, lets the user override // default options (and those stored in the .rtcmixrc file). The options // are kept in the <options> object (see Option.h). // // To add new options... // // 1. add a symbol to the ParamType enum below, // 2. add an entry to the Param struct array, and // 3. write a case statement to match the enum symbol in _set_key_value_option, // using the _str_to_* functions for string conversion. // // Please keep the items created in the steps above in the same order that they // appear in Option.h -- makes this file easier to maintain. // // -JGG, 6/30/04, rev. 4/10/05 #include <RTcmix.h> #include <ugens.h> // for die() #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <Option.h> enum ParamType { AUDIO, PLAY, RECORD, CLOBBER, PRINT, REPORT_CLIPPING, CHECK_PEAKS, FULL_DUPLEX, EXIT_ON_ERROR, AUTO_LOAD, BUFFER_FRAMES, BUFFER_COUNT, DEVICE, INDEVICE, OUTDEVICE, MIDI_INDEVICE, MIDI_OUTDEVICE, DSOPATH, RCNAME }; #define OPT_STRLEN 128 struct Param { char arg[OPT_STRLEN]; ParamType type; bool value; // use false if not relevant, i.e. for key=value style }; static Param _param_list[] = { // These are key=value option strings. Please list these in the order in // which they appear in Option.h, to make it easier to compare. { kOptionAudio, AUDIO, false}, { kOptionPlay, PLAY, false}, { kOptionRecord, RECORD, false}, { kOptionClobber, CLOBBER, false}, { kOptionPrint, PRINT, false}, { kOptionReportClipping, REPORT_CLIPPING, false}, { kOptionCheckPeaks, CHECK_PEAKS, false}, { kOptionExitOnError, EXIT_ON_ERROR, false}, { kOptionAutoLoad, AUTO_LOAD, false}, { kOptionBufferFrames, BUFFER_FRAMES, false}, { kOptionBufferCount, BUFFER_COUNT, false}, { kOptionDevice, DEVICE, false}, { kOptionInDevice, INDEVICE, false}, { kOptionOutDevice, OUTDEVICE, false}, { kOptionMidiInDevice, MIDI_INDEVICE, false}, { kOptionMidiOutDevice, MIDI_OUTDEVICE, false}, { kOptionDSOPath, DSOPATH, false}, { kOptionRCName, RCNAME, false}, // These are the deprecated single-value option strings. // Please don't add more. { "AUDIO_ON", AUDIO, true}, { "AUDIO_OFF", AUDIO, false}, { "RECORD_ON", RECORD, true}, { "RECORD_OFF", RECORD, false}, { "PLAY_ON", AUDIO, true}, { "PLAY_OFF", AUDIO, false}, { "CLOBBER_ON", CLOBBER, true}, { "CLOBBER_OFF", CLOBBER, false}, { "REPORT_CLIPPING_ON", REPORT_CLIPPING, true}, { "REPORT_CLIPPING_OFF", REPORT_CLIPPING, false}, { "CHECK_PEAKS_ON", CHECK_PEAKS, true}, { "CHECK_PEAKS_OFF", CHECK_PEAKS, false}, { "FULL_DUPLEX_ON", FULL_DUPLEX, true}, { "FULL_DUPLEX_OFF", FULL_DUPLEX, false}, }; static int _num_params = sizeof(_param_list) / sizeof(Param); //-------------------------------- _str_to_bool, _str_to_int, _str_to_double --- static int _str_to_bool(const char *str, bool &val) { if (strcasecmp(str, "yes") == 0 || strcasecmp(str, "true") == 0 || strcasecmp(str, "on") == 0) val = true; else if (strcasecmp(str, "no") == 0 || strcasecmp(str, "false") == 0 || strcasecmp(str, "off") == 0) val = false; else { val = false; return -1; } return 0; } static int _str_to_int(const char *str, int &val) { char *pos = NULL; long num = strtol(str, &pos, 10); if (*pos != 0) return -1; val = num; return 0; } static int _str_to_double(const char *str, double &val) { char *pos = NULL; errno = 0; val = strtod(str, &pos); if (errno != 0 || (val == 0.0 && pos == str)) return -1; return 0; } //--------------------------------------------------------- _set_full_duplex --- // The full duplex state has now been broken up into the <play> and <record> // options, used during audio setup. rtsetparams() checks <record>. static int _set_full_duplex(const bool full_duplex, const bool rtsetparams_called) { if (full_duplex && rtsetparams_called) return die("set_option", "Turn on full duplex BEFORE calling rtsetparams."); if (full_duplex) Option::record(true); else { // If not play, then record. bool state = Option::record() && !Option::play(); Option::record(state); } // Same check as above, for record. if (Option::record() && rtsetparams_called) return die("set_option", "Turn on record BEFORE calling rtsetparams."); return 0; } //---------------------------------------------------- _set_key_value_option --- static int _set_key_value_option(const char *key, const char *sval, const bool rtsetparams_called) { int type = -1; for (int j = 0; j < _num_params; j++) { if (strcasecmp(_param_list[j].arg, key) == 0) { type = _param_list[j].type; break; } } if (type == -1) return -1; if (sval == NULL) return die("set_option", "No value for \"%s\"", key); int status = 0; bool bval = false; int ival = 0; double dval = 0.0; switch (type) { case AUDIO: status = _str_to_bool(sval, bval); Option::audio(bval); break; case PLAY: status = _str_to_bool(sval, bval); Option::play(bval); break; case RECORD: status = _str_to_bool(sval, bval); Option::record(bval); if (Option::record() && rtsetparams_called) return die("set_option", "Turn on record BEFORE calling rtsetparams."); break; case CLOBBER: status = _str_to_bool(sval, bval); Option::clobber(bval); break; case PRINT: status = _str_to_bool(sval, bval); Option::print(bval); break; case REPORT_CLIPPING: status = _str_to_bool(sval, bval); Option::reportClipping(bval); break; case CHECK_PEAKS: status = _str_to_bool(sval, bval); Option::checkPeaks(bval); break; case EXIT_ON_ERROR: status = _str_to_bool(sval, bval); Option::exitOnError(bval); break; case AUTO_LOAD: status = _str_to_bool(sval, bval); Option::autoLoad(bval); break; case BUFFER_FRAMES: status = _str_to_int(sval, ival); if (status == 0) { if (ival <= 0) return die("set_option", "\"%s\" value must be > 0", key); Option::bufferFrames(ival); } break; case BUFFER_COUNT: status = _str_to_int(sval, ival); if (status == 0) { if (ival <= 0) return die("set_option", "\"%s\" value must be > 0", key); Option::bufferCount(ival); } break; case DEVICE: Option::device(sval); break; case INDEVICE: Option::inDevice(sval); break; case OUTDEVICE: Option::outDevice(sval); break; case MIDI_INDEVICE: Option::midiInDevice(sval); break; case MIDI_OUTDEVICE: Option::midiOutDevice(sval); break; case DSOPATH: Option::dsoPath(sval); break; case RCNAME: Option::rcName(sval); break; default: break; } if (status == -1) return die("set_option", "Trouble parsing value \"%s\"", sval); return status; } //-------------------------------------------------------- _set_value_option --- // This way of setting options is deprecated, in favor of the new key=value way. static int _set_value_option(const char *sval, const bool rtsetparams_called) { int type = -1; bool bval = false; for (int j = 0; j < _num_params; j++) { if (strcasecmp(_param_list[j].arg, sval) == 0) { type = _param_list[j].type; bval = _param_list[j].value; break; } } if (type == -1) return -1; switch (type) { case AUDIO: Option::play(bval); break; case RECORD: Option::record(bval); if (Option::record() && rtsetparams_called) return die("set_option", "Turn on record BEFORE calling rtsetparams."); break; case CLOBBER: Option::clobber(bval); break; case REPORT_CLIPPING: Option::reportClipping(bval); break; case CHECK_PEAKS: Option::checkPeaks(bval); break; case FULL_DUPLEX: if (_set_full_duplex(bval, rtsetparams_called) == -1) return -1; break; default: break; } return 0; } //--------------------------------------------------------------- _parse_arg --- static int _parse_arg(const char *arg, const bool rtsetparams_called) { // Strip white-space chars from text to the left of any '=' and between // the '=' and the next non-white space. The reason we don't strip the // whole string is to preserve options that must include spaces, such // as "MOTU 828". Store result into <opt>. int len = arg ? strlen(arg) : 0; if (len > OPT_STRLEN - 1) len = OPT_STRLEN - 1; char opt[OPT_STRLEN]; char *p = opt; int space_state = 0; for (int j = 0; j < len; j++) { if (space_state > 1) *p++ = arg[j]; else if (!isspace(arg[j])) { if (space_state == 1) space_state++; else if (arg[j] == '=') space_state = 1; *p++ = arg[j]; } } *p = '\0'; // Two styles of option string: a single "value" and a "key=value" pair. int status = 0; p = strchr(opt, '='); // check for "key=value" if (p) { *p++ = '\0'; // <opt> is now key only if (*p == '\0') // p now points to value string return die("set_option", "Missing value for key \"%s\"", opt); status = _set_key_value_option(opt, p, rtsetparams_called); } else // check for single "value" status = _set_value_option(opt, rtsetparams_called); if (status == -1) return die("set_option", "Unrecognized option \"%s\"", opt); return 0; } //--------------------------------------------------------------- set_option --- double RTcmix::set_option(float *p, int nargs, double pp[]) { for (int i = 0; i < nargs; i++) { char *arg = (char *) ((int) pp[i]); // cast pfield to string if (_parse_arg(arg, rtsetparams_called) == -1) return -1.0; } return 0.0; } <|endoftext|>
<commit_before>#include <iostream> #include <helper/args.h> #include <helper/link.h> #include <boost/filesystem.hpp> #include <boost/range/iterator_range.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/regex.hpp> using namespace boost::filesystem; using namespace boost; void testFiles(std::vector<path> paths); int main(int argc, char **argv) { cOptions options("River version 0.1"); cCommandOption version({"v", "version"}, "Prints version", false); options.mainState.add(&version); cOptionsState test("test", "Tests your orange project"); cCommandOption testFailed({"f", "failed"}, "Only test tests that failed on the last run", false); test.add(&testFailed); options.mainState.addState(&test); options.parse(argc, argv); if (version.isSet()) { std::cout << "River version 0.1" << std::endl; exit(0); } for (std::string option : test.unparsed()) { } if (test.isActive() && test.unparsed().size() == 0) { // for now, test everything in test, going through each subdirectory. path p("test"); regex filter(".*\\.or"); std::vector<path> toTest; if (!exists(p)) { exit(0); } else { for (auto& entry : make_iterator_range(recursive_directory_iterator(p), {})) { smatch what; if (!regex_match(entry.path().filename().string(), what, filter)) continue; toTest.push_back(entry.path()); } testFiles(toTest); } } else if (test.isActive() && test.unparsed().size() > 0) { regex filter(".*\\.or"); std::vector<path> toTest; for (std::string subdir : test.unparsed()) { std::string search = "test/" + subdir; path p(search); if (!exists(p)) { std::cerr << "fatal: path " << search << " does not exist.\n"; exit(1); } for (auto& entry : make_iterator_range(recursive_directory_iterator(p), {})) { smatch what; if (!regex_match(entry.path().filename().string(), what, filter)) continue; toTest.push_back(entry.path()); } } testFiles(toTest); } return 0; } void testFiles(std::vector<path> paths) { boost::posix_time::ptime startTime = boost::posix_time::microsec_clock::local_time(); int total = 0; int failed = 0; int passed = 0; int warnings = 0; std::vector<std::string> errors; const char *ocPath = programPath("oc"); if (ocPath == nullptr) { std::cerr << "fatal: could not find oc in $PATH.\n"; exit(1); } try { boost::filesystem::create_directories("build/test"); } catch (filesystem_error e) { std::cerr << "fatal: could not build directory build/test\n"; exit(1); } for (path p : paths) { std::vector<const char *> options; options.push_back(p.string().c_str()); options.push_back("-o"); std::string output = p.stem().string(); output = "build/test/" + output; #ifdef _WIN32 output += ".exe"; #endif options.push_back(output.c_str()); int status = invokeProgramWithOptions(ocPath, options, true); bool added_error = false; path output_p(output); if (!exists(output_p)) status = 1; if (status && !added_error) { errors.push_back(p.string() + " (compile failed)"); added_error = true; } if (status == 0) { std::vector<const char *> roptions; status = invokeProgramWithOptions(output.c_str(), roptions, true); } if (status && !added_error) { errors.push_back(p.string() + " (program did not return 0)"); added_error = true; } if (status == 0) { std::cout << "." << std::flush; passed++; } else { std::cout << "F" << std::flush; failed++; } if (exists(output_p)) { remove(output_p); } total++; if ((total % 40) == 0) std::cout << "\n"; } boost::posix_time::ptime endTime = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_duration diff = endTime - startTime; long ms = diff.total_milliseconds(); std::cout << "\n\nTest results (" << (float)ms/1000.0f << " seconds):\n"; std::cout << "\t" << total << " tests total.\n"; std::cout << "\t" << passed << " tests passed.\n"; std::cout << "\t" << failed << " tests failed.\n"; if (errors.size() > 0) { std::cout << "\nErrors:\n"; for (std::string error : errors) { std::cout << "\t" << error << std::endl; } std::cout << std::endl; } } <commit_msg>Added ability to run failed tests from the last run.<commit_after>#include <iostream> #include <helper/args.h> #include <helper/link.h> #include <boost/filesystem.hpp> #include <boost/range/iterator_range.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/regex.hpp> #include <fstream> using namespace boost::filesystem; using namespace boost; void testFiles(std::vector<path> paths); void runFailed(); int main(int argc, char **argv) { cOptions options("River version 0.1"); cCommandOption version({"v", "version"}, "Prints version", false); options.mainState.add(&version); cOptionsState test("test", "Tests your orange project"); cCommandOption testFailed({"f", "failed"}, "Only test tests that failed on the last run", false); test.add(&testFailed); options.mainState.addState(&test); options.parse(argc, argv); if (version.isSet()) { std::cout << "River version 0.1" << std::endl; exit(0); } if (test.isActive() && testFailed.isSet()) { runFailed(); } else if (test.isActive() && test.unparsed().size() == 0) { // for now, test everything in test, going through each subdirectory. path p("test"); regex filter(".*\\.or"); std::vector<path> toTest; if (!exists(p)) { exit(0); } else { for (auto& entry : make_iterator_range(recursive_directory_iterator(p), {})) { smatch what; if (!regex_match(entry.path().filename().string(), what, filter)) continue; toTest.push_back(entry.path()); } testFiles(toTest); } } else if (test.isActive() && test.unparsed().size() > 0) { regex filter(".*\\.or"); std::vector<path> toTest; for (std::string subdir : test.unparsed()) { std::string search = "test/" + subdir; path p(search); if (!exists(p)) { std::cerr << "fatal: path " << search << " does not exist.\n"; exit(1); } for (auto& entry : make_iterator_range(recursive_directory_iterator(p), {})) { smatch what; if (!regex_match(entry.path().filename().string(), what, filter)) continue; toTest.push_back(entry.path()); } } testFiles(toTest); } return 0; } class TestError { public: std::string file; std::string reason; std::string string() { return file + " (" + reason + ")"; } }; void runFailed() { std::vector<path> toTest; std::ifstream errorCache("build/test/.fails-cache.river", std::ios_base::in); std::string line; while (std::getline(errorCache, line)) { if (line == "") continue; toTest.push_back(line); } testFiles(toTest); } void createFailCache(std::vector<TestError> fails) { std::ofstream errorCache("build/test/.fails-cache.river", std::ios_base::out | std::ios_base::trunc); if (errorCache.is_open() == false) { std::cerr << "fatal: could not create fail cache\n"; exit(1); } for (TestError error : fails) { errorCache << error.file << std::endl; } errorCache.close(); } void testFiles(std::vector<path> paths) { boost::posix_time::ptime startTime = boost::posix_time::microsec_clock::local_time(); int total = 0; int failed = 0; int passed = 0; int warnings = 0; std::vector<TestError> errors; const char *ocPath = programPath("oc"); if (ocPath == nullptr) { std::cerr << "fatal: could not find oc in $PATH.\n"; exit(1); } try { boost::filesystem::create_directories("build/test"); } catch (filesystem_error e) { std::cerr << "fatal: could not build directory build/test\n"; exit(1); } for (path p : paths) { std::vector<const char *> options; options.push_back(p.string().c_str()); options.push_back("-o"); std::string output = p.stem().string(); output = "build/test/" + output; #ifdef _WIN32 output += ".exe"; #endif options.push_back(output.c_str()); int status = invokeProgramWithOptions(ocPath, options, true); bool added_error = false; path output_p(output); if (!exists(output_p)) status = 1; if (status && !added_error) { TestError err; err.file = p.string(); err.reason = "compile failed"; errors.push_back(err); added_error = true; } if (status == 0) { std::vector<const char *> roptions; status = invokeProgramWithOptions(output.c_str(), roptions, true); } if (status && !added_error) { TestError err; err.file = p.string(); err.reason = "program did not return 0"; errors.push_back(err); added_error = true; } if (status == 0) { std::cout << "." << std::flush; passed++; } else { std::cout << "F" << std::flush; failed++; } if (exists(output_p)) { remove(output_p); } total++; if ((total % 40) == 0) std::cout << "\n"; } boost::posix_time::ptime endTime = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_duration diff = endTime - startTime; long ms = diff.total_milliseconds(); std::cout << "\n\nTest results (" << (float)ms/1000.0f << " seconds):\n"; std::cout << "\t" << total << " tests total.\n"; std::cout << "\t" << passed << " tests passed.\n"; std::cout << "\t" << failed << " tests failed.\n"; if (errors.size() > 0) { std::cout << "\nErrors:\n"; for (TestError error : errors) { std::cout << "\t" << error.string() << std::endl; } std::cout << std::endl; } createFailCache(errors); } <|endoftext|>
<commit_before>#include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <cstdio> #include <cstdlib> #include <map> #include <string> #include <gtk/gtk.h> #define die(msg, ...) \ ({fprintf(stderr, "gtkglswitch: fatal: " msg "\n", ##__VA_ARGS__); exit(1);}) static bool ask_user(const char procname[], bool &remember) { GtkWidget *dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK, "Use OpenGL offloading for %s?", procname); GtkWidget *content = gtk_message_dialog_get_message_area(GTK_MESSAGE_DIALOG(dialog)); GtkWidget *radioy = gtk_radio_button_new_with_label(NULL, "Yes, use the discrete GPU"); gtk_container_add(GTK_CONTAINER(content), radioy); GtkWidget *radion = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(radioy), "No, use integrated GPU"); gtk_container_add(GTK_CONTAINER(content), radion); GtkWidget *check = gtk_check_button_new_with_label("Remember my choice"); gtk_container_add(GTK_CONTAINER(content), check); gtk_widget_show_all(dialog); gtk_dialog_run(GTK_DIALOG (dialog)); gboolean yes = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioy)); remember = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check)); gtk_widget_destroy(dialog); return yes; } static char *conffile; static std::map<std::string, bool> read_memos() { const char *configdir, *homedir; int r; if ((configdir = getenv("XDG_CONFIG_HOME"))) r = asprintf(&conffile, "%s/libgl_switcheroo.conf", configdir); else if ((homedir = getenv("HOME"))) r = asprintf(&conffile, "%s/.config/libgl_switcheroo.conf", homedir); else die("XDG_CONFIG_HOME and HOME are not set"); if (r < 0) die("asprintf failed"); FILE *f = fopen(conffile, "r"); std::map<std::string, bool> memos; if (!f) return memos; char c, procname[17]; while (fscanf(f, "%c%16[^\n]\n", &c, procname) == 2) memos[std::string(procname)] = c == '+'; fclose(f); return memos; } static std::map<std::string, bool> memos(read_memos()); static bool lookup_memo(const char procname[], bool &choice) { std::map<std::string, bool>::iterator i = memos.find(std::string(procname)); if (i != memos.end()) choice = i->second; return i != memos.end(); } static void add_memo(const char procname[], bool choice) { memos[std::string(procname)] = choice; FILE *f = fopen(conffile, "a"); if (!f) die("failed to open %s for writing", conffile); fprintf(f, "%c%s\n", choice ? '+' : '-', procname); fclose(f); } static bool need_switch(pid_t pid) { char pathbuf[32]; snprintf(pathbuf, 32, "/proc/%d/status", pid); int fd = open(pathbuf, O_RDONLY); char namebuf[32]; read(fd, namebuf, 32); close(fd); *strchr(namebuf, '\n') = 0; char *procname = namebuf + 6; bool switch_yes; if (lookup_memo(procname, switch_yes)) return switch_yes; bool remember = false; switch_yes = ask_user(procname, remember); if (remember) add_memo(procname, switch_yes); return switch_yes; } static void gdk_input_cb(void *data, int sock, GdkInputCondition cond) { int fd = accept(sock, 0, 0); int pid; recv(fd, &pid, sizeof(pid), 0); pid = need_switch(pid); send(fd, &pid, sizeof(pid), 0); close(fd); } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); struct sockaddr_un addr; addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/libgl-switcheroo-%s/socket", getenv("USER")); unlink(addr.sun_path); int sock = socket(PF_UNIX, SOCK_STREAM, 0); if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) die("failed to bind socket %s: %s", addr.sun_path, strerror(errno)); listen(sock, 16); gdk_input_add(sock, GDK_INPUT_READ, gdk_input_cb, NULL); gtk_main(); return 0; } <commit_msg>Implement setting default answer on the command line<commit_after>#include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <cstdio> #include <cstdlib> #include <map> #include <string> #include <gtk/gtk.h> #define die(msg, ...) \ ({fprintf(stderr, "gtkglswitch: fatal: " msg "\n", ##__VA_ARGS__); exit(1);}) static bool ask_user(const char procname[], bool &remember) { GtkWidget *dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK, "Use OpenGL offloading for %s?", procname); GtkWidget *content = gtk_message_dialog_get_message_area(GTK_MESSAGE_DIALOG(dialog)); GtkWidget *radioy = gtk_radio_button_new_with_label(NULL, "Yes, use the discrete GPU"); gtk_container_add(GTK_CONTAINER(content), radioy); GtkWidget *radion = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(radioy), "No, use integrated GPU"); gtk_container_add(GTK_CONTAINER(content), radion); GtkWidget *check = gtk_check_button_new_with_label("Remember my choice"); gtk_container_add(GTK_CONTAINER(content), check); gtk_widget_show_all(dialog); gtk_dialog_run(GTK_DIALOG (dialog)); gboolean yes = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioy)); remember = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check)); gtk_widget_destroy(dialog); return yes; } static char *conffile; static std::map<std::string, bool> read_memos() { const char *configdir, *homedir; int r; if ((configdir = getenv("XDG_CONFIG_HOME"))) r = asprintf(&conffile, "%s/libgl_switcheroo.conf", configdir); else if ((homedir = getenv("HOME"))) r = asprintf(&conffile, "%s/.config/libgl_switcheroo.conf", homedir); else die("XDG_CONFIG_HOME and HOME are not set"); if (r < 0) die("asprintf failed"); FILE *f = fopen(conffile, "r"); std::map<std::string, bool> memos; if (!f) return memos; char c, procname[17]; while (fscanf(f, "%c%16[^\n]\n", &c, procname) == 2) memos[std::string(procname)] = c == '+'; fclose(f); return memos; } static std::map<std::string, bool> memos(read_memos()); static bool lookup_memo(const char procname[], bool &choice) { std::map<std::string, bool>::iterator i = memos.find(std::string(procname)); if (i != memos.end()) choice = i->second; return i != memos.end(); } static void add_memo(const char procname[], bool choice) { memos[std::string(procname)] = choice; FILE *f = fopen(conffile, "a"); if (!f) die("failed to open %s for writing", conffile); fprintf(f, "%c%s\n", choice ? '+' : '-', procname); fclose(f); } static enum { SWITCH_DEFAULT_ASK, SWITCH_DEFAULT_NO, SWITCH_DEFAULT_YES } switch_default; static bool need_switch(pid_t pid) { char pathbuf[32]; snprintf(pathbuf, 32, "/proc/%d/status", pid); int fd = open(pathbuf, O_RDONLY); char namebuf[32]; read(fd, namebuf, 32); close(fd); *strchr(namebuf, '\n') = 0; char *procname = namebuf + 6; bool switch_yes; if (lookup_memo(procname, switch_yes)) return switch_yes; if (switch_default != SWITCH_DEFAULT_ASK) return switch_default == SWITCH_DEFAULT_YES; bool remember = false; switch_yes = ask_user(procname, remember); if (remember) add_memo(procname, switch_yes); return switch_yes; } static void gdk_input_cb(void *data, int sock, GdkInputCondition cond) { int fd = accept(sock, 0, 0); int pid; recv(fd, &pid, sizeof(pid), 0); pid = need_switch(pid); send(fd, &pid, sizeof(pid), 0); close(fd); } int main(int argc, char *argv[]) { char *opt_default = NULL; GError *error = NULL; if (!gtk_init_with_args (&argc, &argv, NULL, (GOptionEntry[]){ {"default", 'D', 0, G_OPTION_ARG_STRING, &opt_default, "assume default answer", ""}, 0}, NULL, &error)) die("GTK initialization failed: %s", error->message); if (opt_default) if (!strcmp(opt_default, "yes")) switch_default = SWITCH_DEFAULT_YES; else if (!strcmp(opt_default, "no")) switch_default = SWITCH_DEFAULT_NO; else die("invalid default answer: %s", opt_default); struct sockaddr_un addr; addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/libgl-switcheroo-%s/socket", getenv("USER")); unlink(addr.sun_path); int sock = socket(PF_UNIX, SOCK_STREAM, 0); if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) die("failed to bind socket %s: %s", addr.sun_path, strerror(errno)); listen(sock, 16); gdk_input_add(sock, GDK_INPUT_READ, gdk_input_cb, NULL); gtk_main(); return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (Apache License) * * Copyright (c) 2014, Dan Solomon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * joint_trajectory_pt.cpp * * Created on: Oct 3, 2014 * Author: Dan Solomon */ #include <console_bridge/console.h> #include "descartes_trajectory/joint_trajectory_pt.h" #define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret; using namespace descartes_core; namespace descartes_trajectory { JointTrajectoryPt::JointTrajectoryPt(const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing) , tool_(Eigen::Affine3d::Identity()) , wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints, const Frame &tool, const Frame &wobj, const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing), joint_position_(joints), tool_(tool), wobj_(wobj) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints, const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing), joint_position_(joints), tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<double> &joints, const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing), tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) { for (size_t ii = 0; ii < joints.size(); ++ii) { joint_position_.push_back(TolerancedJointValue(joints[ii])); } } bool JointTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { NOT_IMPLEMENTED_ERR(false) } bool JointTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { std::vector<double> joints; for(auto& tj: joint_position_) { joints.push_back(tj.nominal); } return model.getFK(joints,pose); } void JointTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const { poses.clear(); } bool JointTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { if(joint_position_.empty()) { return false; } else { return getNominalJointPose(seed_state,model,joint_pose); } } bool JointTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { joint_pose.resize(joint_position_.size()); for (size_t ii=0; ii<joint_position_.size(); ++ii) { joint_pose[ii] = joint_position_[ii].nominal; } return true; } void JointTrajectoryPt::getJointPoses(const RobotModel &model, std::vector<std::vector<double> > &joint_poses) const { std::vector<double> empty_seed; joint_poses.resize(1); getNominalJointPose(empty_seed,model,joint_poses[0]); } bool JointTrajectoryPt::isValid(const RobotModel &model) const { std::vector<double> lower(joint_position_.size()); std::vector<double> upper(joint_position_.size()); for (size_t ii = 0; ii < joint_position_.size(); ++ii) { lower[ii] = joint_position_[ii].tolerance.lower; upper[ii] = joint_position_[ii].tolerance.upper; } return model.isValid(lower) && model.isValid(upper); } bool JointTrajectoryPt::setDiscretization(const std::vector<double> &discretization) { if (discretization.size() != 1 || discretization.size() != joint_position_.size()) { logError("discretization must be size 1 or same size as joint count."); return false; } if (discretization.size() == 1) { discretization_ = std::vector<double>(joint_position_.size(), discretization[0]); return true; } /* Do not copy discretization values until all values are confirmed */ for (size_t ii=0; ii<discretization.size(); ++ii) { if (discretization[ii] < 0. || discretization[ii] > joint_position_[ii].range()) { logError("discretization value out of range."); return false; } } discretization_ = discretization; return true; } } /* namespace descartes_trajectory */ <commit_msg>Lower and upper joint value ranges were being checked against the tolerances instead of the actual values (nominal + tolerance)<commit_after>/* * Software License Agreement (Apache License) * * Copyright (c) 2014, Dan Solomon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * joint_trajectory_pt.cpp * * Created on: Oct 3, 2014 * Author: Dan Solomon */ #include <console_bridge/console.h> #include "descartes_trajectory/joint_trajectory_pt.h" #define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret; using namespace descartes_core; namespace descartes_trajectory { JointTrajectoryPt::JointTrajectoryPt(const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing) , tool_(Eigen::Affine3d::Identity()) , wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints, const Frame &tool, const Frame &wobj, const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing), joint_position_(joints), tool_(tool), wobj_(wobj) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints, const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing), joint_position_(joints), tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<double> &joints, const descartes_core::TimingConstraint& timing) : descartes_core::TrajectoryPt(timing), tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) { for (size_t ii = 0; ii < joints.size(); ++ii) { joint_position_.push_back(TolerancedJointValue(joints[ii])); } } bool JointTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { NOT_IMPLEMENTED_ERR(false) } bool JointTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { std::vector<double> joints; for(auto& tj: joint_position_) { joints.push_back(tj.nominal); } return model.getFK(joints,pose); } void JointTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const { poses.clear(); } bool JointTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { if(joint_position_.empty()) { return false; } else { return getNominalJointPose(seed_state,model,joint_pose); } } bool JointTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { joint_pose.resize(joint_position_.size()); for (size_t ii=0; ii<joint_position_.size(); ++ii) { joint_pose[ii] = joint_position_[ii].nominal; } return true; } void JointTrajectoryPt::getJointPoses(const RobotModel &model, std::vector<std::vector<double> > &joint_poses) const { std::vector<double> empty_seed; joint_poses.resize(1); getNominalJointPose(empty_seed,model,joint_poses[0]); } bool JointTrajectoryPt::isValid(const RobotModel &model) const { std::vector<double> lower(joint_position_.size()); std::vector<double> upper(joint_position_.size()); for (size_t ii = 0; ii < joint_position_.size(); ++ii) { lower[ii] = joint_position_[ii].nominal + joint_position_[ii].tolerance.lower; upper[ii] = joint_position_[ii].nominal + joint_position_[ii].tolerance.upper; } return model.isValid(lower) && model.isValid(upper); } bool JointTrajectoryPt::setDiscretization(const std::vector<double> &discretization) { if (discretization.size() != 1 || discretization.size() != joint_position_.size()) { logError("discretization must be size 1 or same size as joint count."); return false; } if (discretization.size() == 1) { discretization_ = std::vector<double>(joint_position_.size(), discretization[0]); return true; } /* Do not copy discretization values until all values are confirmed */ for (size_t ii=0; ii<discretization.size(); ++ii) { if (discretization[ii] < 0. || discretization[ii] > joint_position_[ii].range()) { logError("discretization value out of range."); return false; } } discretization_ = discretization; return true; } } /* namespace descartes_trajectory */ <|endoftext|>
<commit_before><commit_msg>Sim_Control : use absolute time for point search and fix compile warnings<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/component/container/MultiMeshLoader.h> #include <sofa/core/ObjectFactory.h> #include <sofa/core/componentmodel/topology/Topology.h> #include <iostream> namespace sofa { namespace component { namespace container { using namespace sofa::defaulttype; SOFA_DECL_CLASS(MultiMeshLoader) int MultiMeshLoaderClass = core::RegisterObject("Generic multiple Mesh Loader") .add< MultiMeshLoader >() ; MultiMeshLoader::MultiMeshLoader() : filenameList(initData(&filenameList,"filenamelist","list of the filenames of the objects")) {} void MultiMeshLoader::parse(core::objectmodel::BaseObjectDescription* arg) { this->BaseObject::parse(arg); clear(); for (unsigned int i=0 ; i<filenameList.getValue().size() ; i++) { if (filenameList.getValue()[i] != "") { pushMesh(filenameList.getValue()[i].c_str()); } } } void MultiMeshLoader::pushMesh(const char* filename) { int cptPoints = seqPoints.size(); load(filename); nbPointsPerMesh.push_back(seqPoints.size() - cptPoints); } bool MultiMeshLoader::load(const char* filename) { //clear(); if (!MeshTopologyLoader::load(filename)) { serr << "Unable to load Mesh "<<filename << sendl; return false; } return true; } void MultiMeshLoader::addPoint(double px, double py, double pz) { seqPoints.push_back(helper::make_array((SReal)px, (SReal)py, (SReal)pz)); } void MultiMeshLoader::addLine( int a, int b ) { seqEdges.push_back(Edge(currentMeshIndex+a,currentMeshIndex+b)); } void MultiMeshLoader::addTriangle( int a, int b, int c ) { seqTriangles.push_back( Triangle(currentMeshIndex+a,currentMeshIndex+b,currentMeshIndex+c) ); } void MultiMeshLoader::addTetra( int a, int b, int c, int d ) { seqTetrahedra.push_back( Tetra(currentMeshIndex+a,currentMeshIndex+b,currentMeshIndex+c,currentMeshIndex+d) ); } void MultiMeshLoader::addQuad(int p1, int p2, int p3, int p4) { if (triangulate.getValue()) { addTriangle(p1,p2,p3); addTriangle(p1,p3,p4); } else seqQuads.push_back(Quad(currentMeshIndex+p1,currentMeshIndex+p2,currentMeshIndex+p3,currentMeshIndex+p4)); } void MultiMeshLoader::addCube(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { #ifdef SOFA_NEW_HEXA seqHexahedra.push_back(Hexa(currentMeshIndex+p1,currentMeshIndex+p2,currentMeshIndex+p3,currentMeshIndex+p4,currentMeshIndex+p5,currentMeshIndex+p6,currentMeshIndex+p7,currentMeshIndex+p8)); #else seqHexahedra.push_back(Hexa(currentMeshIndex+p1,currentMeshIndex+p2,currentMeshIndex+p4,currentMeshIndex+p3,currentMeshIndex+p5,currentMeshIndex+p6,currentMeshIndex+p8,currentMeshIndex+p7)); #endif } } } // namespace component } // namespace sofa <commit_msg>r6921/sofa-dev : FIX : error loading multi mesh<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/component/container/MultiMeshLoader.h> #include <sofa/core/ObjectFactory.h> #include <sofa/core/componentmodel/topology/Topology.h> #include <iostream> namespace sofa { namespace component { namespace container { using namespace sofa::defaulttype; SOFA_DECL_CLASS(MultiMeshLoader) int MultiMeshLoaderClass = core::RegisterObject("Generic multiple Mesh Loader") .add< MultiMeshLoader >() ; MultiMeshLoader::MultiMeshLoader() : filenameList(initData(&filenameList,"filenamelist","list of the filenames of the objects")) {} void MultiMeshLoader::parse(core::objectmodel::BaseObjectDescription* arg) { this->BaseObject::parse(arg); clear(); for (unsigned int i=0 ; i<filenameList.getValue().size() ; i++) { if (filenameList.getValue()[i] != "") { pushMesh(filenameList.getValue()[i].c_str()); } } } void MultiMeshLoader::pushMesh(const char* filename) { currentMeshIndex = seqPoints.size(); load(filename); nbPointsPerMesh.push_back(seqPoints.size() - currentMeshIndex); } bool MultiMeshLoader::load(const char* filename) { //clear(); if (!MeshTopologyLoader::load(filename)) { serr << "Unable to load Mesh "<<filename << sendl; return false; } return true; } void MultiMeshLoader::addPoint(double px, double py, double pz) { seqPoints.push_back(helper::make_array((SReal)px, (SReal)py, (SReal)pz)); } void MultiMeshLoader::addLine( int a, int b ) { seqEdges.push_back(Edge(currentMeshIndex+a,currentMeshIndex+b)); } void MultiMeshLoader::addTriangle( int a, int b, int c ) { seqTriangles.push_back( Triangle(currentMeshIndex+a,currentMeshIndex+b,currentMeshIndex+c) ); } void MultiMeshLoader::addTetra( int a, int b, int c, int d ) { seqTetrahedra.push_back( Tetra(currentMeshIndex+a,currentMeshIndex+b,currentMeshIndex+c,currentMeshIndex+d) ); } void MultiMeshLoader::addQuad(int p1, int p2, int p3, int p4) { if (triangulate.getValue()) { addTriangle(p1,p2,p3); addTriangle(p1,p3,p4); } else seqQuads.push_back(Quad(currentMeshIndex+p1,currentMeshIndex+p2,currentMeshIndex+p3,currentMeshIndex+p4)); } void MultiMeshLoader::addCube(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { #ifdef SOFA_NEW_HEXA seqHexahedra.push_back(Hexa(currentMeshIndex+p1,currentMeshIndex+p2,currentMeshIndex+p3,currentMeshIndex+p4,currentMeshIndex+p5,currentMeshIndex+p6,currentMeshIndex+p7,currentMeshIndex+p8)); #else seqHexahedra.push_back(Hexa(currentMeshIndex+p1,currentMeshIndex+p2,currentMeshIndex+p4,currentMeshIndex+p3,currentMeshIndex+p5,currentMeshIndex+p6,currentMeshIndex+p8,currentMeshIndex+p7)); #endif } } } // namespace component } // namespace sofa <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/video_coding/codecs/i420/main/interface/i420.h" #include <string.h> #include "common_video/libyuv/include/webrtc_libyuv.h" namespace webrtc { I420Encoder::I420Encoder(): _inited(false), _encodedImage(), _encodedCompleteCallback(NULL) {} I420Encoder::~I420Encoder() { _inited = false; if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; } } int I420Encoder::Release() { // Should allocate an encoded frame and then release it here, for that we // actually need an init flag. if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; } _inited = false; return WEBRTC_VIDEO_CODEC_OK; } int I420Encoder::InitEncode(const VideoCodec* codecSettings, int /*numberOfCores*/, uint32_t /*maxPayloadSize */) { if (codecSettings == NULL) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } if (codecSettings->width < 1 || codecSettings->height < 1) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } // Allocating encoded memory. if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; _encodedImage._size = 0; } const uint32_t newSize = CalcBufferSize(kI420, codecSettings->width, codecSettings->height); uint8_t* newBuffer = new uint8_t[newSize]; if (newBuffer == NULL) { return WEBRTC_VIDEO_CODEC_MEMORY; } _encodedImage._size = newSize; _encodedImage._buffer = newBuffer; // If no memory allocation, no point to init. _inited = true; return WEBRTC_VIDEO_CODEC_OK; } int I420Encoder::Encode(const I420VideoFrame& inputImage, const CodecSpecificInfo* /*codecSpecificInfo*/, const std::vector<VideoFrameType>* /*frame_types*/) { if (!_inited) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } if (_encodedCompleteCallback == NULL) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } _encodedImage._frameType = kKeyFrame; // No coding. _encodedImage._timeStamp = inputImage.timestamp(); _encodedImage._encodedHeight = inputImage.height(); _encodedImage._encodedWidth = inputImage.width(); int req_length = CalcBufferSize(kI420, inputImage.width(), inputImage.height()); if (_encodedImage._size > static_cast<unsigned int>(req_length)) { // Allocating encoded memory. if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; _encodedImage._size = 0; } uint8_t* newBuffer = new uint8_t[req_length]; if (newBuffer == NULL) { return WEBRTC_VIDEO_CODEC_MEMORY; } _encodedImage._size = req_length; _encodedImage._buffer = newBuffer; } int ret_length = ExtractBuffer(inputImage, req_length, _encodedImage._buffer); if (ret_length < 0) return WEBRTC_VIDEO_CODEC_MEMORY; _encodedImage._length = ret_length; _encodedCompleteCallback->Encoded(_encodedImage); return WEBRTC_VIDEO_CODEC_OK; } int I420Encoder::RegisterEncodeCompleteCallback(EncodedImageCallback* callback) { _encodedCompleteCallback = callback; return WEBRTC_VIDEO_CODEC_OK; } I420Decoder::I420Decoder(): _decodedImage(), _width(0), _height(0), _inited(false), _decodeCompleteCallback(NULL) {} I420Decoder::~I420Decoder() { Release(); } int I420Decoder::Reset() { return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::InitDecode(const VideoCodec* codecSettings, int /*numberOfCores */) { if (codecSettings == NULL) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } else if (codecSettings->width < 1 || codecSettings->height < 1) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } _width = codecSettings->width; _height = codecSettings->height; _inited = true; return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::Decode(const EncodedImage& inputImage, bool /*missingFrames*/, const RTPFragmentationHeader* /*fragmentation*/, const CodecSpecificInfo* /*codecSpecificInfo*/, int64_t /*renderTimeMs*/) { if (inputImage._buffer == NULL) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } if (_decodeCompleteCallback == NULL) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } if (inputImage._length <= 0) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } if (inputImage._completeFrame == false) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } if (!_inited) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } // Verify that the available length is sufficient: int req_length = CalcBufferSize(kI420, _width, _height); if (req_length > static_cast<int>(inputImage._length)) { return WEBRTC_VIDEO_CODEC_ERROR; } // Set decoded image parameters. int half_width = (_width + 1) / 2; int half_height = (_height + 1) / 2; int size_y = _width * _height; int size_uv = half_width * half_height; const uint8_t* buffer_y = inputImage._buffer; const uint8_t* buffer_u = buffer_y + size_y; const uint8_t* buffer_v = buffer_u + size_uv; // TODO(mikhal): Do we need an align stride? int ret = _decodedImage.CreateFrame(size_y, buffer_y, size_uv, buffer_u, size_uv, buffer_v, _width, _height, _width, half_width, half_width); if (ret < 0) { return WEBRTC_VIDEO_CODEC_MEMORY; } _decodedImage.set_timestamp(inputImage._timeStamp); _decodeCompleteCallback->Decoded(_decodedImage); return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::RegisterDecodeCompleteCallback(DecodedImageCallback* callback) { _decodeCompleteCallback = callback; return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::Release() { _inited = false; return WEBRTC_VIDEO_CODEC_OK; } } <commit_msg>Revert 3071 - i420:verify image length<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/video_coding/codecs/i420/main/interface/i420.h" #include <string.h> #include "common_video/libyuv/include/webrtc_libyuv.h" namespace webrtc { I420Encoder::I420Encoder(): _inited(false), _encodedImage(), _encodedCompleteCallback(NULL) {} I420Encoder::~I420Encoder() { _inited = false; if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; } } int I420Encoder::Release() { // Should allocate an encoded frame and then release it here, for that we // actually need an init flag. if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; } _inited = false; return WEBRTC_VIDEO_CODEC_OK; } int I420Encoder::InitEncode(const VideoCodec* codecSettings, int /*numberOfCores*/, uint32_t /*maxPayloadSize */) { if (codecSettings == NULL) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } if (codecSettings->width < 1 || codecSettings->height < 1) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } // Allocating encoded memory. if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; _encodedImage._size = 0; } const uint32_t newSize = CalcBufferSize(kI420, codecSettings->width, codecSettings->height); uint8_t* newBuffer = new uint8_t[newSize]; if (newBuffer == NULL) { return WEBRTC_VIDEO_CODEC_MEMORY; } _encodedImage._size = newSize; _encodedImage._buffer = newBuffer; // If no memory allocation, no point to init. _inited = true; return WEBRTC_VIDEO_CODEC_OK; } int I420Encoder::Encode(const I420VideoFrame& inputImage, const CodecSpecificInfo* /*codecSpecificInfo*/, const std::vector<VideoFrameType>* /*frame_types*/) { if (!_inited) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } if (_encodedCompleteCallback == NULL) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } _encodedImage._frameType = kKeyFrame; // No coding. _encodedImage._timeStamp = inputImage.timestamp(); _encodedImage._encodedHeight = inputImage.height(); _encodedImage._encodedWidth = inputImage.width(); int req_length = CalcBufferSize(kI420, inputImage.width(), inputImage.height()); if (_encodedImage._size > static_cast<unsigned int>(req_length)) { // Allocating encoded memory. if (_encodedImage._buffer != NULL) { delete [] _encodedImage._buffer; _encodedImage._buffer = NULL; _encodedImage._size = 0; } uint8_t* newBuffer = new uint8_t[req_length]; if (newBuffer == NULL) { return WEBRTC_VIDEO_CODEC_MEMORY; } _encodedImage._size = req_length; _encodedImage._buffer = newBuffer; } int ret_length = ExtractBuffer(inputImage, req_length, _encodedImage._buffer); if (ret_length < 0) return WEBRTC_VIDEO_CODEC_MEMORY; _encodedImage._length = ret_length; _encodedCompleteCallback->Encoded(_encodedImage); return WEBRTC_VIDEO_CODEC_OK; } int I420Encoder::RegisterEncodeCompleteCallback(EncodedImageCallback* callback) { _encodedCompleteCallback = callback; return WEBRTC_VIDEO_CODEC_OK; } I420Decoder::I420Decoder(): _decodedImage(), _width(0), _height(0), _inited(false), _decodeCompleteCallback(NULL) {} I420Decoder::~I420Decoder() { Release(); } int I420Decoder::Reset() { return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::InitDecode(const VideoCodec* codecSettings, int /*numberOfCores */) { if (codecSettings == NULL) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } else if (codecSettings->width < 1 || codecSettings->height < 1) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } _width = codecSettings->width; _height = codecSettings->height; _inited = true; return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::Decode(const EncodedImage& inputImage, bool /*missingFrames*/, const RTPFragmentationHeader* /*fragmentation*/, const CodecSpecificInfo* /*codecSpecificInfo*/, int64_t /*renderTimeMs*/) { if (inputImage._buffer == NULL) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } if (_decodeCompleteCallback == NULL) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } if (inputImage._length <= 0) { return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } if (!_inited) { return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } // Set decoded image parameters. int half_width = (_width + 1) / 2; int half_height = (_height + 1) / 2; int size_y = _width * _height; int size_uv = half_width * half_height; const uint8_t* buffer_y = inputImage._buffer; const uint8_t* buffer_u = buffer_y + size_y; const uint8_t* buffer_v = buffer_u + size_uv; // TODO(mikhal): Do we need an align stride? int ret = _decodedImage.CreateFrame(size_y, buffer_y, size_uv, buffer_u, size_uv, buffer_v, _width, _height, _width, half_width, half_width); if (ret < 0) { return WEBRTC_VIDEO_CODEC_MEMORY; } _decodedImage.set_timestamp(inputImage._timeStamp); _decodeCompleteCallback->Decoded(_decodedImage); return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::RegisterDecodeCompleteCallback(DecodedImageCallback* callback) { _decodeCompleteCallback = callback; return WEBRTC_VIDEO_CODEC_OK; } int I420Decoder::Release() { _inited = false; return WEBRTC_VIDEO_CODEC_OK; } } <|endoftext|>
<commit_before>/*! * \author ddubois * \date 21-Aug-18. */ #include "shaderpack_loading.hpp" #include "../folder_accessor.hpp" #include "../loading_utils.hpp" #include "../zip_folder_accessor.hpp" #include "../regular_folder_accessor.hpp" #include "../utils.hpp" #include "json_interop.hpp" #include <ftl\atomic_counter.h> namespace nova { fs::path SHADERPACK_ROOT("shaderpacks"); fs::path BEDROCK_SHADERPACK_ROOT("resourcepacks"); folder_accessor_base* get_shaderpack_accessor(const fs::path &shaderpack_name); void load_dynamic_resources_file(ftl::TaskScheduler *task_scheduler, void *arg); void load_passes_file(ftl::TaskScheduler *task_scheduler, void *arg); void load_pipeline_files(ftl::TaskScheduler *task_scheduler, void *arg); void load_single_pipeline(ftl::TaskScheduler *task_scheduler, void *arg); void load_material_files(ftl::TaskScheduler *task_scheduler, void *arg); void load_single_material(ftl::TaskScheduler *task_scheduler, void *arg); template<typename DataType> struct load_data_args { folder_accessor_base* folder_access; DataType output; }; shaderpack_data load_shaderpack_data(const fs::path& shaderpack_name, ftl::TaskScheduler& task_scheduler) { folder_accessor_base* folder_access = get_shaderpack_accessor(shaderpack_name); // The shaderpack has a number of items: There's the shaders themselves, of course, but there's so, so much more // What else is there? // - resources.json, to describe the dynamic resources that a shaderpack needs // - passes.json, to describe the frame graph itself // - All the pipeline descriptions // - All the material descriptions // // All these things are loaded from the filesystem ftl::AtomicCounter loading_tasks_remaining(&task_scheduler); // Load resource definitions auto load_resources_data = load_data_args<shaderpack_resources_data>{folder_access, shaderpack_resources_data()}; ftl::Task load_dynamic_resource_task = { load_dynamic_resources_file, &load_resources_data }; task_scheduler.AddTask(load_dynamic_resource_task, &loading_tasks_remaining); // Load pass definitions auto load_passes_data = load_data_args<std::vector<render_pass_data>>{folder_access, std::vector<render_pass_data>()}; ftl::Task load_passes_task = { load_passes_file, &load_passes_data }; task_scheduler.AddTask(load_passes_task, &loading_tasks_remaining); // Load pipeline definitions auto load_pipelines_data = load_data_args<std::vector<pipeline_data>>{folder_access, std::vector<pipeline_data>()}; ftl::Task load_pipelines_task = { load_pipeline_files, &load_pipelines_data }; //task_scheduler.AddTask(load_pipelines_task, &loading_tasks_remaining); auto load_materials_data = load_data_args<std::vector<material_data>>{ folder_access, std::vector<material_data>() }; ftl::Task load_materials_task = { load_material_files, &load_materials_data }; //task_scheduler.AddTask(load_materials_task, &loading_tasks_remaining); task_scheduler.WaitForCounter(&loading_tasks_remaining, 0); shaderpack_data data; data.pipelines = load_pipelines_data.output; data.passes = load_passes_data.output; data.resources = load_resources_data.output; delete folder_access; return data; } folder_accessor_base* get_shaderpack_accessor(const fs::path &shaderpack_name) { folder_accessor_base* folder_access = nullptr; fs::path path_to_shaderpack = SHADERPACK_ROOT / shaderpack_name; // Where is the shaderpack, and what kind of folder is it in? if(is_zip_folder(path_to_shaderpack)) { // zip folder in shaderpacks folder path_to_shaderpack.replace_extension(".zip"); folder_access = new zip_folder_accessor(path_to_shaderpack); } else if(std::experimental::filesystem::v1::exists(path_to_shaderpack)) { // regular folder in shaderpacks folder folder_access = new regular_folder_accessor(path_to_shaderpack); } else { path_to_shaderpack = BEDROCK_SHADERPACK_ROOT / shaderpack_name; if(is_zip_folder(path_to_shaderpack)) { // zip folder in the resourcepacks folder path_to_shaderpack.replace_extension(".zip"); folder_access = new zip_folder_accessor(path_to_shaderpack); } else if(std::experimental::filesystem::v1::exists(path_to_shaderpack)) { folder_access = new regular_folder_accessor(path_to_shaderpack); } } if(folder_access == nullptr) { throw resource_not_found_error(shaderpack_name.string()); } return folder_access; } void load_dynamic_resources_file(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_data_args<shaderpack_resources_data>*>(arg); try { std::string resources_string = args->folder_access->read_text_file("resources.json"); auto json_resource = nlohmann::json::parse(resources_string.c_str()); auto resources = json_resource.get<shaderpack_resources_data>(); args->output.samplers = std::move(resources.samplers); args->output.textures = std::move(resources.textures); } catch(resource_not_found_error&) { // No resources defined.. I guess they think they don't need any? NOVA_LOG(DEBUG) << "No resources file found for shaderpack"; } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse your shaderpack's resources.json: " << err.what(); } } void load_passes_file(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_data_args<std::vector<render_pass_data>>*>(arg); auto passes_bytes = args->folder_access->read_text_file("passes.json"); try { auto json_passes = nlohmann::json::parse(passes_bytes); auto passes = json_passes.get<std::vector<render_pass_data>>(); args->output = std::move(passes); } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse your shaderpack's passes.json: " << err.what(); } } struct load_pipeline_data { folder_accessor_base* folder_access; size_t out_idx; std::vector<pipeline_data>* output; const fs::path* pipeline_path; }; void load_pipeline_files(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_data_args<std::vector<pipeline_data>>*>(arg); auto potential_pipeline_files = args->folder_access->get_all_items_in_folder("materials"); // The resize will make this vector about twice as big as it should be, but there won't be any reallocating // so I'm into it std::vector<pipeline_data> pipeline_data_promises; pipeline_data_promises.resize(potential_pipeline_files.size()); uint32_t num_pipelines = 0; ftl::AtomicCounter pipeline_load_tasks_remaining(task_scheduler); std::vector<load_pipeline_data> datas; for(const fs::path& potential_file : potential_pipeline_files) { if(potential_file.extension() == ".pipeline") { // Pipeline file! load_pipeline_data data_for_loading_pipeline; data_for_loading_pipeline.folder_access = args->folder_access; data_for_loading_pipeline.out_idx = num_pipelines; data_for_loading_pipeline.output = &pipeline_data_promises; data_for_loading_pipeline.pipeline_path = &potential_file; datas.emplace_back(data_for_loading_pipeline); ftl::Task load_single_pipeline_task = { load_single_pipeline, &datas[num_pipelines] }; task_scheduler->AddTask(load_single_pipeline_task, &pipeline_load_tasks_remaining); num_pipelines++; } } task_scheduler->WaitForCounter(&pipeline_load_tasks_remaining, 0); args->output.resize(num_pipelines); for(uint32_t i = 0; i < num_pipelines; i++) { args->output.push_back(pipeline_data_promises.at(i)); } } void load_single_pipeline(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_pipeline_data*>(arg); auto pipeline_bytes = args->folder_access->read_text_file(*args->pipeline_path); try { auto json_pipeline = nlohmann::json::parse(pipeline_bytes); auto pipeline = json_pipeline.get<pipeline_data>(); args->output->emplace(args->output->begin() + args->out_idx, pipeline); } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse pipeline file " << args->pipeline_path->string() << ": " << err.what(); } } struct load_material_data { folder_accessor_base* folder_access; size_t out_idx; std::vector<material_data>* output; const fs::path* material_path; }; void load_material_files(ftl::TaskScheduler * task_scheduler, void * arg) { auto* args = static_cast<load_data_args<std::vector<material_data>>*>(arg); auto potential_material_files = args->folder_access->get_all_items_in_folder("materials"); // The resize will make this vector about twice as big as it should be, but there won't be any reallocating // so I'm into it std::vector<material_data> loaded_material_data; loaded_material_data.resize(potential_material_files.size()); size_t cur_promise = 0; ftl::AtomicCounter material_load_tasks_remaining(task_scheduler); uint32_t num_materials = 0; std::vector<load_material_data> datas; for(const fs::path& potential_file : potential_material_files) { if(potential_file.extension() == ".mat") { // Material file! load_material_data data_for_loading_material; data_for_loading_material.folder_access = args->folder_access; data_for_loading_material.material_path = &potential_file; data_for_loading_material.out_idx = num_materials; data_for_loading_material.output = &loaded_material_data; datas.emplace_back(data_for_loading_material); ftl::Task load_single_material_task = { load_single_material, &datas[num_materials] }; task_scheduler->AddTask(load_single_material_task, &material_load_tasks_remaining); num_materials++; } } task_scheduler->WaitForCounter(&material_load_tasks_remaining, 0); args->output.resize(num_materials); for(uint32_t i = 0; i < num_materials; i++) { args->output.push_back(loaded_material_data.at(i)); } } void load_single_material(ftl::TaskScheduler * task_scheduler, void * arg) { auto* args = static_cast<load_material_data*>(arg); auto material_bytes = args->folder_access->read_text_file(*args->material_path); try { auto json_material = nlohmann::json::parse(material_bytes); auto material = json_material.get<material_data>(); args->output->emplace(args->output->begin() + args->out_idx, material); } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse material file " << args->material_path->string() << ": " << err.what(); } } } <commit_msg>Windows is bad...<commit_after>/*! * \author ddubois * \date 21-Aug-18. */ #include "shaderpack_loading.hpp" #include "../folder_accessor.hpp" #include "../loading_utils.hpp" #include "../zip_folder_accessor.hpp" #include "../regular_folder_accessor.hpp" #include "../utils.hpp" #include "json_interop.hpp" #include <ftl/atomic_counter.h> namespace nova { fs::path SHADERPACK_ROOT("shaderpacks"); fs::path BEDROCK_SHADERPACK_ROOT("resourcepacks"); folder_accessor_base* get_shaderpack_accessor(const fs::path &shaderpack_name); void load_dynamic_resources_file(ftl::TaskScheduler *task_scheduler, void *arg); void load_passes_file(ftl::TaskScheduler *task_scheduler, void *arg); void load_pipeline_files(ftl::TaskScheduler *task_scheduler, void *arg); void load_single_pipeline(ftl::TaskScheduler *task_scheduler, void *arg); void load_material_files(ftl::TaskScheduler *task_scheduler, void *arg); void load_single_material(ftl::TaskScheduler *task_scheduler, void *arg); template<typename DataType> struct load_data_args { folder_accessor_base* folder_access; DataType output; }; shaderpack_data load_shaderpack_data(const fs::path& shaderpack_name, ftl::TaskScheduler& task_scheduler) { folder_accessor_base* folder_access = get_shaderpack_accessor(shaderpack_name); // The shaderpack has a number of items: There's the shaders themselves, of course, but there's so, so much more // What else is there? // - resources.json, to describe the dynamic resources that a shaderpack needs // - passes.json, to describe the frame graph itself // - All the pipeline descriptions // - All the material descriptions // // All these things are loaded from the filesystem ftl::AtomicCounter loading_tasks_remaining(&task_scheduler); // Load resource definitions auto load_resources_data = load_data_args<shaderpack_resources_data>{folder_access, shaderpack_resources_data()}; ftl::Task load_dynamic_resource_task = { load_dynamic_resources_file, &load_resources_data }; task_scheduler.AddTask(load_dynamic_resource_task, &loading_tasks_remaining); // Load pass definitions auto load_passes_data = load_data_args<std::vector<render_pass_data>>{folder_access, std::vector<render_pass_data>()}; ftl::Task load_passes_task = { load_passes_file, &load_passes_data }; task_scheduler.AddTask(load_passes_task, &loading_tasks_remaining); // Load pipeline definitions auto load_pipelines_data = load_data_args<std::vector<pipeline_data>>{folder_access, std::vector<pipeline_data>()}; ftl::Task load_pipelines_task = { load_pipeline_files, &load_pipelines_data }; //task_scheduler.AddTask(load_pipelines_task, &loading_tasks_remaining); auto load_materials_data = load_data_args<std::vector<material_data>>{ folder_access, std::vector<material_data>() }; ftl::Task load_materials_task = { load_material_files, &load_materials_data }; //task_scheduler.AddTask(load_materials_task, &loading_tasks_remaining); task_scheduler.WaitForCounter(&loading_tasks_remaining, 0); shaderpack_data data; data.pipelines = load_pipelines_data.output; data.passes = load_passes_data.output; data.resources = load_resources_data.output; delete folder_access; return data; } folder_accessor_base* get_shaderpack_accessor(const fs::path &shaderpack_name) { folder_accessor_base* folder_access = nullptr; fs::path path_to_shaderpack = SHADERPACK_ROOT / shaderpack_name; // Where is the shaderpack, and what kind of folder is it in? if(is_zip_folder(path_to_shaderpack)) { // zip folder in shaderpacks folder path_to_shaderpack.replace_extension(".zip"); folder_access = new zip_folder_accessor(path_to_shaderpack); } else if(std::experimental::filesystem::v1::exists(path_to_shaderpack)) { // regular folder in shaderpacks folder folder_access = new regular_folder_accessor(path_to_shaderpack); } else { path_to_shaderpack = BEDROCK_SHADERPACK_ROOT / shaderpack_name; if(is_zip_folder(path_to_shaderpack)) { // zip folder in the resourcepacks folder path_to_shaderpack.replace_extension(".zip"); folder_access = new zip_folder_accessor(path_to_shaderpack); } else if(std::experimental::filesystem::v1::exists(path_to_shaderpack)) { folder_access = new regular_folder_accessor(path_to_shaderpack); } } if(folder_access == nullptr) { throw resource_not_found_error(shaderpack_name.string()); } return folder_access; } void load_dynamic_resources_file(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_data_args<shaderpack_resources_data>*>(arg); try { std::string resources_string = args->folder_access->read_text_file("resources.json"); auto json_resource = nlohmann::json::parse(resources_string.c_str()); auto resources = json_resource.get<shaderpack_resources_data>(); args->output.samplers = std::move(resources.samplers); args->output.textures = std::move(resources.textures); } catch(resource_not_found_error&) { // No resources defined.. I guess they think they don't need any? NOVA_LOG(DEBUG) << "No resources file found for shaderpack"; } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse your shaderpack's resources.json: " << err.what(); } } void load_passes_file(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_data_args<std::vector<render_pass_data>>*>(arg); auto passes_bytes = args->folder_access->read_text_file("passes.json"); try { auto json_passes = nlohmann::json::parse(passes_bytes); auto passes = json_passes.get<std::vector<render_pass_data>>(); args->output = std::move(passes); } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse your shaderpack's passes.json: " << err.what(); } } struct load_pipeline_data { folder_accessor_base* folder_access; size_t out_idx; std::vector<pipeline_data>* output; const fs::path* pipeline_path; }; void load_pipeline_files(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_data_args<std::vector<pipeline_data>>*>(arg); auto potential_pipeline_files = args->folder_access->get_all_items_in_folder("materials"); // The resize will make this vector about twice as big as it should be, but there won't be any reallocating // so I'm into it std::vector<pipeline_data> pipeline_data_promises; pipeline_data_promises.resize(potential_pipeline_files.size()); uint32_t num_pipelines = 0; ftl::AtomicCounter pipeline_load_tasks_remaining(task_scheduler); std::vector<load_pipeline_data> datas; for(const fs::path& potential_file : potential_pipeline_files) { if(potential_file.extension() == ".pipeline") { // Pipeline file! load_pipeline_data data_for_loading_pipeline; data_for_loading_pipeline.folder_access = args->folder_access; data_for_loading_pipeline.out_idx = num_pipelines; data_for_loading_pipeline.output = &pipeline_data_promises; data_for_loading_pipeline.pipeline_path = &potential_file; datas.emplace_back(data_for_loading_pipeline); ftl::Task load_single_pipeline_task = { load_single_pipeline, &datas[num_pipelines] }; task_scheduler->AddTask(load_single_pipeline_task, &pipeline_load_tasks_remaining); num_pipelines++; } } task_scheduler->WaitForCounter(&pipeline_load_tasks_remaining, 0); args->output.resize(num_pipelines); for(uint32_t i = 0; i < num_pipelines; i++) { args->output.push_back(pipeline_data_promises.at(i)); } } void load_single_pipeline(ftl::TaskScheduler *task_scheduler, void *arg) { auto* args = static_cast<load_pipeline_data*>(arg); auto pipeline_bytes = args->folder_access->read_text_file(*args->pipeline_path); try { auto json_pipeline = nlohmann::json::parse(pipeline_bytes); auto pipeline = json_pipeline.get<pipeline_data>(); args->output->emplace(args->output->begin() + args->out_idx, pipeline); } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse pipeline file " << args->pipeline_path->string() << ": " << err.what(); } } struct load_material_data { folder_accessor_base* folder_access; size_t out_idx; std::vector<material_data>* output; const fs::path* material_path; }; void load_material_files(ftl::TaskScheduler * task_scheduler, void * arg) { auto* args = static_cast<load_data_args<std::vector<material_data>>*>(arg); auto potential_material_files = args->folder_access->get_all_items_in_folder("materials"); // The resize will make this vector about twice as big as it should be, but there won't be any reallocating // so I'm into it std::vector<material_data> loaded_material_data; loaded_material_data.resize(potential_material_files.size()); size_t cur_promise = 0; ftl::AtomicCounter material_load_tasks_remaining(task_scheduler); uint32_t num_materials = 0; std::vector<load_material_data> datas; for(const fs::path& potential_file : potential_material_files) { if(potential_file.extension() == ".mat") { // Material file! load_material_data data_for_loading_material; data_for_loading_material.folder_access = args->folder_access; data_for_loading_material.material_path = &potential_file; data_for_loading_material.out_idx = num_materials; data_for_loading_material.output = &loaded_material_data; datas.emplace_back(data_for_loading_material); ftl::Task load_single_material_task = { load_single_material, &datas[num_materials] }; task_scheduler->AddTask(load_single_material_task, &material_load_tasks_remaining); num_materials++; } } task_scheduler->WaitForCounter(&material_load_tasks_remaining, 0); args->output.resize(num_materials); for(uint32_t i = 0; i < num_materials; i++) { args->output.push_back(loaded_material_data.at(i)); } } void load_single_material(ftl::TaskScheduler * task_scheduler, void * arg) { auto* args = static_cast<load_material_data*>(arg); auto material_bytes = args->folder_access->read_text_file(*args->material_path); try { auto json_material = nlohmann::json::parse(material_bytes); auto material = json_material.get<material_data>(); args->output->emplace(args->output->begin() + args->out_idx, material); } catch(nlohmann::json::parse_error& err) { NOVA_LOG(ERROR) << "Could not parse material file " << args->material_path->string() << ": " << err.what(); } } } <|endoftext|>
<commit_before>//=- ClangSACheckersEmitter.cpp - Generate Clang SA checkers tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits Clang Static Analyzer checkers tables. // //===----------------------------------------------------------------------===// #include "ClangSACheckersEmitter.h" #include "Record.h" #include "llvm/ADT/DenseSet.h" #include <map> #include <string> using namespace llvm; //===----------------------------------------------------------------------===// // Static Analyzer Checkers Tables generation //===----------------------------------------------------------------------===// /// \brief True if it is specified hidden or a parent package is specified /// as hidden, otherwise false. static bool isHidden(const Record &R) { if (R.getValueAsBit("Hidden")) return true; // Not declared as hidden, check the parent package if it is hidden. if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("ParentPackage"))) return isHidden(*DI->getDef()); return false; } static bool isCheckerNamed(const Record *R) { return !R->getValueAsString("CheckerName").empty(); } static std::string getPackageFullName(const Record *R); static std::string getParentPackageFullName(const Record *R) { std::string name; if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage"))) name = getPackageFullName(DI->getDef()); return name; } static std::string getPackageFullName(const Record *R) { std::string name = getParentPackageFullName(R); if (!name.empty()) name += "."; return name + R->getValueAsString("PackageName"); } static std::string getCheckerFullName(const Record *R) { std::string name = getParentPackageFullName(R); if (isCheckerNamed(R)) { if (!name.empty()) name += "."; name += R->getValueAsString("CheckerName"); } return name; } static std::string getStringValue(const Record &R, StringRef field) { if (StringInit * SI = dynamic_cast<StringInit*>(R.getValueInit(field))) return SI->getValue(); return std::string(); } namespace { struct GroupInfo { llvm::DenseSet<const Record*> Checkers; llvm::DenseSet<const Record *> SubGroups; bool Hidden; unsigned Index; GroupInfo() : Hidden(false) { } }; } static void addPackageToCheckerGroup(const Record *package, const Record *group, llvm::DenseMap<const Record *, GroupInfo *> &recordGroupMap) { llvm::DenseSet<const Record *> &checkers = recordGroupMap[package]->Checkers; for (llvm::DenseSet<const Record *>::iterator I = checkers.begin(), E = checkers.end(); I != E; ++I) recordGroupMap[group]->Checkers.insert(*I); llvm::DenseSet<const Record *> &subGroups = recordGroupMap[package]->SubGroups; for (llvm::DenseSet<const Record *>::iterator I = subGroups.begin(), E = subGroups.end(); I != E; ++I) addPackageToCheckerGroup(*I, group, recordGroupMap); } void ClangSACheckersEmitter::run(raw_ostream &OS) { std::vector<Record*> checkers = Records.getAllDerivedDefinitions("Checker"); llvm::DenseMap<const Record *, unsigned> checkerRecIndexMap; for (unsigned i = 0, e = checkers.size(); i != e; ++i) checkerRecIndexMap[checkers[i]] = i; OS << "\n#ifdef GET_CHECKERS\n"; for (unsigned i = 0, e = checkers.size(); i != e; ++i) { const Record &R = *checkers[i]; OS << "CHECKER(" << "\""; std::string name; if (isCheckerNamed(&R)) name = getCheckerFullName(&R); OS.write_escaped(name) << "\", "; OS << R.getName() << ", "; OS << getStringValue(R, "DescFile") << ", "; OS << "\""; OS.write_escaped(getStringValue(R, "HelpText")) << "\", "; // Hidden bit if (isHidden(R)) OS << "true"; else OS << "false"; OS << ")\n"; } OS << "#endif // GET_CHECKERS\n\n"; // Invert the mapping of checkers to package/group into a one to many // mapping of packages/groups to checkers. std::map<std::string, GroupInfo> groupInfoByName; llvm::DenseMap<const Record *, GroupInfo *> recordGroupMap; std::vector<Record*> packages = Records.getAllDerivedDefinitions("Package"); for (unsigned i = 0, e = packages.size(); i != e; ++i) { Record *R = packages[i]; std::string fullName = getPackageFullName(R); if (!fullName.empty()) { GroupInfo &info = groupInfoByName[fullName]; info.Hidden = isHidden(*R); recordGroupMap[R] = &info; } } std::vector<Record*> checkerGroups = Records.getAllDerivedDefinitions("CheckerGroup"); for (unsigned i = 0, e = checkerGroups.size(); i != e; ++i) { Record *R = checkerGroups[i]; std::string name = R->getValueAsString("GroupName"); if (!name.empty()) { GroupInfo &info = groupInfoByName[name]; recordGroupMap[R] = &info; } } for (unsigned i = 0, e = checkers.size(); i != e; ++i) { Record *R = checkers[i]; Record *package = 0; if (DefInit * DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage"))) package = DI->getDef(); if (!isCheckerNamed(R) && !package) throw "Checker '" + R->getName() + "' is neither named, nor in a package!"; if (isCheckerNamed(R)) { // Create a pseudo-group to hold this checker. std::string fullName = getCheckerFullName(R); GroupInfo &info = groupInfoByName[fullName]; info.Hidden = R->getValueAsBit("Hidden"); recordGroupMap[R] = &info; info.Checkers.insert(R); } else { recordGroupMap[package]->Checkers.insert(R); } Record *currR = isCheckerNamed(R) ? R : package; // Insert the checker and its parent packages into the subgroups set of // the corresponding parent package. while (DefInit *DI = dynamic_cast<DefInit*>(currR->getValueInit("ParentPackage"))) { Record *parentPackage = DI->getDef(); recordGroupMap[parentPackage]->SubGroups.insert(currR); currR = parentPackage; } // Insert the checker into the set of its group. if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"))) recordGroupMap[DI->getDef()]->Checkers.insert(R); } // If a package is in group, add all its checkers and its sub-packages // checkers into the group. for (unsigned i = 0, e = packages.size(); i != e; ++i) if (DefInit *DI = dynamic_cast<DefInit*>(packages[i]->getValueInit("Group"))) addPackageToCheckerGroup(packages[i], DI->getDef(), recordGroupMap); unsigned index = 0; for (std::map<std::string, GroupInfo>::iterator I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) I->second.Index = index++; // Walk through the packages/groups/checkers emitting an array for each // set of checkers and an array for each set of subpackages. OS << "\n#ifdef GET_MEMBER_ARRAYS\n"; unsigned maxLen = 0; for (std::map<std::string, GroupInfo>::iterator I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) { maxLen = std::max(maxLen, (unsigned)I->first.size()); llvm::DenseSet<const Record *> &checkers = I->second.Checkers; if (!checkers.empty()) { OS << "static const short CheckerArray" << I->second.Index << "[] = { "; for (llvm::DenseSet<const Record *>::iterator I = checkers.begin(), E = checkers.end(); I != E; ++I) OS << checkerRecIndexMap[*I] << ", "; OS << "-1 };\n"; } llvm::DenseSet<const Record *> &subGroups = I->second.SubGroups; if (!subGroups.empty()) { OS << "static const short SubPackageArray" << I->second.Index << "[] = { "; for (llvm::DenseSet<const Record *>::iterator I = subGroups.begin(), E = subGroups.end(); I != E; ++I) { OS << recordGroupMap[*I]->Index << ", "; } OS << "-1 };\n"; } } OS << "#endif // GET_MEMBER_ARRAYS\n\n"; OS << "\n#ifdef GET_CHECKNAME_TABLE\n"; for (std::map<std::string, GroupInfo>::iterator I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) { // Group option string. OS << " { \""; OS.write_escaped(I->first) << "\"," << std::string(maxLen-I->first.size()+1, ' '); if (I->second.Checkers.empty()) OS << "0, "; else OS << "CheckerArray" << I->second.Index << ", "; // Subgroups. if (I->second.SubGroups.empty()) OS << "0, "; else OS << "SubPackageArray" << I->second.Index << ", "; OS << (I->second.Hidden ? "true" : "false"); OS << " },\n"; } OS << "#endif // GET_CHECKNAME_TABLE\n\n"; } <commit_msg>In ClangSACheckersEmitter: - Also emit a list of packages and groups sorted by name - Avoid iterating over DenseSet so that the output of the arrays is deterministic.<commit_after>//=- ClangSACheckersEmitter.cpp - Generate Clang SA checkers tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits Clang Static Analyzer checkers tables. // //===----------------------------------------------------------------------===// #include "ClangSACheckersEmitter.h" #include "Record.h" #include "llvm/ADT/DenseSet.h" #include <map> #include <string> using namespace llvm; //===----------------------------------------------------------------------===// // Static Analyzer Checkers Tables generation //===----------------------------------------------------------------------===// /// \brief True if it is specified hidden or a parent package is specified /// as hidden, otherwise false. static bool isHidden(const Record &R) { if (R.getValueAsBit("Hidden")) return true; // Not declared as hidden, check the parent package if it is hidden. if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("ParentPackage"))) return isHidden(*DI->getDef()); return false; } static bool isCheckerNamed(const Record *R) { return !R->getValueAsString("CheckerName").empty(); } static std::string getPackageFullName(const Record *R); static std::string getParentPackageFullName(const Record *R) { std::string name; if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage"))) name = getPackageFullName(DI->getDef()); return name; } static std::string getPackageFullName(const Record *R) { std::string name = getParentPackageFullName(R); if (!name.empty()) name += "."; return name + R->getValueAsString("PackageName"); } static std::string getCheckerFullName(const Record *R) { std::string name = getParentPackageFullName(R); if (isCheckerNamed(R)) { if (!name.empty()) name += "."; name += R->getValueAsString("CheckerName"); } return name; } static std::string getStringValue(const Record &R, StringRef field) { if (StringInit * SI = dynamic_cast<StringInit*>(R.getValueInit(field))) return SI->getValue(); return std::string(); } namespace { struct GroupInfo { llvm::DenseSet<const Record*> Checkers; llvm::DenseSet<const Record *> SubGroups; bool Hidden; unsigned Index; GroupInfo() : Hidden(false) { } }; } static void addPackageToCheckerGroup(const Record *package, const Record *group, llvm::DenseMap<const Record *, GroupInfo *> &recordGroupMap) { llvm::DenseSet<const Record *> &checkers = recordGroupMap[package]->Checkers; for (llvm::DenseSet<const Record *>::iterator I = checkers.begin(), E = checkers.end(); I != E; ++I) recordGroupMap[group]->Checkers.insert(*I); llvm::DenseSet<const Record *> &subGroups = recordGroupMap[package]->SubGroups; for (llvm::DenseSet<const Record *>::iterator I = subGroups.begin(), E = subGroups.end(); I != E; ++I) addPackageToCheckerGroup(*I, group, recordGroupMap); } void ClangSACheckersEmitter::run(raw_ostream &OS) { std::vector<Record*> checkers = Records.getAllDerivedDefinitions("Checker"); llvm::DenseMap<const Record *, unsigned> checkerRecIndexMap; for (unsigned i = 0, e = checkers.size(); i != e; ++i) checkerRecIndexMap[checkers[i]] = i; OS << "\n#ifdef GET_CHECKERS\n"; for (unsigned i = 0, e = checkers.size(); i != e; ++i) { const Record &R = *checkers[i]; OS << "CHECKER(" << "\""; std::string name; if (isCheckerNamed(&R)) name = getCheckerFullName(&R); OS.write_escaped(name) << "\", "; OS << R.getName() << ", "; OS << getStringValue(R, "DescFile") << ", "; OS << "\""; OS.write_escaped(getStringValue(R, "HelpText")) << "\", "; // Hidden bit if (isHidden(R)) OS << "true"; else OS << "false"; OS << ")\n"; } OS << "#endif // GET_CHECKERS\n\n"; // Invert the mapping of checkers to package/group into a one to many // mapping of packages/groups to checkers. std::map<std::string, GroupInfo> groupInfoByName; llvm::DenseMap<const Record *, GroupInfo *> recordGroupMap; std::vector<Record*> packages = Records.getAllDerivedDefinitions("Package"); for (unsigned i = 0, e = packages.size(); i != e; ++i) { Record *R = packages[i]; std::string fullName = getPackageFullName(R); if (!fullName.empty()) { GroupInfo &info = groupInfoByName[fullName]; info.Hidden = isHidden(*R); recordGroupMap[R] = &info; } } std::vector<Record*> checkerGroups = Records.getAllDerivedDefinitions("CheckerGroup"); for (unsigned i = 0, e = checkerGroups.size(); i != e; ++i) { Record *R = checkerGroups[i]; std::string name = R->getValueAsString("GroupName"); if (!name.empty()) { GroupInfo &info = groupInfoByName[name]; recordGroupMap[R] = &info; } } typedef std::map<std::string, const Record *> SortedRecords; OS << "\n#ifdef GET_PACKAGES\n"; { SortedRecords sortedPackages; for (unsigned i = 0, e = packages.size(); i != e; ++i) sortedPackages[getPackageFullName(packages[i])] = packages[i]; for (SortedRecords::iterator I = sortedPackages.begin(), E = sortedPackages.end(); I != E; ++I) { const Record &R = *I->second; OS << "PACKAGE(" << "\""; OS.write_escaped(getPackageFullName(&R)) << "\", "; // Hidden bit if (isHidden(R)) OS << "true"; else OS << "false"; OS << ")\n"; } } OS << "#endif // GET_PACKAGES\n\n"; OS << "\n#ifdef GET_GROUPS\n"; { SortedRecords sortedGroups; for (unsigned i = 0, e = checkerGroups.size(); i != e; ++i) sortedGroups[checkerGroups[i]->getValueAsString("GroupName")] = checkerGroups[i]; for (SortedRecords::iterator I = sortedGroups.begin(), E = sortedGroups.end(); I != E; ++I) { const Record &R = *I->second; OS << "GROUP(" << "\""; OS.write_escaped(R.getValueAsString("GroupName")) << "\""; OS << ")\n"; } } OS << "#endif // GET_GROUPS\n\n"; for (unsigned i = 0, e = checkers.size(); i != e; ++i) { Record *R = checkers[i]; Record *package = 0; if (DefInit * DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage"))) package = DI->getDef(); if (!isCheckerNamed(R) && !package) throw "Checker '" + R->getName() + "' is neither named, nor in a package!"; if (isCheckerNamed(R)) { // Create a pseudo-group to hold this checker. std::string fullName = getCheckerFullName(R); GroupInfo &info = groupInfoByName[fullName]; info.Hidden = R->getValueAsBit("Hidden"); recordGroupMap[R] = &info; info.Checkers.insert(R); } else { recordGroupMap[package]->Checkers.insert(R); } Record *currR = isCheckerNamed(R) ? R : package; // Insert the checker and its parent packages into the subgroups set of // the corresponding parent package. while (DefInit *DI = dynamic_cast<DefInit*>(currR->getValueInit("ParentPackage"))) { Record *parentPackage = DI->getDef(); recordGroupMap[parentPackage]->SubGroups.insert(currR); currR = parentPackage; } // Insert the checker into the set of its group. if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"))) recordGroupMap[DI->getDef()]->Checkers.insert(R); } // If a package is in group, add all its checkers and its sub-packages // checkers into the group. for (unsigned i = 0, e = packages.size(); i != e; ++i) if (DefInit *DI = dynamic_cast<DefInit*>(packages[i]->getValueInit("Group"))) addPackageToCheckerGroup(packages[i], DI->getDef(), recordGroupMap); unsigned index = 0; for (std::map<std::string, GroupInfo>::iterator I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) I->second.Index = index++; // Walk through the packages/groups/checkers emitting an array for each // set of checkers and an array for each set of subpackages. OS << "\n#ifdef GET_MEMBER_ARRAYS\n"; unsigned maxLen = 0; for (std::map<std::string, GroupInfo>::iterator I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) { maxLen = std::max(maxLen, (unsigned)I->first.size()); llvm::DenseSet<const Record *> &checkers = I->second.Checkers; if (!checkers.empty()) { // Make the output order deterministic. std::map<int, const Record *> sorted; for (llvm::DenseSet<const Record *>::iterator I = checkers.begin(), E = checkers.end(); I != E; ++I) sorted[(*I)->getID()] = *I; OS << "static const short CheckerArray" << I->second.Index << "[] = { "; for (std::map<int, const Record *>::iterator I = sorted.begin(), E = sorted.end(); I != E; ++I) OS << checkerRecIndexMap[I->second] << ", "; OS << "-1 };\n"; } llvm::DenseSet<const Record *> &subGroups = I->second.SubGroups; if (!subGroups.empty()) { // Make the output order deterministic. std::map<int, const Record *> sorted; for (llvm::DenseSet<const Record *>::iterator I = subGroups.begin(), E = subGroups.end(); I != E; ++I) sorted[(*I)->getID()] = *I; OS << "static const short SubPackageArray" << I->second.Index << "[] = { "; for (std::map<int, const Record *>::iterator I = sorted.begin(), E = sorted.end(); I != E; ++I) { OS << recordGroupMap[I->second]->Index << ", "; } OS << "-1 };\n"; } } OS << "#endif // GET_MEMBER_ARRAYS\n\n"; OS << "\n#ifdef GET_CHECKNAME_TABLE\n"; for (std::map<std::string, GroupInfo>::iterator I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) { // Group option string. OS << " { \""; OS.write_escaped(I->first) << "\"," << std::string(maxLen-I->first.size()+1, ' '); if (I->second.Checkers.empty()) OS << "0, "; else OS << "CheckerArray" << I->second.Index << ", "; // Subgroups. if (I->second.SubGroups.empty()) OS << "0, "; else OS << "SubPackageArray" << I->second.Index << ", "; OS << (I->second.Hidden ? "true" : "false"); OS << " },\n"; } OS << "#endif // GET_CHECKNAME_TABLE\n\n"; } <|endoftext|>
<commit_before>/** * @file llfloaterconversationpreview.cpp * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llconversationlog.h" #include "llfloaterconversationpreview.h" #include "llimview.h" #include "lllineeditor.h" // <FS:CR> [FS communication UI] //#include "llfloaterimnearbychat.h" #include "fsfloaternearbychat.h" // </FS:CR> [FS communication UI] #include "llspinctrl.h" #include "lltrans.h" // <FS:CR> #include "llviewercontrol.h" #include "llavataractions.h" // </FS:CR> const std::string LL_FCP_COMPLETE_NAME("complete_name"); const std::string LL_FCP_ACCOUNT_NAME("user_name"); LLFloaterConversationPreview::LLFloaterConversationPreview(const LLSD& session_id) : LLFloater(session_id), mChatHistory(NULL), mSessionID(session_id.asUUID()), mCurrentPage(0), mPageSize(gSavedSettings.getS32("ConversationHistoryPageSize")), mAccountName(session_id[LL_FCP_ACCOUNT_NAME]), mCompleteName(session_id[LL_FCP_COMPLETE_NAME]) { } BOOL LLFloaterConversationPreview::postBuild() { // <FS:CR> [FS communication UI] //mChatHistory = getChild<LLChatHistory>("chat_history"); mChatHistory = getChild<FSChatHistory>("chat_history"); // <FS:CR> [FS communication UI] childSetAction("open_external_btn", boost::bind(&LLFloaterConversationPreview::onBtnOpenExternal, this)); //<FS:CR> Open chat history externally const LLConversation* conv = LLConversationLog::instance().getConversation(mSessionID); std::string name; std::string file; if (mAccountName != "") { name = mCompleteName; file = mAccountName; } else if (mSessionID != LLUUID::null && conv) { name = conv->getConversationName(); file = conv->getHistoryFileName(); } else { name = LLTrans::getString("NearbyChatTitle"); file = "chat"; } LLStringUtil::format_map_t args; args["[NAME]"] = name; std::string title = getString("Title", args); setTitle(title); LLSD load_params; load_params["load_all_history"] = true; load_params["cut_off_todays_date"] = false; LLLogChat::loadChatHistory(file, mMessages, load_params); mCurrentPage = mMessages.size() / mPageSize; mPageSpinner = getChild<LLSpinCtrl>("history_page_spin"); mPageSpinner->setCommitCallback(boost::bind(&LLFloaterConversationPreview::onMoreHistoryBtnClick, this)); mPageSpinner->setMinValue(1); mPageSpinner->setMaxValue(mCurrentPage + 1); mPageSpinner->set(mCurrentPage + 1); std::string total_page_num = llformat("/ %d", mCurrentPage + 1); getChild<LLTextBox>("page_num_label")->setValue(total_page_num); return LLFloater::postBuild(); } void LLFloaterConversationPreview::draw() { LLFloater::draw(); } void LLFloaterConversationPreview::onOpen(const LLSD& key) { showHistory(); } void LLFloaterConversationPreview::showHistory() { if (!mMessages.size()) { return; } mChatHistory->clear(); std::ostringstream message; std::list<LLSD>::const_iterator iter = mMessages.begin(); int delta = 0; if (mCurrentPage) { int remainder = mMessages.size() % mPageSize; delta = (remainder == 0) ? 0 : (mPageSize - remainder); } std::advance(iter, (mCurrentPage * mPageSize) - delta); for (int msg_num = 0; (iter != mMessages.end() && msg_num < mPageSize); ++iter, ++msg_num) { LLSD msg = *iter; LLUUID from_id = LLUUID::null; std::string time = msg["time"].asString(); std::string from = msg["from"].asString(); std::string message = msg["message"].asString(); if (msg["from_id"].isDefined()) { from_id = msg["from_id"].asUUID(); } else { std::string legacy_name = gCacheName->buildLegacyName(from); gCacheName->getUUID(legacy_name, from_id); } LLChat chat; chat.mFromID = from_id; chat.mSessionID = mSessionID; chat.mFromName = from; chat.mTimeStr = time; chat.mChatStyle = CHAT_STYLE_HISTORY; chat.mText = message; if (from_id.isNull() && SYSTEM_FROM == from) { chat.mSourceType = CHAT_SOURCE_SYSTEM; } else if (from_id.isNull()) { // <FS:CR> [FS communication UI] //chat.mSourceType = LLFloaterIMNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT; chat.mSourceType = FSFloaterNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT; // </FS:CR> [FS communication UI] } LLSD chat_args; chat_args["use_plain_text_chat_history"] = gSavedSettings.getBOOL("PlainTextChatHistory"); chat_args["show_time"] = gSavedSettings.getBOOL("IMShowTime"); chat_args["show_names_for_p2p_conv"] = gSavedSettings.getBOOL("IMShowNamesForP2PConv"); mChatHistory->appendMessage(chat,chat_args); } } void LLFloaterConversationPreview::onMoreHistoryBtnClick() { mCurrentPage = (int)(mPageSpinner->getValueF32()); if (--mCurrentPage < 0) { return; } showHistory(); } // <FS:CR> Open chat history externally void (LLFloaterConversationPreview::onBtnOpenExternal()) { LLAvatarActions::viewChatHistoryExternally(mSessionID); } <commit_msg>Make open log externally button on conversation preview also work for nearby chat log<commit_after>/** * @file llfloaterconversationpreview.cpp * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llconversationlog.h" #include "llfloaterconversationpreview.h" #include "llimview.h" #include "lllineeditor.h" // <FS:CR> [FS communication UI] //#include "llfloaterimnearbychat.h" #include "fsfloaternearbychat.h" // </FS:CR> [FS communication UI] #include "llspinctrl.h" #include "lltrans.h" // <FS:CR> #include "llviewercontrol.h" #include "llavataractions.h" #include "llviewerwindow.h" #include "llwindow.h" // </FS:CR> const std::string LL_FCP_COMPLETE_NAME("complete_name"); const std::string LL_FCP_ACCOUNT_NAME("user_name"); LLFloaterConversationPreview::LLFloaterConversationPreview(const LLSD& session_id) : LLFloater(session_id), mChatHistory(NULL), mSessionID(session_id.asUUID()), mCurrentPage(0), mPageSize(gSavedSettings.getS32("ConversationHistoryPageSize")), mAccountName(session_id[LL_FCP_ACCOUNT_NAME]), mCompleteName(session_id[LL_FCP_COMPLETE_NAME]) { } BOOL LLFloaterConversationPreview::postBuild() { // <FS:CR> [FS communication UI] //mChatHistory = getChild<LLChatHistory>("chat_history"); mChatHistory = getChild<FSChatHistory>("chat_history"); // <FS:CR> [FS communication UI] childSetAction("open_external_btn", boost::bind(&LLFloaterConversationPreview::onBtnOpenExternal, this)); //<FS:CR> Open chat history externally const LLConversation* conv = LLConversationLog::instance().getConversation(mSessionID); std::string name; std::string file; if (mAccountName != "") { name = mCompleteName; file = mAccountName; } else if (mSessionID != LLUUID::null && conv) { name = conv->getConversationName(); file = conv->getHistoryFileName(); } else { name = LLTrans::getString("NearbyChatTitle"); file = "chat"; } LLStringUtil::format_map_t args; args["[NAME]"] = name; std::string title = getString("Title", args); setTitle(title); LLSD load_params; load_params["load_all_history"] = true; load_params["cut_off_todays_date"] = false; LLLogChat::loadChatHistory(file, mMessages, load_params); mCurrentPage = mMessages.size() / mPageSize; mPageSpinner = getChild<LLSpinCtrl>("history_page_spin"); mPageSpinner->setCommitCallback(boost::bind(&LLFloaterConversationPreview::onMoreHistoryBtnClick, this)); mPageSpinner->setMinValue(1); mPageSpinner->setMaxValue(mCurrentPage + 1); mPageSpinner->set(mCurrentPage + 1); std::string total_page_num = llformat("/ %d", mCurrentPage + 1); getChild<LLTextBox>("page_num_label")->setValue(total_page_num); return LLFloater::postBuild(); } void LLFloaterConversationPreview::draw() { LLFloater::draw(); } void LLFloaterConversationPreview::onOpen(const LLSD& key) { showHistory(); } void LLFloaterConversationPreview::showHistory() { if (!mMessages.size()) { return; } mChatHistory->clear(); std::ostringstream message; std::list<LLSD>::const_iterator iter = mMessages.begin(); int delta = 0; if (mCurrentPage) { int remainder = mMessages.size() % mPageSize; delta = (remainder == 0) ? 0 : (mPageSize - remainder); } std::advance(iter, (mCurrentPage * mPageSize) - delta); for (int msg_num = 0; (iter != mMessages.end() && msg_num < mPageSize); ++iter, ++msg_num) { LLSD msg = *iter; LLUUID from_id = LLUUID::null; std::string time = msg["time"].asString(); std::string from = msg["from"].asString(); std::string message = msg["message"].asString(); if (msg["from_id"].isDefined()) { from_id = msg["from_id"].asUUID(); } else { std::string legacy_name = gCacheName->buildLegacyName(from); gCacheName->getUUID(legacy_name, from_id); } LLChat chat; chat.mFromID = from_id; chat.mSessionID = mSessionID; chat.mFromName = from; chat.mTimeStr = time; chat.mChatStyle = CHAT_STYLE_HISTORY; chat.mText = message; if (from_id.isNull() && SYSTEM_FROM == from) { chat.mSourceType = CHAT_SOURCE_SYSTEM; } else if (from_id.isNull()) { // <FS:CR> [FS communication UI] //chat.mSourceType = LLFloaterIMNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT; chat.mSourceType = FSFloaterNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT; // </FS:CR> [FS communication UI] } LLSD chat_args; chat_args["use_plain_text_chat_history"] = gSavedSettings.getBOOL("PlainTextChatHistory"); chat_args["show_time"] = gSavedSettings.getBOOL("IMShowTime"); chat_args["show_names_for_p2p_conv"] = gSavedSettings.getBOOL("IMShowNamesForP2PConv"); mChatHistory->appendMessage(chat,chat_args); } } void LLFloaterConversationPreview::onMoreHistoryBtnClick() { mCurrentPage = (int)(mPageSpinner->getValueF32()); if (--mCurrentPage < 0) { return; } showHistory(); } // <FS:CR> Open chat history externally void (LLFloaterConversationPreview::onBtnOpenExternal()) { if (mSessionID.notNull()) { LLAvatarActions::viewChatHistoryExternally(mSessionID); } else { gViewerWindow->getWindow()->openFile(LLLogChat::makeLogFileName("chat")); } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/menu/menu_item_view.h" #include "base/utf_string_conversions.h" #include "grit/app_resources.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/favicon_size.h" #include "views/controls/button/text_button.h" #include "views/controls/menu/menu_config.h" #include "views/controls/menu/menu_image_util_gtk.h" #include "views/controls/menu/submenu_view.h" namespace views { // Background color when the menu item is selected. #if defined(OS_CHROMEOS) static const SkColor kSelectedBackgroundColor = SkColorSetRGB(0xDC, 0xE4, 0xFA); #else static const SkColor kSelectedBackgroundColor = SkColorSetRGB(246, 249, 253); #endif gfx::Size MenuItemView::CalculatePreferredSize() { const gfx::Font& font = MenuConfig::instance().font; // TODO(sky): this is a workaround until I figure out why font.height() // isn't returning the right thing. We really only want to include // kFaviconSize if we're showing icons. int content_height = std::max(kFaviconSize, font.GetHeight()); return gfx::Size( font.GetStringWidth(title_) + label_start_ + item_right_margin_ + GetChildPreferredWidth(), content_height + GetBottomMargin() + GetTopMargin()); } void MenuItemView::PaintButton(gfx::Canvas* canvas, PaintButtonMode mode) { const MenuConfig& config = MenuConfig::instance(); bool render_selection = (mode == PB_NORMAL && IsSelected() && parent_menu_item_->GetSubmenu()->GetShowSelection(this) && !has_children()); int icon_x = config.item_left_margin; int top_margin = GetTopMargin(); int bottom_margin = GetBottomMargin(); int icon_y = top_margin + (height() - config.item_top_margin - bottom_margin - config.check_height) / 2; int icon_height = config.check_height; int available_height = height() - top_margin - bottom_margin; // Render the background. As MenuScrollViewContainer draws the background, we // only need the background when we want it to look different, as when we're // selected. if (render_selection) canvas->AsCanvasSkia()->drawColor(kSelectedBackgroundColor, SkXfermode::kSrc_Mode); // Render the check. if (type_ == CHECKBOX && GetDelegate()->IsItemChecked(GetCommand())) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* check = rb.GetBitmapNamed(IDR_MENU_CHECK); // Don't use config.check_width here as it's padded to force more padding. gfx::Rect check_bounds(icon_x, icon_y, check->width(), icon_height); AdjustBoundsForRTLUI(&check_bounds); canvas->DrawBitmapInt(*check, check_bounds.x(), check_bounds.y()); } else if (type_ == RADIO) { const SkBitmap* image = GetRadioButtonImage(GetDelegate()->IsItemChecked(GetCommand())); gfx::Rect radio_bounds(icon_x, top_margin + (height() - top_margin - bottom_margin - image->height()) / 2, image->width(), image->height()); AdjustBoundsForRTLUI(&radio_bounds); canvas->DrawBitmapInt(*image, radio_bounds.x(), radio_bounds.y()); } // Render the foreground. #if defined(OS_CHROMEOS) SkColor fg_color = IsEnabled() ? SK_ColorBLACK : SkColorSetRGB(0x80, 0x80, 0x80); #else SkColor fg_color = IsEnabled() ? TextButton::kEnabledColor : TextButton::kDisabledColor; #endif const gfx::Font& font = MenuConfig::instance().font; int accel_width = parent_menu_item_->GetSubmenu()->max_accelerator_width(); int width = this->width() - item_right_margin_ - label_start_ - accel_width; gfx::Rect text_bounds(label_start_, top_margin + (available_height - font.GetHeight()) / 2, width, font.GetHeight()); text_bounds.set_x(GetMirroredXForRect(text_bounds)); canvas->DrawStringInt(WideToUTF16Hack(GetTitle()), font, fg_color, text_bounds.x(), text_bounds.y(), text_bounds.width(), text_bounds.height(), GetRootMenuItem()->GetDrawStringFlags()); PaintAccelerator(canvas); // Render the icon. if (icon_.width() > 0) { gfx::Rect icon_bounds(config.item_left_margin, top_margin + (height() - top_margin - bottom_margin - icon_.height()) / 2, icon_.width(), icon_.height()); icon_bounds.set_x(GetMirroredXForRect(icon_bounds)); canvas->DrawBitmapInt(icon_, icon_bounds.x(), icon_bounds.y()); } // Render the submenu indicator (arrow). if (HasSubmenu()) { gfx::Rect arrow_bounds(this->width() - item_right_margin_ + config.label_to_arrow_padding, top_margin + (available_height - config.arrow_width) / 2, config.arrow_width, height()); AdjustBoundsForRTLUI(&arrow_bounds); canvas->DrawBitmapInt(*GetSubmenuArrowImage(), arrow_bounds.x(), arrow_bounds.y()); } } } // namespace views <commit_msg>Revert workaround. This was problematic because it is relying on an unrelated constant (kFavicon) which now has a different value for the touch case.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/menu/menu_item_view.h" #include "base/utf_string_conversions.h" #include "grit/app_resources.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/favicon_size.h" #include "views/controls/button/text_button.h" #include "views/controls/menu/menu_config.h" #include "views/controls/menu/menu_image_util_gtk.h" #include "views/controls/menu/submenu_view.h" namespace views { // Background color when the menu item is selected. #if defined(OS_CHROMEOS) static const SkColor kSelectedBackgroundColor = SkColorSetRGB(0xDC, 0xE4, 0xFA); #else static const SkColor kSelectedBackgroundColor = SkColorSetRGB(246, 249, 253); #endif gfx::Size MenuItemView::CalculatePreferredSize() { const gfx::Font& font = MenuConfig::instance().font; return gfx::Size( font.GetStringWidth(title_) + label_start_ + item_right_margin_ + GetChildPreferredWidth(), font.GetHeight() + GetBottomMargin() + GetTopMargin()); } void MenuItemView::PaintButton(gfx::Canvas* canvas, PaintButtonMode mode) { const MenuConfig& config = MenuConfig::instance(); bool render_selection = (mode == PB_NORMAL && IsSelected() && parent_menu_item_->GetSubmenu()->GetShowSelection(this) && !has_children()); int icon_x = config.item_left_margin; int top_margin = GetTopMargin(); int bottom_margin = GetBottomMargin(); int icon_y = top_margin + (height() - config.item_top_margin - bottom_margin - config.check_height) / 2; int icon_height = config.check_height; int available_height = height() - top_margin - bottom_margin; // Render the background. As MenuScrollViewContainer draws the background, we // only need the background when we want it to look different, as when we're // selected. if (render_selection) canvas->AsCanvasSkia()->drawColor(kSelectedBackgroundColor, SkXfermode::kSrc_Mode); // Render the check. if (type_ == CHECKBOX && GetDelegate()->IsItemChecked(GetCommand())) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* check = rb.GetBitmapNamed(IDR_MENU_CHECK); // Don't use config.check_width here as it's padded to force more padding. gfx::Rect check_bounds(icon_x, icon_y, check->width(), icon_height); AdjustBoundsForRTLUI(&check_bounds); canvas->DrawBitmapInt(*check, check_bounds.x(), check_bounds.y()); } else if (type_ == RADIO) { const SkBitmap* image = GetRadioButtonImage(GetDelegate()->IsItemChecked(GetCommand())); gfx::Rect radio_bounds(icon_x, top_margin + (height() - top_margin - bottom_margin - image->height()) / 2, image->width(), image->height()); AdjustBoundsForRTLUI(&radio_bounds); canvas->DrawBitmapInt(*image, radio_bounds.x(), radio_bounds.y()); } // Render the foreground. #if defined(OS_CHROMEOS) SkColor fg_color = IsEnabled() ? SK_ColorBLACK : SkColorSetRGB(0x80, 0x80, 0x80); #else SkColor fg_color = IsEnabled() ? TextButton::kEnabledColor : TextButton::kDisabledColor; #endif const gfx::Font& font = MenuConfig::instance().font; int accel_width = parent_menu_item_->GetSubmenu()->max_accelerator_width(); int width = this->width() - item_right_margin_ - label_start_ - accel_width; gfx::Rect text_bounds(label_start_, top_margin + (available_height - font.GetHeight()) / 2, width, font.GetHeight()); text_bounds.set_x(GetMirroredXForRect(text_bounds)); canvas->DrawStringInt(WideToUTF16Hack(GetTitle()), font, fg_color, text_bounds.x(), text_bounds.y(), text_bounds.width(), text_bounds.height(), GetRootMenuItem()->GetDrawStringFlags()); PaintAccelerator(canvas); // Render the icon. if (icon_.width() > 0) { gfx::Rect icon_bounds(config.item_left_margin, top_margin + (height() - top_margin - bottom_margin - icon_.height()) / 2, icon_.width(), icon_.height()); icon_bounds.set_x(GetMirroredXForRect(icon_bounds)); canvas->DrawBitmapInt(icon_, icon_bounds.x(), icon_bounds.y()); } // Render the submenu indicator (arrow). if (HasSubmenu()) { gfx::Rect arrow_bounds(this->width() - item_right_margin_ + config.label_to_arrow_padding, top_margin + (available_height - config.arrow_width) / 2, config.arrow_width, height()); AdjustBoundsForRTLUI(&arrow_bounds); canvas->DrawBitmapInt(*GetSubmenuArrowImage(), arrow_bounds.x(), arrow_bounds.y()); } } } // namespace views <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <psapi.h> #include "skia/ext/bitmap_platform_device_win.h" #include "third_party/skia/include/core/SkMatrix.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/skia/include/core/SkUtils.h" namespace skia { namespace { // Constrains position and size to fit within available_size. If |size| is -1, // all the available_size is used. Returns false if the position is out of // available_size. bool Constrain(int available_size, int* position, int *size) { if (*size < -2) return false; if (*position < 0) { if (*size != -1) *size += *position; *position = 0; } if (*size == 0 || *position >= available_size) return false; if (*size > 0) { int overflow = (*position + *size) - available_size; if (overflow > 0) { *size -= overflow; } } else { // Fill up available size. *size = available_size - *position; } return true; } } // namespace class BitmapPlatformDevice::BitmapPlatformDeviceData : public SkRefCnt { public: explicit BitmapPlatformDeviceData(HBITMAP hbitmap); // Create/destroy hdc_, which is the memory DC for our bitmap data. HDC GetBitmapDC(); void ReleaseBitmapDC(); bool IsBitmapDCCreated() const; // Sets the transform and clip operations. This will not update the DC, // but will mark the config as dirty. The next call of LoadConfig will // pick up these changes. void SetMatrixClip(const SkMatrix& transform, const SkRegion& region); const SkMatrix& transform() const { return transform_; } protected: // Loads the current transform and clip into the DC. Can be called even when // the DC is NULL (will be a NOP). void LoadConfig(); // Windows bitmap corresponding to our surface. HBITMAP hbitmap_; // Lazily-created DC used to draw into the bitmap, see getBitmapDC. HDC hdc_; // True when there is a transform or clip that has not been set to the DC. // The DC is retrieved for every text operation, and the transform and clip // do not change as much. We can save time by not loading the clip and // transform for every one. bool config_dirty_; // Translation assigned to the DC: we need to keep track of this separately // so it can be updated even if the DC isn't created yet. SkMatrix transform_; // The current clipping SkRegion clip_region_; private: virtual ~BitmapPlatformDeviceData(); // Copy & assign are not supported. BitmapPlatformDeviceData(const BitmapPlatformDeviceData&); BitmapPlatformDeviceData& operator=(const BitmapPlatformDeviceData&); }; BitmapPlatformDevice::BitmapPlatformDeviceData::BitmapPlatformDeviceData( HBITMAP hbitmap) : hbitmap_(hbitmap), hdc_(NULL), config_dirty_(true) { // Want to load the config next time. // Initialize the clip region to the entire bitmap. BITMAP bitmap_data; if (GetObject(hbitmap_, sizeof(BITMAP), &bitmap_data)) { SkIRect rect; rect.set(0, 0, bitmap_data.bmWidth, bitmap_data.bmHeight); clip_region_ = SkRegion(rect); } transform_.reset(); } BitmapPlatformDevice::BitmapPlatformDeviceData::~BitmapPlatformDeviceData() { if (hdc_) ReleaseBitmapDC(); // this will free the bitmap data as well as the bitmap handle DeleteObject(hbitmap_); } HDC BitmapPlatformDevice::BitmapPlatformDeviceData::GetBitmapDC() { if (!hdc_) { hdc_ = CreateCompatibleDC(NULL); InitializeDC(hdc_); HGDIOBJ old_bitmap = SelectObject(hdc_, hbitmap_); // When the memory DC is created, its display surface is exactly one // monochrome pixel wide and one monochrome pixel high. Since we select our // own bitmap, we must delete the previous one. DeleteObject(old_bitmap); } LoadConfig(); return hdc_; } void BitmapPlatformDevice::BitmapPlatformDeviceData::ReleaseBitmapDC() { SkASSERT(hdc_); DeleteDC(hdc_); hdc_ = NULL; } bool BitmapPlatformDevice::BitmapPlatformDeviceData::IsBitmapDCCreated() const { return hdc_ != NULL; } void BitmapPlatformDevice::BitmapPlatformDeviceData::SetMatrixClip( const SkMatrix& transform, const SkRegion& region) { transform_ = transform; clip_region_ = region; config_dirty_ = true; } void BitmapPlatformDevice::BitmapPlatformDeviceData::LoadConfig() { if (!config_dirty_ || !hdc_) return; // Nothing to do. config_dirty_ = false; // Transform. SkMatrix t(transform_); LoadTransformToDC(hdc_, t); LoadClippingRegionToDC(hdc_, clip_region_, t); } // We use this static factory function instead of the regular constructor so // that we can create the pixel data before calling the constructor. This is // required so that we can call the base class' constructor with the pixel // data. BitmapPlatformDevice* BitmapPlatformDevice::create( HDC screen_dc, int width, int height, bool is_opaque, HANDLE shared_section) { SkBitmap bitmap; // CreateDIBSection appears to get unhappy if we create an empty bitmap, so // just create a minimal bitmap if ((width == 0) || (height == 0)) { width = 1; height = 1; } BITMAPINFOHEADER hdr = {0}; hdr.biSize = sizeof(BITMAPINFOHEADER); hdr.biWidth = width; hdr.biHeight = -height; // minus means top-down bitmap hdr.biPlanes = 1; hdr.biBitCount = 32; hdr.biCompression = BI_RGB; // no compression hdr.biSizeImage = 0; hdr.biXPelsPerMeter = 1; hdr.biYPelsPerMeter = 1; hdr.biClrUsed = 0; hdr.biClrImportant = 0; void* data = NULL; HBITMAP hbitmap = CreateDIBSection(screen_dc, reinterpret_cast<BITMAPINFO*>(&hdr), 0, &data, shared_section, 0); if (!hbitmap) { return NULL; } bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height); bitmap.setPixels(data); bitmap.setIsOpaque(is_opaque); if (is_opaque) { #ifndef NDEBUG // To aid in finding bugs, we set the background color to something // obviously wrong so it will be noticable when it is not cleared bitmap.eraseARGB(255, 0, 255, 128); // bright bluish green #endif } else { bitmap.eraseARGB(0, 0, 0, 0); } // The device object will take ownership of the HBITMAP. The initial refcount // of the data object will be 1, which is what the constructor expects. return new BitmapPlatformDevice(new BitmapPlatformDeviceData(hbitmap), bitmap); } // static BitmapPlatformDevice* BitmapPlatformDevice::create(int width, int height, bool is_opaque, HANDLE shared_section) { HDC screen_dc = GetDC(NULL); BitmapPlatformDevice* device = BitmapPlatformDevice::create( screen_dc, width, height, is_opaque, shared_section); ReleaseDC(NULL, screen_dc); return device; } // The device will own the HBITMAP, which corresponds to also owning the pixel // data. Therefore, we do not transfer ownership to the SkDevice's bitmap. BitmapPlatformDevice::BitmapPlatformDevice( BitmapPlatformDeviceData* data, const SkBitmap& bitmap) : PlatformDevice(bitmap), data_(data) { // The data object is already ref'ed for us by create(). } // The copy constructor just adds another reference to the underlying data. // We use a const cast since the default Skia definitions don't define the // proper constedness that we expect (accessBitmap should really be const). BitmapPlatformDevice::BitmapPlatformDevice( const BitmapPlatformDevice& other) : PlatformDevice( const_cast<BitmapPlatformDevice&>(other).accessBitmap(true)), data_(other.data_) { data_->ref(); } BitmapPlatformDevice::~BitmapPlatformDevice() { data_->unref(); } BitmapPlatformDevice& BitmapPlatformDevice::operator=( const BitmapPlatformDevice& other) { data_ = other.data_; data_->ref(); return *this; } HDC BitmapPlatformDevice::getBitmapDC() { return data_->GetBitmapDC(); } void BitmapPlatformDevice::setMatrixClip(const SkMatrix& transform, const SkRegion& region) { data_->SetMatrixClip(transform, region); } void BitmapPlatformDevice::drawToHDC(HDC dc, int x, int y, const RECT* src_rect) { bool created_dc = !data_->IsBitmapDCCreated(); HDC source_dc = getBitmapDC(); RECT temp_rect; if (!src_rect) { temp_rect.left = 0; temp_rect.right = width(); temp_rect.top = 0; temp_rect.bottom = height(); src_rect = &temp_rect; } int copy_width = src_rect->right - src_rect->left; int copy_height = src_rect->bottom - src_rect->top; // We need to reset the translation for our bitmap or (0,0) won't be in the // upper left anymore SkMatrix identity; identity.reset(); LoadTransformToDC(source_dc, identity); if (isOpaque()) { BitBlt(dc, x, y, copy_width, copy_height, source_dc, src_rect->left, src_rect->top, SRCCOPY); } else { SkASSERT(copy_width != 0 && copy_height != 0); BLENDFUNCTION blend_function = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA}; GdiAlphaBlend(dc, x, y, copy_width, copy_height, source_dc, src_rect->left, src_rect->top, copy_width, copy_height, blend_function); } LoadTransformToDC(source_dc, data_->transform()); if (created_dc) data_->ReleaseBitmapDC(); } void BitmapPlatformDevice::makeOpaque(int x, int y, int width, int height) { const SkBitmap& bitmap = accessBitmap(true); SkASSERT(bitmap.config() == SkBitmap::kARGB_8888_Config); // FIXME(brettw): This is kind of lame, we shouldn't be dealing with // transforms at this level. Probably there should be a PlatformCanvas // function that does the transform (using the actual transform not just the // translation) and calls us with the transformed rect. const SkMatrix& matrix = data_->transform(); int bitmap_start_x = SkScalarRound(matrix.getTranslateX()) + x; int bitmap_start_y = SkScalarRound(matrix.getTranslateY()) + y; if (Constrain(bitmap.width(), &bitmap_start_x, &width) && Constrain(bitmap.height(), &bitmap_start_y, &height)) { SkAutoLockPixels lock(bitmap); SkASSERT(bitmap.rowBytes() % sizeof(uint32_t) == 0u); size_t row_words = bitmap.rowBytes() / sizeof(uint32_t); // Set data to the first pixel to be modified. uint32_t* data = bitmap.getAddr32(0, 0) + (bitmap_start_y * row_words) + bitmap_start_x; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) data[j] |= (0xFF << SK_A32_SHIFT); data += row_words; } } } // Returns the color value at the specified location. SkColor BitmapPlatformDevice::getColorAt(int x, int y) { const SkBitmap& bitmap = accessBitmap(false); SkAutoLockPixels lock(bitmap); uint32_t* data = bitmap.getAddr32(0, 0); return static_cast<SkColor>(data[x + y * width()]); } void BitmapPlatformDevice::onAccessBitmap(SkBitmap* bitmap) { // FIXME(brettw) OPTIMIZATION: We should only flush if we know a GDI // operation has occurred on our DC. if (data_->IsBitmapDCCreated()) GdiFlush(); } } // namespace skia <commit_msg>[Landing for Jonathon Dixon] Tiny code simplification/optimization: remove unecessay temporary copy of SkMatrix.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <psapi.h> #include "skia/ext/bitmap_platform_device_win.h" #include "third_party/skia/include/core/SkMatrix.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/skia/include/core/SkUtils.h" namespace skia { namespace { // Constrains position and size to fit within available_size. If |size| is -1, // all the available_size is used. Returns false if the position is out of // available_size. bool Constrain(int available_size, int* position, int *size) { if (*size < -2) return false; if (*position < 0) { if (*size != -1) *size += *position; *position = 0; } if (*size == 0 || *position >= available_size) return false; if (*size > 0) { int overflow = (*position + *size) - available_size; if (overflow > 0) { *size -= overflow; } } else { // Fill up available size. *size = available_size - *position; } return true; } } // namespace class BitmapPlatformDevice::BitmapPlatformDeviceData : public SkRefCnt { public: explicit BitmapPlatformDeviceData(HBITMAP hbitmap); // Create/destroy hdc_, which is the memory DC for our bitmap data. HDC GetBitmapDC(); void ReleaseBitmapDC(); bool IsBitmapDCCreated() const; // Sets the transform and clip operations. This will not update the DC, // but will mark the config as dirty. The next call of LoadConfig will // pick up these changes. void SetMatrixClip(const SkMatrix& transform, const SkRegion& region); const SkMatrix& transform() const { return transform_; } protected: // Loads the current transform and clip into the DC. Can be called even when // the DC is NULL (will be a NOP). void LoadConfig(); // Windows bitmap corresponding to our surface. HBITMAP hbitmap_; // Lazily-created DC used to draw into the bitmap, see getBitmapDC. HDC hdc_; // True when there is a transform or clip that has not been set to the DC. // The DC is retrieved for every text operation, and the transform and clip // do not change as much. We can save time by not loading the clip and // transform for every one. bool config_dirty_; // Translation assigned to the DC: we need to keep track of this separately // so it can be updated even if the DC isn't created yet. SkMatrix transform_; // The current clipping SkRegion clip_region_; private: virtual ~BitmapPlatformDeviceData(); // Copy & assign are not supported. BitmapPlatformDeviceData(const BitmapPlatformDeviceData&); BitmapPlatformDeviceData& operator=(const BitmapPlatformDeviceData&); }; BitmapPlatformDevice::BitmapPlatformDeviceData::BitmapPlatformDeviceData( HBITMAP hbitmap) : hbitmap_(hbitmap), hdc_(NULL), config_dirty_(true) { // Want to load the config next time. // Initialize the clip region to the entire bitmap. BITMAP bitmap_data; if (GetObject(hbitmap_, sizeof(BITMAP), &bitmap_data)) { SkIRect rect; rect.set(0, 0, bitmap_data.bmWidth, bitmap_data.bmHeight); clip_region_ = SkRegion(rect); } transform_.reset(); } BitmapPlatformDevice::BitmapPlatformDeviceData::~BitmapPlatformDeviceData() { if (hdc_) ReleaseBitmapDC(); // this will free the bitmap data as well as the bitmap handle DeleteObject(hbitmap_); } HDC BitmapPlatformDevice::BitmapPlatformDeviceData::GetBitmapDC() { if (!hdc_) { hdc_ = CreateCompatibleDC(NULL); InitializeDC(hdc_); HGDIOBJ old_bitmap = SelectObject(hdc_, hbitmap_); // When the memory DC is created, its display surface is exactly one // monochrome pixel wide and one monochrome pixel high. Since we select our // own bitmap, we must delete the previous one. DeleteObject(old_bitmap); } LoadConfig(); return hdc_; } void BitmapPlatformDevice::BitmapPlatformDeviceData::ReleaseBitmapDC() { SkASSERT(hdc_); DeleteDC(hdc_); hdc_ = NULL; } bool BitmapPlatformDevice::BitmapPlatformDeviceData::IsBitmapDCCreated() const { return hdc_ != NULL; } void BitmapPlatformDevice::BitmapPlatformDeviceData::SetMatrixClip( const SkMatrix& transform, const SkRegion& region) { transform_ = transform; clip_region_ = region; config_dirty_ = true; } void BitmapPlatformDevice::BitmapPlatformDeviceData::LoadConfig() { if (!config_dirty_ || !hdc_) return; // Nothing to do. config_dirty_ = false; // Transform. LoadTransformToDC(hdc_, transform_); LoadClippingRegionToDC(hdc_, clip_region_, transform_); } // We use this static factory function instead of the regular constructor so // that we can create the pixel data before calling the constructor. This is // required so that we can call the base class' constructor with the pixel // data. BitmapPlatformDevice* BitmapPlatformDevice::create( HDC screen_dc, int width, int height, bool is_opaque, HANDLE shared_section) { SkBitmap bitmap; // CreateDIBSection appears to get unhappy if we create an empty bitmap, so // just create a minimal bitmap if ((width == 0) || (height == 0)) { width = 1; height = 1; } BITMAPINFOHEADER hdr = {0}; hdr.biSize = sizeof(BITMAPINFOHEADER); hdr.biWidth = width; hdr.biHeight = -height; // minus means top-down bitmap hdr.biPlanes = 1; hdr.biBitCount = 32; hdr.biCompression = BI_RGB; // no compression hdr.biSizeImage = 0; hdr.biXPelsPerMeter = 1; hdr.biYPelsPerMeter = 1; hdr.biClrUsed = 0; hdr.biClrImportant = 0; void* data = NULL; HBITMAP hbitmap = CreateDIBSection(screen_dc, reinterpret_cast<BITMAPINFO*>(&hdr), 0, &data, shared_section, 0); if (!hbitmap) { return NULL; } bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height); bitmap.setPixels(data); bitmap.setIsOpaque(is_opaque); if (is_opaque) { #ifndef NDEBUG // To aid in finding bugs, we set the background color to something // obviously wrong so it will be noticable when it is not cleared bitmap.eraseARGB(255, 0, 255, 128); // bright bluish green #endif } else { bitmap.eraseARGB(0, 0, 0, 0); } // The device object will take ownership of the HBITMAP. The initial refcount // of the data object will be 1, which is what the constructor expects. return new BitmapPlatformDevice(new BitmapPlatformDeviceData(hbitmap), bitmap); } // static BitmapPlatformDevice* BitmapPlatformDevice::create(int width, int height, bool is_opaque, HANDLE shared_section) { HDC screen_dc = GetDC(NULL); BitmapPlatformDevice* device = BitmapPlatformDevice::create( screen_dc, width, height, is_opaque, shared_section); ReleaseDC(NULL, screen_dc); return device; } // The device will own the HBITMAP, which corresponds to also owning the pixel // data. Therefore, we do not transfer ownership to the SkDevice's bitmap. BitmapPlatformDevice::BitmapPlatformDevice( BitmapPlatformDeviceData* data, const SkBitmap& bitmap) : PlatformDevice(bitmap), data_(data) { // The data object is already ref'ed for us by create(). } // The copy constructor just adds another reference to the underlying data. // We use a const cast since the default Skia definitions don't define the // proper constedness that we expect (accessBitmap should really be const). BitmapPlatformDevice::BitmapPlatformDevice( const BitmapPlatformDevice& other) : PlatformDevice( const_cast<BitmapPlatformDevice&>(other).accessBitmap(true)), data_(other.data_) { data_->ref(); } BitmapPlatformDevice::~BitmapPlatformDevice() { data_->unref(); } BitmapPlatformDevice& BitmapPlatformDevice::operator=( const BitmapPlatformDevice& other) { data_ = other.data_; data_->ref(); return *this; } HDC BitmapPlatformDevice::getBitmapDC() { return data_->GetBitmapDC(); } void BitmapPlatformDevice::setMatrixClip(const SkMatrix& transform, const SkRegion& region) { data_->SetMatrixClip(transform, region); } void BitmapPlatformDevice::drawToHDC(HDC dc, int x, int y, const RECT* src_rect) { bool created_dc = !data_->IsBitmapDCCreated(); HDC source_dc = getBitmapDC(); RECT temp_rect; if (!src_rect) { temp_rect.left = 0; temp_rect.right = width(); temp_rect.top = 0; temp_rect.bottom = height(); src_rect = &temp_rect; } int copy_width = src_rect->right - src_rect->left; int copy_height = src_rect->bottom - src_rect->top; // We need to reset the translation for our bitmap or (0,0) won't be in the // upper left anymore SkMatrix identity; identity.reset(); LoadTransformToDC(source_dc, identity); if (isOpaque()) { BitBlt(dc, x, y, copy_width, copy_height, source_dc, src_rect->left, src_rect->top, SRCCOPY); } else { SkASSERT(copy_width != 0 && copy_height != 0); BLENDFUNCTION blend_function = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA}; GdiAlphaBlend(dc, x, y, copy_width, copy_height, source_dc, src_rect->left, src_rect->top, copy_width, copy_height, blend_function); } LoadTransformToDC(source_dc, data_->transform()); if (created_dc) data_->ReleaseBitmapDC(); } void BitmapPlatformDevice::makeOpaque(int x, int y, int width, int height) { const SkBitmap& bitmap = accessBitmap(true); SkASSERT(bitmap.config() == SkBitmap::kARGB_8888_Config); // FIXME(brettw): This is kind of lame, we shouldn't be dealing with // transforms at this level. Probably there should be a PlatformCanvas // function that does the transform (using the actual transform not just the // translation) and calls us with the transformed rect. const SkMatrix& matrix = data_->transform(); int bitmap_start_x = SkScalarRound(matrix.getTranslateX()) + x; int bitmap_start_y = SkScalarRound(matrix.getTranslateY()) + y; if (Constrain(bitmap.width(), &bitmap_start_x, &width) && Constrain(bitmap.height(), &bitmap_start_y, &height)) { SkAutoLockPixels lock(bitmap); SkASSERT(bitmap.rowBytes() % sizeof(uint32_t) == 0u); size_t row_words = bitmap.rowBytes() / sizeof(uint32_t); // Set data to the first pixel to be modified. uint32_t* data = bitmap.getAddr32(0, 0) + (bitmap_start_y * row_words) + bitmap_start_x; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) data[j] |= (0xFF << SK_A32_SHIFT); data += row_words; } } } // Returns the color value at the specified location. SkColor BitmapPlatformDevice::getColorAt(int x, int y) { const SkBitmap& bitmap = accessBitmap(false); SkAutoLockPixels lock(bitmap); uint32_t* data = bitmap.getAddr32(0, 0); return static_cast<SkColor>(data[x + y * width()]); } void BitmapPlatformDevice::onAccessBitmap(SkBitmap* bitmap) { // FIXME(brettw) OPTIMIZATION: We should only flush if we know a GDI // operation has occurred on our DC. if (data_->IsBitmapDCCreated()) GdiFlush(); } } // namespace skia <|endoftext|>
<commit_before>#pragma once #include <UtH/UtHEngine.hpp> #include <Player.hpp> class EnemyFactory { static uth::Layer* m_layer; static uth::PhysicsWorld* m_physicsWorld; static Player* m_player; static uth::Sound* m_expSound; static uth::Sound* m_hpSound; static uth::Sound* m_starSound; static uth::Sound* m_humanSound1; static uth::Sound* m_humanSound2; static uth::Sound* m_humanSound3; static pmath::Vec2 SpawnPosition(); static void m_tankSpawn(float dt); static void m_soldierSpawn(float dt); static void m_aeroplaneSpawn(float dt); static void m_heliSpawn(float dt); static float m_aeroplaneSpawnCooldown; static float m_aeroplaneSpawnTimer; static float m_tankSpawnCooldown; static float m_tankSpawnTimer; static float m_soldierSpawnCooldown; static float m_soldierSpawnTimer; static float m_heliSpawnCooldown; static float m_heliSpawnTimer; static bool isBoss; static bool isVictory; public: static float m_timeCounter; static void Init(uth::Layer* layer, uth::PhysicsWorld* physWorld, Player* player) { m_layer = layer; m_physicsWorld = physWorld; m_player = player; m_expSound = uthRS.LoadSound("Audio/Effects/Short_Explosion1.wav"); m_hpSound = uthRS.LoadSound("Audio/Effects/Heart_pickup.wav"); m_starSound = uthRS.LoadSound("Audio/Effects/Star_pickup.wav"); m_humanSound1 = uthRS.LoadSound("Audio/Effects/auts1.wav"); m_humanSound2 = uthRS.LoadSound("Audio/Effects/auts2.wav"); m_humanSound3 = uthRS.LoadSound("Audio/Effects/auts3.wav"); //m_expSound->SetVolume(50); } static void Update(float dt); static std::shared_ptr<uth::GameObject> CreateTank(); static std::shared_ptr<uth::GameObject> CreateSoldier(); static std::shared_ptr<uth::GameObject> CreateAeroplane(); static std::shared_ptr<uth::GameObject> CreateHeli(); static std::shared_ptr<uth::GameObject> CreateHP(pmath::Vec2 pos); static std::shared_ptr<uth::GameObject> CreateStar(pmath::Vec2 pos); static std::shared_ptr<uth::GameObject> EnemyFactory::CreateBoss(); static std::shared_ptr<uth::GameObject> EnemyFactory::CreateBossVictory(); static void CheckEnemies(); };<commit_msg>fixed few lines<commit_after>#pragma once #include <UtH/UtHEngine.hpp> #include <Player.hpp> class EnemyFactory { static uth::Layer* m_layer; static uth::PhysicsWorld* m_physicsWorld; static Player* m_player; static uth::Sound* m_expSound; static uth::Sound* m_hpSound; static uth::Sound* m_starSound; static uth::Sound* m_humanSound1; static uth::Sound* m_humanSound2; static uth::Sound* m_humanSound3; static pmath::Vec2 SpawnPosition(); static void m_tankSpawn(float dt); static void m_soldierSpawn(float dt); static void m_aeroplaneSpawn(float dt); static void m_heliSpawn(float dt); static float m_aeroplaneSpawnCooldown; static float m_aeroplaneSpawnTimer; static float m_tankSpawnCooldown; static float m_tankSpawnTimer; static float m_soldierSpawnCooldown; static float m_soldierSpawnTimer; static float m_heliSpawnCooldown; static float m_heliSpawnTimer; static bool isBoss; static bool isVictory; public: static float m_timeCounter; static void Init(uth::Layer* layer, uth::PhysicsWorld* physWorld, Player* player) { m_layer = layer; m_physicsWorld = physWorld; m_player = player; m_expSound = uthRS.LoadSound("Audio/Effects/Short_Explosion1.wav"); m_hpSound = uthRS.LoadSound("Audio/Effects/Heart_pickup.wav"); m_starSound = uthRS.LoadSound("Audio/Effects/Star_pickup.wav"); m_humanSound1 = uthRS.LoadSound("Audio/Effects/auts1.wav"); m_humanSound2 = uthRS.LoadSound("Audio/Effects/auts2.wav"); m_humanSound3 = uthRS.LoadSound("Audio/Effects/auts3.wav"); //m_expSound->SetVolume(50); } static void Update(float dt); static std::shared_ptr<uth::GameObject> CreateTank(); static std::shared_ptr<uth::GameObject> CreateSoldier(); static std::shared_ptr<uth::GameObject> CreateAeroplane(); static std::shared_ptr<uth::GameObject> CreateHeli(); static std::shared_ptr<uth::GameObject> CreateHP(pmath::Vec2 pos); static std::shared_ptr<uth::GameObject> CreateStar(pmath::Vec2 pos); static std::shared_ptr<uth::GameObject> CreateBoss(); static std::shared_ptr<uth::GameObject> CreateBossVictory(); static void CheckEnemies(); };<|endoftext|>
<commit_before><commit_msg>Composer now tests different OpenGL versions to get the highest<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: otherjre.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:30:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "osl/thread.h" #include "otherjre.hxx" using namespace rtl; using namespace std; namespace jfw_plugin { Reference<VendorBase> OtherInfo::createInstance() { return new OtherInfo; } char const* const* OtherInfo::getJavaExePaths(int * size) { static char const * ar[] = { #ifdef WNT "bin/java.exe", "jre/bin/java.exe" #elif UNX "bin/java", "jre/bin/java" #endif }; *size = sizeof (ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getRuntimePaths(int * size) { static char const* ar[]= { #ifdef WNT "/bin/client/jvm.dll", "/bin/hotspot/jvm.dll", "/bin/classic/jvm.dll" #elif UNX #ifdef MACOSX "/../../../JavaVM" #else "/bin/classic/libjvm.so", // for IBM Java "/jre/bin/classic/libjvm.so", // for IBM Java "/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC "/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so" // for Blackdown PPC #endif #endif }; *size = sizeof(ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getLibraryPaths(int* size) { #ifdef UNX static char const * ar[] = { #ifdef MACOSX "/../Libraries", "/lib" #else "/bin", "/jre/bin", "/bin/classic", "/jre/bin/classic", "/lib/" JFW_PLUGIN_ARCH "/client", "/lib/" JFW_PLUGIN_ARCH "/classic", "/lib/" JFW_PLUGIN_ARCH "/native_threads", "/lib/" JFW_PLUGIN_ARCH #endif }; *size = sizeof(ar) / sizeof (char*); return ar; #endif size = 0; return NULL; } int OtherInfo::compareVersions(const rtl::OUString& sSecond) const { //Need to provide an own algorithm for comparing version. //Because this function returns always 0, which means the version of //this JRE and the provided version "sSecond" are equal, one cannot put //any excludeVersion entries in the javavendors.xml file. return 0; } } <commit_msg>INTEGRATION: CWS morejava (1.7.2); FILE MERGED 2005/08/26 13:55:41 fridrich_strba 1.7.2.1: Issue number: Submitted by: fridrich_strba Reviewed by: fridrich_strba Add JRE of BEA Systems, Inc. among supported java virtual machines<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: otherjre.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2005-10-25 11:35:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "osl/thread.h" #include "otherjre.hxx" using namespace rtl; using namespace std; namespace jfw_plugin { Reference<VendorBase> OtherInfo::createInstance() { return new OtherInfo; } char const* const* OtherInfo::getJavaExePaths(int * size) { static char const * ar[] = { #ifdef WNT "bin/java.exe", "jre/bin/java.exe" #elif UNX "bin/java", "jre/bin/java" #endif }; *size = sizeof (ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getRuntimePaths(int * size) { static char const* ar[]= { #ifdef WNT "/bin/client/jvm.dll", "/bin/hotspot/jvm.dll", "/bin/classic/jvm.dll" "/bin/jrockit/jvm.dll" #elif UNX #ifdef MACOSX "/../../../JavaVM" #else "/bin/classic/libjvm.so", // for IBM Java "/jre/bin/classic/libjvm.so", // for IBM Java "/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC "/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so" // for Blackdown PPC "/lib/" JFW_PLUGIN_ARCH "/jrockit/libjvm.so" // for Java of BEA Systems #endif #endif }; *size = sizeof(ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getLibraryPaths(int* size) { #ifdef UNX static char const * ar[] = { #ifdef MACOSX "/../Libraries", "/lib" #else "/bin", "/jre/bin", "/bin/classic", "/jre/bin/classic", "/lib/" JFW_PLUGIN_ARCH "/client", "/lib/" JFW_PLUGIN_ARCH "/classic", "/lib/" JFW_PLUGIN_ARCH "/jrockit", "/lib/" JFW_PLUGIN_ARCH "/native_threads", "/lib/" JFW_PLUGIN_ARCH #endif }; *size = sizeof(ar) / sizeof (char*); return ar; #endif size = 0; return NULL; } int OtherInfo::compareVersions(const rtl::OUString& sSecond) const { //Need to provide an own algorithm for comparing version. //Because this function returns always 0, which means the version of //this JRE and the provided version "sSecond" are equal, one cannot put //any excludeVersion entries in the javavendors.xml file. return 0; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleDocumentViewBase.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-09 04:57:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_ACCESSIBILITY_ACCESSIBLE_DOCUMENT_VIEW_BASE_HXX #define SD_ACCESSIBILITY_ACCESSIBLE_DOCUMENT_VIEW_BASE_HXX #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_CONTEXT_BASE_HXX #include <svx/AccessibleContextBase.hxx> #endif #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_COMPONENT_BASE_HXX #include <svx/AccessibleComponentBase.hxx> #endif #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SELECTION_BASE_HXX #include <svx/AccessibleSelectionBase.hxx> #endif #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #include "AccessibleViewForwarder.hxx" #endif #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX #include "AccessiblePageShape.hxx" #endif #ifndef _SVX_ACCESSIBILITY_CHILDREN_MANAGER_HXX #include <svx/ChildrenManager.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_ #include <com/sun/star/awt/XWindowListener.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_ #include <com/sun/star/awt/XFocusListener.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_ #include <com/sun/star/beans/XPropertyChangeListener.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif namespace sd { class ViewShell; class Window; } class VclSimpleEvent; namespace accessibility { /** Base class for the various document views of the Draw and Impress applications. <p>The different view modes of the Draw and Impress applications are made accessible by derived classes. When the view mode is changed than the object representing the document view is disposed and replaced by a new instance of the then appropriate derived class.</p> <p>This base class also manages an optionally active accessible OLE object. If you overwrite the <member>getAccessibleChildCount</member> and <member>getAccessibleChild</member> methods then make sure to first call the corresponding method of this class and adapt your child count and indices accordingly. Only one active OLE object is allowed at a time. This class does not listen for disposing calls at the moment because it does not use the accessible OLE object directly and trusts on getting informed through VCL window events.</p> <p>This class implements three kinds of listeners: <ol><li>The property change listener is not used directly but exists as convenience for derived classes. May be moved to those classes instead.</li> <li>As window listener it waits for changes of the window geometry and forwards those as view forwarder changes.</li> <li>As focus listener it keeps track of the focus to give this class and derived classes the oportunity to set and remove the focus to/from shapes.</li> </ol> </p> */ class AccessibleDocumentViewBase : public AccessibleContextBase, public AccessibleComponentBase, public AccessibleSelectionBase, public IAccessibleViewForwarderListener, public ::com::sun::star::beans::XPropertyChangeListener, public ::com::sun::star::awt::XWindowListener, public ::com::sun::star::awt::XFocusListener { public: //===== internal ======================================================== /** Create a new object. Note that the caller has to call the Init method directly after this constructor has finished. @param pSdWindow The window whose content is to be made accessible. @param pViewShell The view shell associated with the given window. @param rxController The controller from which to get the model. @param rxParent The accessible parent of the new object. Note that this parent does not necessarily correspond with the parent of the given window. */ AccessibleDocumentViewBase ( ::sd::Window* pSdWindow, ::sd::ViewShell* pViewShell, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController>& rxController, const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>& rxParent); virtual ~AccessibleDocumentViewBase (void); /** Initialize a new object. Call this method directly after creating a new object. It finished the initialization begun in the constructor but which needs a fully created object. */ virtual void Init (void); /** Define callback for listening to window child events of VCL. Listen for creation or destruction of OLE objects. */ DECL_LINK (WindowChildEventListener, VclSimpleEvent*); //===== IAccessibleViewForwarderListener ================================ /** A view forwarder change is signalled for instance when any of the window events is recieved. Thus, instead of overloading the four windowResized... methods it will be sufficient in most cases just to overload this method. */ virtual void ViewForwarderChanged (ChangeType aChangeType, const IAccessibleViewForwarder* pViewForwarder); //===== XAccessibleContext ============================================== virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /** This implementation returns either 1 or 0 depending on whether there is an active accessible OLE object or not. */ virtual sal_Int32 SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /** This implementation either returns the active accessible OLE object if it exists and the given index is 0 or throws an exception. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (long nIndex) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleComponent ============================================ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint (const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocation (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Size SAL_CALL getSize (void) throw (::com::sun::star::uno::RuntimeException); //===== XInterface ====================================================== virtual com::sun::star::uno::Any SAL_CALL queryInterface (const com::sun::star::uno::Type & rType) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire (void) throw (); virtual void SAL_CALL release (void) throw (); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); //===== XTypeProvider =================================================== virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> SAL_CALL getTypes (void) throw (::com::sun::star::uno::RuntimeException); //===== lang::XEventListener ============================================ virtual void SAL_CALL disposing (const ::com::sun::star::lang::EventObject& rEventObject) throw (::com::sun::star::uno::RuntimeException); //===== XPropertyChangeListener ========================================= virtual void SAL_CALL propertyChange (const ::com::sun::star::beans::PropertyChangeEvent& rEventObject) throw (::com::sun::star::uno::RuntimeException); //===== XWindowListener ================================================= virtual void SAL_CALL windowResized (const ::com::sun::star::awt::WindowEvent& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL windowMoved (const ::com::sun::star::awt::WindowEvent& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL windowShown (const ::com::sun::star::lang::EventObject& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL windowHidden (const ::com::sun::star::lang::EventObject& e) throw (::com::sun::star::uno::RuntimeException); //===== XFocusListener ================================================= virtual void SAL_CALL focusGained (const ::com::sun::star::awt::FocusEvent& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL focusLost (const ::com::sun::star::awt::FocusEvent& e) throw (::com::sun::star::uno::RuntimeException); private: // return the member maMutex; virtual ::osl::Mutex& implGetMutex(); // return ourself as context in default case virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > implGetAccessibleContext() throw ( ::com::sun::star::uno::RuntimeException ); // return sal_False in default case virtual sal_Bool implIsSelected( sal_Int32 nAccessibleChildIndex ) throw (::com::sun::star::uno::RuntimeException); // return nothing in default case virtual void implSelect( sal_Int32 nAccessibleChildIndex, sal_Bool bSelect ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); protected: /// The core window that is made accessible. ::sd::Window* mpWindow; /// The API window that is made accessible. ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow; /// The controller of the window in which this view is displayed. ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController> mxController; /// Model of the document. ::com::sun::star::uno::Reference < ::com::sun::star::frame::XModel> mxModel; // Bundle of information that is passed down the shape tree. AccessibleShapeTreeInfo maShapeTreeInfo; /// The view forwarder passed to the children manager. AccessibleViewForwarder maViewForwarder; /** Accessible OLE object. Set or removed by the <member>SetAccessibleOLEObject</member> method. */ ::com::sun::star::uno::Reference < ::com::sun::star::accessibility::XAccessible> mxAccessibleOLEObject; // This method is called from the component helper base class while // disposing. virtual void SAL_CALL disposing (void); /** Create a name string. The current name is not modified and, therefore, no events are send. This method is usually called once by the <member>getAccessibleName</member> method of the base class. @return A name string. */ virtual ::rtl::OUString CreateAccessibleName () throw (::com::sun::star::uno::RuntimeException); /** Create a description string. The current description is not modified and, therefore, no events are send. This method is usually called once by the <member>getAccessibleDescription</member> method of the base class. @return A description string. */ virtual ::rtl::OUString CreateAccessibleDescription () throw (::com::sun::star::uno::RuntimeException); /** This method is called when (after) the frame containing this document has been activated. Can be used to send FOCUSED state changes for the currently selected element. Note: Currently used as a substitute for FocusGained. Should be renamed in the future. */ virtual void Activated (void); /** This method is called when (before or after?) the frame containing this document has been deactivated. Can be used to send FOCUSED state changes for the currently selected element. Note: Currently used as a substitute for FocusLost. Should be renamed in the future. */ virtual void Deactivated (void); /** Set or remove the currently active accessible OLE object. @param xOLEObject If this is a valid reference then a child event is send that informs the listeners of a new child. If there has already been an active accessible OLE object then this is removed first and appropriate events are send. If this is an empty reference then the currently active accessible OLE object (if there is one) is removed. */ virtual void SetAccessibleOLEObject ( const ::com::sun::star::uno::Reference < ::com::sun::star::accessibility::XAccessible>& xOLEObject); }; } // end of namespace accessibility #endif <commit_msg>INTEGRATION: CWS sixtyfour11 (1.11.406); FILE MERGED 2007/03/12 16:39:22 kendy 1.11.406.1: #i75331# Don't introduce new virtual methods where they should be overridden.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleDocumentViewBase.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2007-04-25 14:40:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_ACCESSIBILITY_ACCESSIBLE_DOCUMENT_VIEW_BASE_HXX #define SD_ACCESSIBILITY_ACCESSIBLE_DOCUMENT_VIEW_BASE_HXX #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_CONTEXT_BASE_HXX #include <svx/AccessibleContextBase.hxx> #endif #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_COMPONENT_BASE_HXX #include <svx/AccessibleComponentBase.hxx> #endif #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SELECTION_BASE_HXX #include <svx/AccessibleSelectionBase.hxx> #endif #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #include "AccessibleViewForwarder.hxx" #endif #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX #include "AccessiblePageShape.hxx" #endif #ifndef _SVX_ACCESSIBILITY_CHILDREN_MANAGER_HXX #include <svx/ChildrenManager.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_ #include <com/sun/star/awt/XWindowListener.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_ #include <com/sun/star/awt/XFocusListener.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_ #include <com/sun/star/beans/XPropertyChangeListener.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif namespace sd { class ViewShell; class Window; } class VclSimpleEvent; namespace accessibility { /** Base class for the various document views of the Draw and Impress applications. <p>The different view modes of the Draw and Impress applications are made accessible by derived classes. When the view mode is changed than the object representing the document view is disposed and replaced by a new instance of the then appropriate derived class.</p> <p>This base class also manages an optionally active accessible OLE object. If you overwrite the <member>getAccessibleChildCount</member> and <member>getAccessibleChild</member> methods then make sure to first call the corresponding method of this class and adapt your child count and indices accordingly. Only one active OLE object is allowed at a time. This class does not listen for disposing calls at the moment because it does not use the accessible OLE object directly and trusts on getting informed through VCL window events.</p> <p>This class implements three kinds of listeners: <ol><li>The property change listener is not used directly but exists as convenience for derived classes. May be moved to those classes instead.</li> <li>As window listener it waits for changes of the window geometry and forwards those as view forwarder changes.</li> <li>As focus listener it keeps track of the focus to give this class and derived classes the oportunity to set and remove the focus to/from shapes.</li> </ol> </p> */ class AccessibleDocumentViewBase : public AccessibleContextBase, public AccessibleComponentBase, public AccessibleSelectionBase, public IAccessibleViewForwarderListener, public ::com::sun::star::beans::XPropertyChangeListener, public ::com::sun::star::awt::XWindowListener, public ::com::sun::star::awt::XFocusListener { public: //===== internal ======================================================== /** Create a new object. Note that the caller has to call the Init method directly after this constructor has finished. @param pSdWindow The window whose content is to be made accessible. @param pViewShell The view shell associated with the given window. @param rxController The controller from which to get the model. @param rxParent The accessible parent of the new object. Note that this parent does not necessarily correspond with the parent of the given window. */ AccessibleDocumentViewBase ( ::sd::Window* pSdWindow, ::sd::ViewShell* pViewShell, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController>& rxController, const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>& rxParent); virtual ~AccessibleDocumentViewBase (void); /** Initialize a new object. Call this method directly after creating a new object. It finished the initialization begun in the constructor but which needs a fully created object. */ virtual void Init (void); /** Define callback for listening to window child events of VCL. Listen for creation or destruction of OLE objects. */ DECL_LINK (WindowChildEventListener, VclSimpleEvent*); //===== IAccessibleViewForwarderListener ================================ /** A view forwarder change is signalled for instance when any of the window events is recieved. Thus, instead of overloading the four windowResized... methods it will be sufficient in most cases just to overload this method. */ virtual void ViewForwarderChanged (ChangeType aChangeType, const IAccessibleViewForwarder* pViewForwarder); //===== XAccessibleContext ============================================== virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /** This implementation returns either 1 or 0 depending on whether there is an active accessible OLE object or not. */ virtual sal_Int32 SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /** This implementation either returns the active accessible OLE object if it exists and the given index is 0 or throws an exception. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (sal_Int32 nIndex) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleComponent ============================================ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint (const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocation (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Size SAL_CALL getSize (void) throw (::com::sun::star::uno::RuntimeException); //===== XInterface ====================================================== virtual com::sun::star::uno::Any SAL_CALL queryInterface (const com::sun::star::uno::Type & rType) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire (void) throw (); virtual void SAL_CALL release (void) throw (); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); //===== XTypeProvider =================================================== virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> SAL_CALL getTypes (void) throw (::com::sun::star::uno::RuntimeException); //===== lang::XEventListener ============================================ virtual void SAL_CALL disposing (const ::com::sun::star::lang::EventObject& rEventObject) throw (::com::sun::star::uno::RuntimeException); //===== XPropertyChangeListener ========================================= virtual void SAL_CALL propertyChange (const ::com::sun::star::beans::PropertyChangeEvent& rEventObject) throw (::com::sun::star::uno::RuntimeException); //===== XWindowListener ================================================= virtual void SAL_CALL windowResized (const ::com::sun::star::awt::WindowEvent& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL windowMoved (const ::com::sun::star::awt::WindowEvent& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL windowShown (const ::com::sun::star::lang::EventObject& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL windowHidden (const ::com::sun::star::lang::EventObject& e) throw (::com::sun::star::uno::RuntimeException); //===== XFocusListener ================================================= virtual void SAL_CALL focusGained (const ::com::sun::star::awt::FocusEvent& e) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL focusLost (const ::com::sun::star::awt::FocusEvent& e) throw (::com::sun::star::uno::RuntimeException); private: // return the member maMutex; virtual ::osl::Mutex& implGetMutex(); // return ourself as context in default case virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > implGetAccessibleContext() throw ( ::com::sun::star::uno::RuntimeException ); // return sal_False in default case virtual sal_Bool implIsSelected( sal_Int32 nAccessibleChildIndex ) throw (::com::sun::star::uno::RuntimeException); // return nothing in default case virtual void implSelect( sal_Int32 nAccessibleChildIndex, sal_Bool bSelect ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); protected: /// The core window that is made accessible. ::sd::Window* mpWindow; /// The API window that is made accessible. ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow; /// The controller of the window in which this view is displayed. ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController> mxController; /// Model of the document. ::com::sun::star::uno::Reference < ::com::sun::star::frame::XModel> mxModel; // Bundle of information that is passed down the shape tree. AccessibleShapeTreeInfo maShapeTreeInfo; /// The view forwarder passed to the children manager. AccessibleViewForwarder maViewForwarder; /** Accessible OLE object. Set or removed by the <member>SetAccessibleOLEObject</member> method. */ ::com::sun::star::uno::Reference < ::com::sun::star::accessibility::XAccessible> mxAccessibleOLEObject; // This method is called from the component helper base class while // disposing. virtual void SAL_CALL disposing (void); /** Create a name string. The current name is not modified and, therefore, no events are send. This method is usually called once by the <member>getAccessibleName</member> method of the base class. @return A name string. */ virtual ::rtl::OUString CreateAccessibleName () throw (::com::sun::star::uno::RuntimeException); /** Create a description string. The current description is not modified and, therefore, no events are send. This method is usually called once by the <member>getAccessibleDescription</member> method of the base class. @return A description string. */ virtual ::rtl::OUString CreateAccessibleDescription () throw (::com::sun::star::uno::RuntimeException); /** This method is called when (after) the frame containing this document has been activated. Can be used to send FOCUSED state changes for the currently selected element. Note: Currently used as a substitute for FocusGained. Should be renamed in the future. */ virtual void Activated (void); /** This method is called when (before or after?) the frame containing this document has been deactivated. Can be used to send FOCUSED state changes for the currently selected element. Note: Currently used as a substitute for FocusLost. Should be renamed in the future. */ virtual void Deactivated (void); /** Set or remove the currently active accessible OLE object. @param xOLEObject If this is a valid reference then a child event is send that informs the listeners of a new child. If there has already been an active accessible OLE object then this is removed first and appropriate events are send. If this is an empty reference then the currently active accessible OLE object (if there is one) is removed. */ virtual void SetAccessibleOLEObject ( const ::com::sun::star::uno::Reference < ::com::sun::star::accessibility::XAccessible>& xOLEObject); }; } // end of namespace accessibility #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(SHARED_WORKERS) #include "SharedWorkerRepository.h" #include "Event.h" #include "EventNames.h" #include "MessagePortChannel.h" #include "SharedWorker.h" #include "PlatformMessagePortChannel.h" #include "WebKit.h" #include "WebKitClient.h" #include "WebMessagePortChannel.h" #include "WebSharedWorker.h" #include "WebSharedWorkerRepository.h" #include "WebString.h" #include "WebURL.h" #include "WorkerScriptLoader.h" #include "WorkerScriptLoaderClient.h" namespace WebCore { class Document; using WebKit::WebMessagePortChannel; using WebKit::WebSharedWorker; using WebKit::WebSharedWorkerRepository; // Callback class that keeps the Worker object alive while loads are potentially happening, and also translates load errors into error events on the worker. class SharedWorkerScriptLoader : public RefCounted<SharedWorkerScriptLoader>, private WorkerScriptLoaderClient { public: SharedWorkerScriptLoader(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, PassOwnPtr<WebSharedWorker> webWorker) : m_worker(worker), m_webWorker(webWorker), m_port(port) { } void load(const KURL&); private: // WorkerScriptLoaderClient callback virtual void notifyFinished(); RefPtr<SharedWorker> m_worker; OwnPtr<WebSharedWorker> m_webWorker; OwnPtr<MessagePortChannel> m_port; WorkerScriptLoader m_scriptLoader; }; void SharedWorkerScriptLoader::load(const KURL& url) { m_scriptLoader.loadAsynchronously(m_worker->scriptExecutionContext(), url, DenyCrossOriginRequests, this); } // Extracts a WebMessagePortChannel from a MessagePortChannel. static WebMessagePortChannel* getWebPort(PassOwnPtr<MessagePortChannel> port) { // Extract the WebMessagePortChannel to send to the worker. PlatformMessagePortChannel* platformChannel = port->channel(); WebMessagePortChannel* webPort = platformChannel->webChannelRelease(); webPort->setClient(0); return webPort; } void SharedWorkerScriptLoader::notifyFinished() { if (m_scriptLoader.failed()) m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true)); else { m_webWorker->startWorkerContext(m_scriptLoader.url(), m_worker->scriptExecutionContext()->userAgent(m_scriptLoader.url()), m_scriptLoader.script()); m_webWorker->connect(getWebPort(m_port.release())); } // Connect event has been sent, so free ourselves (this releases the SharedWorker so it can be freed as well if unreferenced). delete this; } bool SharedWorkerRepository::isAvailable() { // SharedWorkers are disabled for now until the implementation is further along. // TODO(atwilson): Add code to check for a runtime flag like so: // return commandLineFlag && WebKit::webKitClient()->sharedWorkerRepository(); return false; } static WebSharedWorkerRepository::DocumentID getId(void* document) { ASSERT(document); return reinterpret_cast<WebSharedWorkerRepository::DocumentID>(document); } void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec) { ScriptExecutionContext* context = worker->scriptExecutionContext(); // No nested workers (for now) - connect() should only be called from document context. ASSERT(context->isDocument()); OwnPtr<WebSharedWorker> webWorker; ASSERT(WebKit::webKitClient()->sharedWorkerRepository()); webWorker = WebKit::webKitClient()->sharedWorkerRepository()->lookup(url, name, getId(context)); if (!webWorker) { // Existing worker does not match this url, so return an error back to the caller. ec = URL_MISMATCH_ERR; return; } if (!webWorker->isStarted()) { // Need to kick off a load for the worker. The loader will connect to the worker once the script has been loaded, then free itself. SharedWorkerScriptLoader* loader = new SharedWorkerScriptLoader(worker, port.release(), webWorker.release()); loader->load(url); } else webWorker->connect(getWebPort(port.release())); } void SharedWorkerRepository::documentDetached(Document* document) { WebKit::WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository(); if (repo) repo->documentDetached(getId(document)); } bool SharedWorkerRepository::hasSharedWorkers(Document* document) { WebKit::WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository(); return repo && repo->hasSharedWorkers(getId(document)); } } // namespace WebCore #endif // ENABLE(SHARED_WORKERS) <commit_msg>TBR: nsylvain<commit_after>/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(SHARED_WORKERS) #include "SharedWorkerRepository.h" #include "Event.h" #include "EventNames.h" #include "MessagePortChannel.h" #include "PlatformMessagePortChannel.h" #include "ScriptExecutionContext.h" #include "SharedWorker.h" #include "WebKit.h" #include "WebKitClient.h" #include "WebMessagePortChannel.h" #include "WebSharedWorker.h" #include "WebSharedWorkerRepository.h" #include "WebString.h" #include "WebURL.h" #include "WorkerScriptLoader.h" #include "WorkerScriptLoaderClient.h" namespace WebCore { class Document; using WebKit::WebMessagePortChannel; using WebKit::WebSharedWorker; using WebKit::WebSharedWorkerRepository; // Callback class that keeps the Worker object alive while loads are potentially happening, and also translates load errors into error events on the worker. class SharedWorkerScriptLoader : public RefCounted<SharedWorkerScriptLoader>, private WorkerScriptLoaderClient { public: SharedWorkerScriptLoader(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, PassOwnPtr<WebSharedWorker> webWorker) : m_worker(worker), m_webWorker(webWorker), m_port(port) { } void load(const KURL&); private: // WorkerScriptLoaderClient callback virtual void notifyFinished(); RefPtr<SharedWorker> m_worker; OwnPtr<WebSharedWorker> m_webWorker; OwnPtr<MessagePortChannel> m_port; WorkerScriptLoader m_scriptLoader; }; void SharedWorkerScriptLoader::load(const KURL& url) { m_scriptLoader.loadAsynchronously(m_worker->scriptExecutionContext(), url, DenyCrossOriginRequests, this); } // Extracts a WebMessagePortChannel from a MessagePortChannel. static WebMessagePortChannel* getWebPort(PassOwnPtr<MessagePortChannel> port) { // Extract the WebMessagePortChannel to send to the worker. PlatformMessagePortChannel* platformChannel = port->channel(); WebMessagePortChannel* webPort = platformChannel->webChannelRelease(); webPort->setClient(0); return webPort; } void SharedWorkerScriptLoader::notifyFinished() { if (m_scriptLoader.failed()) m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true)); else { m_webWorker->startWorkerContext(m_scriptLoader.url(), m_worker->scriptExecutionContext()->userAgent(m_scriptLoader.url()), m_scriptLoader.script()); m_webWorker->connect(getWebPort(m_port.release())); } // Connect event has been sent, so free ourselves (this releases the SharedWorker so it can be freed as well if unreferenced). delete this; } bool SharedWorkerRepository::isAvailable() { // SharedWorkers are disabled for now until the implementation is further along. // TODO(atwilson): Add code to check for a runtime flag like so: // return commandLineFlag && WebKit::webKitClient()->sharedWorkerRepository(); return false; } static WebSharedWorkerRepository::DocumentID getId(void* document) { ASSERT(document); return reinterpret_cast<WebSharedWorkerRepository::DocumentID>(document); } void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec) { ScriptExecutionContext* context = worker->scriptExecutionContext(); // No nested workers (for now) - connect() should only be called from document context. ASSERT(context->isDocument()); OwnPtr<WebSharedWorker> webWorker; ASSERT(WebKit::webKitClient()->sharedWorkerRepository()); webWorker = WebKit::webKitClient()->sharedWorkerRepository()->lookup(url, name, getId(context)); if (!webWorker) { // Existing worker does not match this url, so return an error back to the caller. ec = URL_MISMATCH_ERR; return; } if (!webWorker->isStarted()) { // Need to kick off a load for the worker. The loader will connect to the worker once the script has been loaded, then free itself. SharedWorkerScriptLoader* loader = new SharedWorkerScriptLoader(worker, port.release(), webWorker.release()); loader->load(url); } else webWorker->connect(getWebPort(port.release())); } void SharedWorkerRepository::documentDetached(Document* document) { WebKit::WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository(); if (repo) repo->documentDetached(getId(document)); } bool SharedWorkerRepository::hasSharedWorkers(Document* document) { WebKit::WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository(); return repo && repo->hasSharedWorkers(getId(document)); } } // namespace WebCore #endif // ENABLE(SHARED_WORKERS) <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/fileapi/file_system_usage_cache.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/pickle.h" namespace fileapi { const FilePath::CharType FileSystemUsageCache::kUsageFileName[] = FILE_PATH_LITERAL(".usage"); const char FileSystemUsageCache::kUsageFileHeader[] = "FSU4"; const int FileSystemUsageCache::kUsageFileHeaderSize = 4; /* Pickle::{Read,Write}Bool treat bool as int */ const int FileSystemUsageCache::kUsageFileSize = sizeof(Pickle::Header) + FileSystemUsageCache::kUsageFileHeaderSize + sizeof(int) + sizeof(int32) + sizeof(int64); // static int64 FileSystemUsageCache::GetUsage(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return -1; return fs_usage; } // static int32 FileSystemUsageCache::GetDirty(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return -1; return static_cast<int32>(dirty); } // static bool FileSystemUsageCache::IncrementDirty(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return false; return Write(usage_file_path, is_valid, dirty + 1, fs_usage) >= 0; } // static bool FileSystemUsageCache::DecrementDirty(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0 || dirty <= 0) return false; return Write(usage_file_path, is_valid, dirty - 1, fs_usage) >= 0; } // static bool FileSystemUsageCache::Invalidate(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); return fs_usage >= 0 && Write(usage_file_path, false, dirty, fs_usage); } bool FileSystemUsageCache::IsValid(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; Read(usage_file_path, &is_valid, &dirty); return is_valid; } // static int FileSystemUsageCache::AtomicUpdateUsageByDelta( const FilePath& usage_file_path, int64 delta) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; // TODO(dmikurube): Make sure that usage_file_path is available. fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return -1; return Write(usage_file_path, is_valid, dirty, fs_usage + delta); } // static int FileSystemUsageCache::UpdateUsage(const FilePath& usage_file_path, int64 fs_usage) { return Write(usage_file_path, true, 0, fs_usage); } // static bool FileSystemUsageCache::Exists(const FilePath& usage_file_path) { return file_util::PathExists(usage_file_path); } // static bool FileSystemUsageCache::Delete(const FilePath& usage_file_path) { return file_util::Delete(usage_file_path, true); } // static int64 FileSystemUsageCache::Read(const FilePath& usage_file_path, bool* is_valid, uint32* dirty) { char buffer[kUsageFileSize]; const char *header; DCHECK(!usage_file_path.empty()); if (kUsageFileSize != file_util::ReadFile(usage_file_path, buffer, kUsageFileSize)) return -1; Pickle read_pickle(buffer, kUsageFileSize); PickleIterator iter(read_pickle); int64 fs_usage; if (!read_pickle.ReadBytes(&iter, &header, kUsageFileHeaderSize) || !read_pickle.ReadBool(&iter, is_valid) || !read_pickle.ReadUInt32(&iter, dirty) || !read_pickle.ReadInt64(&iter, &fs_usage)) return -1; if (header[0] != kUsageFileHeader[0] || header[1] != kUsageFileHeader[1] || header[2] != kUsageFileHeader[2] || header[3] != kUsageFileHeader[3]) return -1; return fs_usage; } // static int FileSystemUsageCache::Write(const FilePath& usage_file_path, bool is_valid, uint32 dirty, int64 fs_usage) { Pickle write_pickle; write_pickle.WriteBytes(kUsageFileHeader, kUsageFileHeaderSize); write_pickle.WriteBool(is_valid); write_pickle.WriteUInt32(dirty); write_pickle.WriteInt64(fs_usage); DCHECK(!usage_file_path.empty()); FilePath temporary_usage_file_path; file_util::CreateTemporaryFileInDir(usage_file_path.DirName(), &temporary_usage_file_path); int bytes_written = file_util::WriteFile(temporary_usage_file_path, (const char *)write_pickle.data(), write_pickle.size()); if (bytes_written != kUsageFileSize) return -1; if (file_util::ReplaceFile(temporary_usage_file_path, usage_file_path)) return bytes_written; else return -1; } } // namespace fileapi <commit_msg>Fix two unchecked return values<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/fileapi/file_system_usage_cache.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/pickle.h" namespace fileapi { const FilePath::CharType FileSystemUsageCache::kUsageFileName[] = FILE_PATH_LITERAL(".usage"); const char FileSystemUsageCache::kUsageFileHeader[] = "FSU4"; const int FileSystemUsageCache::kUsageFileHeaderSize = 4; /* Pickle::{Read,Write}Bool treat bool as int */ const int FileSystemUsageCache::kUsageFileSize = sizeof(Pickle::Header) + FileSystemUsageCache::kUsageFileHeaderSize + sizeof(int) + sizeof(int32) + sizeof(int64); // static int64 FileSystemUsageCache::GetUsage(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return -1; return fs_usage; } // static int32 FileSystemUsageCache::GetDirty(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return -1; return static_cast<int32>(dirty); } // static bool FileSystemUsageCache::IncrementDirty(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return false; return Write(usage_file_path, is_valid, dirty + 1, fs_usage) >= 0; } // static bool FileSystemUsageCache::DecrementDirty(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0 || dirty <= 0) return false; return Write(usage_file_path, is_valid, dirty - 1, fs_usage) >= 0; } // static bool FileSystemUsageCache::Invalidate(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; fs_usage = Read(usage_file_path, &is_valid, &dirty); return fs_usage >= 0 && Write(usage_file_path, false, dirty, fs_usage); } bool FileSystemUsageCache::IsValid(const FilePath& usage_file_path) { bool is_valid = true; uint32 dirty = 0; int64 result = Read(usage_file_path, &is_valid, &dirty); if (result < 0) return false; return is_valid; } // static int FileSystemUsageCache::AtomicUpdateUsageByDelta( const FilePath& usage_file_path, int64 delta) { bool is_valid = true; uint32 dirty = 0; int64 fs_usage; // TODO(dmikurube): Make sure that usage_file_path is available. fs_usage = Read(usage_file_path, &is_valid, &dirty); if (fs_usage < 0) return -1; return Write(usage_file_path, is_valid, dirty, fs_usage + delta); } // static int FileSystemUsageCache::UpdateUsage(const FilePath& usage_file_path, int64 fs_usage) { return Write(usage_file_path, true, 0, fs_usage); } // static bool FileSystemUsageCache::Exists(const FilePath& usage_file_path) { return file_util::PathExists(usage_file_path); } // static bool FileSystemUsageCache::Delete(const FilePath& usage_file_path) { return file_util::Delete(usage_file_path, true); } // static int64 FileSystemUsageCache::Read(const FilePath& usage_file_path, bool* is_valid, uint32* dirty) { char buffer[kUsageFileSize]; const char *header; DCHECK(!usage_file_path.empty()); if (kUsageFileSize != file_util::ReadFile(usage_file_path, buffer, kUsageFileSize)) return -1; Pickle read_pickle(buffer, kUsageFileSize); PickleIterator iter(read_pickle); int64 fs_usage; if (!read_pickle.ReadBytes(&iter, &header, kUsageFileHeaderSize) || !read_pickle.ReadBool(&iter, is_valid) || !read_pickle.ReadUInt32(&iter, dirty) || !read_pickle.ReadInt64(&iter, &fs_usage)) return -1; if (header[0] != kUsageFileHeader[0] || header[1] != kUsageFileHeader[1] || header[2] != kUsageFileHeader[2] || header[3] != kUsageFileHeader[3]) return -1; return fs_usage; } // static int FileSystemUsageCache::Write(const FilePath& usage_file_path, bool is_valid, uint32 dirty, int64 fs_usage) { Pickle write_pickle; write_pickle.WriteBytes(kUsageFileHeader, kUsageFileHeaderSize); write_pickle.WriteBool(is_valid); write_pickle.WriteUInt32(dirty); write_pickle.WriteInt64(fs_usage); DCHECK(!usage_file_path.empty()); FilePath temporary_usage_file_path; if (!file_util::CreateTemporaryFileInDir(usage_file_path.DirName(), &temporary_usage_file_path)) { return -1; } int bytes_written = file_util::WriteFile(temporary_usage_file_path, (const char *)write_pickle.data(), write_pickle.size()); if (bytes_written != kUsageFileSize) return -1; if (file_util::ReplaceFile(temporary_usage_file_path, usage_file_path)) return bytes_written; else return -1; } } // namespace fileapi <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string_util.h" #include "webkit/glue/plugins/test/plugin_client.h" #include "webkit/glue/plugins/test/plugin_arguments_test.h" #include "webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h" #include "webkit/glue/plugins/test/plugin_get_javascript_url_test.h" #include "webkit/glue/plugins/test/plugin_geturl_test.h" #include "webkit/glue/plugins/test/plugin_javascript_open_popup.h" #include "webkit/glue/plugins/test/plugin_new_fails_test.h" #include "webkit/glue/plugins/test/plugin_private_test.h" #include "webkit/glue/plugins/test/plugin_npobject_lifetime_test.h" #include "webkit/glue/plugins/test/plugin_npobject_proxy_test.h" #include "webkit/glue/plugins/test/plugin_window_size_test.h" #include "webkit/glue/plugins/test/plugin_windowless_test.h" #include "third_party/npapi/bindings/npapi.h" #include "third_party/npapi/bindings/npruntime.h" namespace NPAPIClient { NPNetscapeFuncs* PluginClient::host_functions_; NPError PluginClient::GetEntryPoints(NPPluginFuncs* pFuncs) { if (pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; if (pFuncs->size < sizeof(NPPluginFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; pFuncs->javaClass = static_cast<JRIGlobalRef>(NPP_GetJavaClass); return NPERR_NO_ERROR; } NPError PluginClient::Initialize(NPNetscapeFuncs* pFuncs) { if (pFuncs == NULL) { return NPERR_INVALID_FUNCTABLE_ERROR; } if (static_cast<unsigned char>((pFuncs->version >> 8) & 0xff) > NP_VERSION_MAJOR) { return NPERR_INCOMPATIBLE_VERSION_ERROR; } host_functions_ = pFuncs; return NPERR_NO_ERROR; } NPError PluginClient::Shutdown() { return NPERR_NO_ERROR; } } // namespace NPAPIClient extern "C" { NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; // We look at the test name requested via the plugin arguments. We match // that against a given test and try to instantiate it. // lookup the name parameter std::string test_name; for (int name_index = 0; name_index < argc; name_index++) if (base::strcasecmp(argn[name_index], "name") == 0) { test_name = argv[name_index]; break; } if (test_name.empty()) return NPERR_GENERIC_ERROR; // no name found NPError ret = NPERR_GENERIC_ERROR; bool windowless_plugin = false; NPAPIClient::PluginTest *new_test = NULL; if (test_name == "arguments") { new_test = new NPAPIClient::PluginArgumentsTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "geturl") { new_test = new NPAPIClient::PluginGetURLTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "npobject_proxy") { new_test = new NPAPIClient::NPObjectProxyTest(instance, NPAPIClient::PluginClient::HostFunctions()); #if defined(OS_WIN) // TODO(port): plugin_windowless_test.*. } else if (test_name == "execute_script_delete_in_paint" || test_name == "execute_script_delete_in_mouse_move" || test_name == "delete_frame_test") { new_test = new NPAPIClient::WindowlessPluginTest(instance, NPAPIClient::PluginClient::HostFunctions(), test_name); windowless_plugin = true; #endif } else if (test_name == "getjavascripturl") { new_test = new NPAPIClient::ExecuteGetJavascriptUrlTest(instance, NPAPIClient::PluginClient::HostFunctions()); #if defined(OS_WIN) // TODO(port): plugin_window_size_test.*. } else if (test_name == "checkwindowrect") { new_test = new NPAPIClient::PluginWindowSizeTest(instance, NPAPIClient::PluginClient::HostFunctions()); #endif } else if (test_name == "self_delete_plugin_stream") { new_test = new NPAPIClient::DeletePluginInStreamTest(instance, NPAPIClient::PluginClient::HostFunctions()); #if defined(OS_WIN) // TODO(port): plugin_npobject_lifetime_test.*. } else if (test_name == "npobject_lifetime_test") { new_test = new NPAPIClient::NPObjectLifetimeTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "npobject_lifetime_test_second_instance") { new_test = new NPAPIClient::NPObjectLifetimeTestInstance2(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "new_fails") { new_test = new NPAPIClient::NewFailsTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "npobject_delete_plugin_in_evaluate") { new_test = new NPAPIClient::NPObjectDeletePluginInNPN_Evaluate(instance, NPAPIClient::PluginClient::HostFunctions()); #endif } else if (test_name == "plugin_javascript_open_popup_with_plugin") { new_test = new NPAPIClient::ExecuteJavascriptOpenPopupWithPluginTest( instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "plugin_popup_with_plugin_target") { new_test = new NPAPIClient::ExecuteJavascriptPopupWindowTargetPluginTest( instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "private") { new_test = new NPAPIClient::PrivateTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else { // If we don't have a test case for this, create a // generic one which basically never fails. LOG(WARNING) << "Unknown test name '" << test_name << "'; using default test."; new_test = new NPAPIClient::PluginTest(instance, NPAPIClient::PluginClient::HostFunctions()); } if (new_test) { ret = new_test->New(mode, argc, (const char**)argn, (const char**)argv, saved); if ((ret == NPERR_NO_ERROR) && windowless_plugin) { NPAPIClient::PluginClient::HostFunctions()->setvalue( instance, NPPVpluginWindowBool, NULL); } } return ret; } NPError NPP_Destroy(NPP instance, NPSavedData** save) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; delete plugin; // XXXMB - do work here. return NPERR_GENERIC_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* pNPWindow) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; if (pNPWindow->window == NULL) { return NPERR_NO_ERROR; } NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->SetWindow(pNPWindow); } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->NewStream(type, stream, seekable, stype); } int32 NPP_WriteReady(NPP instance, NPStream *stream) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->WriteReady(stream); } int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->Write(stream, offset, len, buffer); } NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPError reason) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->DestroyStream(stream, reason); } void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) { if (instance == NULL) return; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->StreamAsFile(stream, fname); } void NPP_Print(NPP instance, NPPrint* printInfo) { if (instance == NULL) return; // XXXMB - do work here. } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if (instance == NULL) return; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->URLNotify(url, reason, notifyData); } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; // XXXMB - do work here. return NPERR_GENERIC_ERROR; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; // XXXMB - do work here. return NPERR_GENERIC_ERROR; } int16 NPP_HandleEvent(NPP instance, void* event) { if (instance == NULL) return 0; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->HandleEvent(event); } void* NPP_GetJavaClass(void) { // XXXMB - do work here. return NULL; } } // extern "C" <commit_msg>Fix build break due to incorrect merge, TBR=awalker<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string_util.h" #include "webkit/glue/plugins/test/plugin_client.h" #include "webkit/glue/plugins/test/plugin_arguments_test.h" #include "webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h" #include "webkit/glue/plugins/test/plugin_get_javascript_url_test.h" #include "webkit/glue/plugins/test/plugin_geturl_test.h" #include "webkit/glue/plugins/test/plugin_javascript_open_popup.h" #include "webkit/glue/plugins/test/plugin_new_fails_test.h" #include "webkit/glue/plugins/test/plugin_private_test.h" #include "webkit/glue/plugins/test/plugin_npobject_lifetime_test.h" #include "webkit/glue/plugins/test/plugin_npobject_proxy_test.h" #include "webkit/glue/plugins/test/plugin_window_size_test.h" #include "webkit/glue/plugins/test/plugin_windowless_test.h" #include "third_party/npapi/bindings/npapi.h" #include "third_party/npapi/bindings/npruntime.h" namespace NPAPIClient { NPNetscapeFuncs* PluginClient::host_functions_; NPError PluginClient::GetEntryPoints(NPPluginFuncs* pFuncs) { if (pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; if (pFuncs->size < sizeof(NPPluginFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; pFuncs->javaClass = reinterpret_cast<JRIGlobalRef>(NPP_GetJavaClass); return NPERR_NO_ERROR; } NPError PluginClient::Initialize(NPNetscapeFuncs* pFuncs) { if (pFuncs == NULL) { return NPERR_INVALID_FUNCTABLE_ERROR; } if (static_cast<unsigned char>((pFuncs->version >> 8) & 0xff) > NP_VERSION_MAJOR) { return NPERR_INCOMPATIBLE_VERSION_ERROR; } host_functions_ = pFuncs; return NPERR_NO_ERROR; } NPError PluginClient::Shutdown() { return NPERR_NO_ERROR; } } // namespace NPAPIClient extern "C" { NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; // We look at the test name requested via the plugin arguments. We match // that against a given test and try to instantiate it. // lookup the name parameter std::string test_name; for (int name_index = 0; name_index < argc; name_index++) if (base::strcasecmp(argn[name_index], "name") == 0) { test_name = argv[name_index]; break; } if (test_name.empty()) return NPERR_GENERIC_ERROR; // no name found NPError ret = NPERR_GENERIC_ERROR; bool windowless_plugin = false; NPAPIClient::PluginTest *new_test = NULL; if (test_name == "arguments") { new_test = new NPAPIClient::PluginArgumentsTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "geturl") { new_test = new NPAPIClient::PluginGetURLTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "npobject_proxy") { new_test = new NPAPIClient::NPObjectProxyTest(instance, NPAPIClient::PluginClient::HostFunctions()); #if defined(OS_WIN) // TODO(port): plugin_windowless_test.*. } else if (test_name == "execute_script_delete_in_paint" || test_name == "execute_script_delete_in_mouse_move" || test_name == "delete_frame_test") { new_test = new NPAPIClient::WindowlessPluginTest(instance, NPAPIClient::PluginClient::HostFunctions(), test_name); windowless_plugin = true; #endif } else if (test_name == "getjavascripturl") { new_test = new NPAPIClient::ExecuteGetJavascriptUrlTest(instance, NPAPIClient::PluginClient::HostFunctions()); #if defined(OS_WIN) // TODO(port): plugin_window_size_test.*. } else if (test_name == "checkwindowrect") { new_test = new NPAPIClient::PluginWindowSizeTest(instance, NPAPIClient::PluginClient::HostFunctions()); #endif } else if (test_name == "self_delete_plugin_stream") { new_test = new NPAPIClient::DeletePluginInStreamTest(instance, NPAPIClient::PluginClient::HostFunctions()); #if defined(OS_WIN) // TODO(port): plugin_npobject_lifetime_test.*. } else if (test_name == "npobject_lifetime_test") { new_test = new NPAPIClient::NPObjectLifetimeTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "npobject_lifetime_test_second_instance") { new_test = new NPAPIClient::NPObjectLifetimeTestInstance2(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "new_fails") { new_test = new NPAPIClient::NewFailsTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "npobject_delete_plugin_in_evaluate") { new_test = new NPAPIClient::NPObjectDeletePluginInNPN_Evaluate(instance, NPAPIClient::PluginClient::HostFunctions()); #endif } else if (test_name == "plugin_javascript_open_popup_with_plugin") { new_test = new NPAPIClient::ExecuteJavascriptOpenPopupWithPluginTest( instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "plugin_popup_with_plugin_target") { new_test = new NPAPIClient::ExecuteJavascriptPopupWindowTargetPluginTest( instance, NPAPIClient::PluginClient::HostFunctions()); } else if (test_name == "private") { new_test = new NPAPIClient::PrivateTest(instance, NPAPIClient::PluginClient::HostFunctions()); } else { // If we don't have a test case for this, create a // generic one which basically never fails. LOG(WARNING) << "Unknown test name '" << test_name << "'; using default test."; new_test = new NPAPIClient::PluginTest(instance, NPAPIClient::PluginClient::HostFunctions()); } if (new_test) { ret = new_test->New(mode, argc, (const char**)argn, (const char**)argv, saved); if ((ret == NPERR_NO_ERROR) && windowless_plugin) { NPAPIClient::PluginClient::HostFunctions()->setvalue( instance, NPPVpluginWindowBool, NULL); } } return ret; } NPError NPP_Destroy(NPP instance, NPSavedData** save) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; delete plugin; // XXXMB - do work here. return NPERR_GENERIC_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* pNPWindow) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; if (pNPWindow->window == NULL) { return NPERR_NO_ERROR; } NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->SetWindow(pNPWindow); } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->NewStream(type, stream, seekable, stype); } int32 NPP_WriteReady(NPP instance, NPStream *stream) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->WriteReady(stream); } int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->Write(stream, offset, len, buffer); } NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPError reason) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->DestroyStream(stream, reason); } void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) { if (instance == NULL) return; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->StreamAsFile(stream, fname); } void NPP_Print(NPP instance, NPPrint* printInfo) { if (instance == NULL) return; // XXXMB - do work here. } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if (instance == NULL) return; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->URLNotify(url, reason, notifyData); } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; // XXXMB - do work here. return NPERR_GENERIC_ERROR; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; // XXXMB - do work here. return NPERR_GENERIC_ERROR; } int16 NPP_HandleEvent(NPP instance, void* event) { if (instance == NULL) return 0; NPAPIClient::PluginTest *plugin = (NPAPIClient::PluginTest*)instance->pdata; return plugin->HandleEvent(event); } void* NPP_GetJavaClass(void) { // XXXMB - do work here. return NULL; } } // extern "C" <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PresenterPaneFactory.hxx,v $ * * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SDEXT_PRESENTER_PANE_FACTORY_HXX #define SDEXT_PRESENTER_PANE_FACTORY_HXX #include <cppuhelper/compbase1.hxx> #include <cppuhelper/basemutex.hxx> #include <com/sun/star/frame/XController.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/drawing/XPresenterHelper.hpp> #include <com/sun/star/drawing/framework/XConfigurationController.hpp> #include <com/sun/star/drawing/framework/XPane.hpp> #include <com/sun/star/drawing/framework/XResourceFactory.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <rtl/ref.hxx> namespace css = ::com::sun::star; namespace sdext { namespace presenter { class PresenterController; namespace { typedef ::cppu::WeakComponentImplHelper1 < css::drawing::framework::XResourceFactory > PresenterPaneFactoryInterfaceBase; } /** The PresenerPaneFactory provides a fixed set of panes. In order to make the presener screen more easily extendable in the future the set of supported panes could be made extendable on demand. */ class PresenterPaneFactory : public ::cppu::BaseMutex, public PresenterPaneFactoryInterfaceBase { public: static const ::rtl::OUString msCurrentSlidePreviewPaneURL; static const ::rtl::OUString msNextSlidePreviewPaneURL; static const ::rtl::OUString msNotesPaneURL; static const ::rtl::OUString msToolBarPaneURL; static const ::rtl::OUString msSlideSorterPaneURL; static const ::rtl::OUString msClockPaneURL; static const ::rtl::OUString msDebugPaneURL; static const ::rtl::OUString msOverlayPaneURL; /** Create a new instance of this class and register it as resource factory in the drawing framework of the given controller. This registration keeps it alive. When the drawing framework is shut down and releases its reference to the factory then the factory is destroyed. */ static css::uno::Reference<css::drawing::framework::XResourceFactory> Create ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const css::uno::Reference<css::frame::XController>& rxController, const ::rtl::Reference<PresenterController>& rpPresenterController); virtual ~PresenterPaneFactory (void); static ::rtl::OUString getImplementationName_static (void); static css::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static (void); static css::uno::Reference<css::uno::XInterface> Create( const css::uno::Reference<css::uno::XComponentContext>& rxContext) SAL_THROW((css::uno::Exception)); virtual void SAL_CALL disposing (void) throw (css::uno::RuntimeException); // XResourceFactory virtual css::uno::Reference<css::drawing::framework::XResource> SAL_CALL createResource ( const ::com::sun::star::uno::Reference< com::sun::star::drawing::framework::XResourceId>& rxPaneId) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL releaseResource ( const ::com::sun::star::uno::Reference<com::sun::star::drawing::framework::XResource>& rxPane) throw (::com::sun::star::uno::RuntimeException); private: css::uno::WeakReference<css::uno::XComponentContext> mxComponentContextWeak; css::uno::WeakReference<css::drawing::framework::XConfigurationController> mxConfigurationControllerWeak; ::rtl::Reference<PresenterController> mpPresenterController; PresenterPaneFactory ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const ::rtl::Reference<PresenterController>& rpPresenterController); void Register (const css::uno::Reference<css::frame::XController>& rxController); css::uno::Reference<css::drawing::framework::XResource> CreatePane ( const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId, const ::rtl::OUString& rsTitle); css::uno::Reference<css::drawing::framework::XResource> CreatePane ( const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId, const ::rtl::OUString& rsTitle, const css::uno::Reference<css::drawing::framework::XPane>& rxParentPane, const bool bIsSpritePane); void ThrowIfDisposed (void) const throw (::com::sun::star::lang::DisposedException); }; } } #endif <commit_msg>INTEGRATION: CWS presenterscreen (1.2.4); FILE MERGED 2008/04/23 11:57:36 af 1.2.4.3: #i18486# Made caching optional, defaults to off. 2008/04/22 08:25:16 af 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008/04/16 15:48:46 af 1.2.4.1: #i18486# Added support for caching unused panes.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PresenterPaneFactory.hxx,v $ * * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SDEXT_PRESENTER_PANE_FACTORY_HXX #define SDEXT_PRESENTER_PANE_FACTORY_HXX #include <cppuhelper/compbase1.hxx> #include <cppuhelper/basemutex.hxx> #include <com/sun/star/frame/XController.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/drawing/XPresenterHelper.hpp> #include <com/sun/star/drawing/framework/XConfigurationController.hpp> #include <com/sun/star/drawing/framework/XPane.hpp> #include <com/sun/star/drawing/framework/XResourceFactory.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <rtl/ref.hxx> #include <boost/scoped_ptr.hpp> #include <map> namespace css = ::com::sun::star; namespace sdext { namespace presenter { class PresenterController; namespace { typedef ::cppu::WeakComponentImplHelper1 < css::drawing::framework::XResourceFactory > PresenterPaneFactoryInterfaceBase; } /** The PresenerPaneFactory provides a fixed set of panes. In order to make the presener screen more easily extendable in the future the set of supported panes could be made extendable on demand. */ class PresenterPaneFactory : public ::cppu::BaseMutex, public PresenterPaneFactoryInterfaceBase { public: static const ::rtl::OUString msCurrentSlidePreviewPaneURL; static const ::rtl::OUString msNextSlidePreviewPaneURL; static const ::rtl::OUString msNotesPaneURL; static const ::rtl::OUString msToolBarPaneURL; static const ::rtl::OUString msSlideSorterPaneURL; static const ::rtl::OUString msHelpPaneURL; static const ::rtl::OUString msOverlayPaneURL; /** Create a new instance of this class and register it as resource factory in the drawing framework of the given controller. This registration keeps it alive. When the drawing framework is shut down and releases its reference to the factory then the factory is destroyed. */ static css::uno::Reference<css::drawing::framework::XResourceFactory> Create ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const css::uno::Reference<css::frame::XController>& rxController, const ::rtl::Reference<PresenterController>& rpPresenterController); virtual ~PresenterPaneFactory (void); static ::rtl::OUString getImplementationName_static (void); static css::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static (void); static css::uno::Reference<css::uno::XInterface> Create( const css::uno::Reference<css::uno::XComponentContext>& rxContext) SAL_THROW((css::uno::Exception)); virtual void SAL_CALL disposing (void) throw (css::uno::RuntimeException); // XResourceFactory virtual css::uno::Reference<css::drawing::framework::XResource> SAL_CALL createResource ( const ::com::sun::star::uno::Reference< com::sun::star::drawing::framework::XResourceId>& rxPaneId) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL releaseResource ( const ::com::sun::star::uno::Reference<com::sun::star::drawing::framework::XResource>& rxPane) throw (::com::sun::star::uno::RuntimeException); private: css::uno::WeakReference<css::uno::XComponentContext> mxComponentContextWeak; css::uno::WeakReference<css::drawing::framework::XConfigurationController> mxConfigurationControllerWeak; ::rtl::Reference<PresenterController> mpPresenterController; typedef ::std::map<rtl::OUString, css::uno::Reference<css::drawing::framework::XResource> > ResourceContainer; ::boost::scoped_ptr<ResourceContainer> mpResourceCache; PresenterPaneFactory ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const ::rtl::Reference<PresenterController>& rpPresenterController); void Register (const css::uno::Reference<css::frame::XController>& rxController); css::uno::Reference<css::drawing::framework::XResource> CreatePane ( const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId, const ::rtl::OUString& rsTitle); css::uno::Reference<css::drawing::framework::XResource> CreatePane ( const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId, const ::rtl::OUString& rsTitle, const css::uno::Reference<css::drawing::framework::XPane>& rxParentPane, const bool bIsSpritePane); void ThrowIfDisposed (void) const throw (::com::sun::star::lang::DisposedException); }; } } #endif <|endoftext|>
<commit_before>#define SEQAN_TEST #include <seqan/sequence.h> #include <seqan/file.h> #include <seqan/align.h> using namespace std; using namespace seqan; template <typename TAlphabet> String<TAlphabet> generate_random(int length_of_sequence) { // init string String<TAlphabet> ret; resize(ret,length_of_sequence); int alphabet_size = ValueSize<TAlphabet>::VALUE; // generate random sequence of length "length_of_sequence" for (int i = 0; i < length_of_sequence; ++i) ret[i] = static_cast<TAlphabet>((alphabet_size * static_cast<int>(rand()) / (static_cast<int>(RAND_MAX) + 1))); return ret; } template <typename TAlphabet> String<TAlphabet> generate_second_sequence(int error_count,String<TAlphabet> copy_of_org) { int length_of_org = length(copy_of_org); int alphabet_size = ValueSize<TAlphabet>::VALUE; for(int i = 0;i < error_count;++i) { // introduce errors into sequence // 1. choose position int pos = static_cast<int>((int)length_of_org * rand() / (RAND_MAX + 1.0)); // generate new char TAlphabet new_char = static_cast<TAlphabet>((alphabet_size * static_cast<int>(rand()) / (static_cast<int>(RAND_MAX) + 1))); // replace char copy_of_org[pos] = new_char; } return copy_of_org; } template <typename TAlphabet> void erase_sequence_parts(int erase_count,String<TAlphabet> & sequence) { // erase single characters int len = length(sequence) - 1; for(int i = 0;i < erase_count;++i) { // calc position int pos = static_cast<int>((int)(len - i) * rand() / (RAND_MAX + 1.0)); erase(sequence,pos,pos+1); } } #define ALPHABET Dna int edit_distance(Align<String<ALPHABET>, ArrayGaps> & ali) { int len_ali = length(row(ali,0)); Iterator<Row<Align<String<ALPHABET>, ArrayGaps> >::Type >::Type ali_row_0 = iter(row(ali, 0), 0); Iterator<Row<Align<String<ALPHABET>, ArrayGaps> >::Type >::Type ali_row_1 = iter(row(ali, 1), 0); int score = 0; int i; // iteration ueber das alignment for(i = 0;i < len_ali;++i) { if(isGap(ali_row_0)) { --score; } else if(isGap(ali_row_1)) { --score; } else if(value(ali_row_0) != value(ali_row_1)) { --score; } goNext(ali_row_0); goNext(ali_row_1); } return score; } SEQAN_DEFINE_TEST(test_align_myers_test_short) { int nw_score,m_score,hm_score; int test_repeat = 1; int test_count = 0; while(test_count < test_repeat) { // create random sequences String<ALPHABET> s_str0 = generate_random<ALPHABET>(20); String<ALPHABET> s_str1 = generate_second_sequence<ALPHABET>(3,s_str0); erase_sequence_parts(3,s_str1); // test alignment with random sequences // use needleman wunsch as reference Align<String<ALPHABET>, ArrayGaps> s_nw_ali; resize(rows(s_nw_ali), 2); assignSource(row(s_nw_ali, 0), s_str0); assignSource(row(s_nw_ali, 1), s_str1); nw_score = globalAlignment(s_nw_ali,SimpleScore()); // compute only score Align<String<ALPHABET>, ArrayGaps> s_m_ali; resize(rows(s_m_ali), 2); assignSource(row(s_m_ali, 0), s_str0); assignSource(row(s_m_ali, 1), s_str1); m_score = globalAlignment(s_m_ali,SimpleScore(), MyersBitVector()); SEQAN_TASSERT(nw_score == m_score); // compute complete alignments Align<String<ALPHABET>, ArrayGaps> s_hm_ali; resize(rows(s_hm_ali), 2); assignSource(row(s_hm_ali, 0), s_str0); assignSource(row(s_hm_ali, 1), s_str1); hm_score = globalAlignment(s_hm_ali,SimpleScore(), MyersHirschberg()); SEQAN_TASSERT(nw_score == hm_score); SEQAN_TASSERT(edit_distance(s_hm_ali) == hm_score); ++test_count; } } SEQAN_DEFINE_TEST(test_align_myers_test_long) { int nw_score,m_score,hm_score; int test_repeat = 1; int test_count = 0; while(test_count < test_repeat) { // create random sequences String<ALPHABET> l_str0 = generate_random<ALPHABET>(200); String<ALPHABET> l_str1 = generate_second_sequence<ALPHABET>(10,l_str0); erase_sequence_parts(5,l_str1); // test alignment with random sequences // use needleman wunsch as reference Align<String<ALPHABET>, ArrayGaps> l_nw_ali; resize(rows(l_nw_ali), 2); assignSource(row(l_nw_ali, 0), l_str0); assignSource(row(l_nw_ali, 1), l_str1); nw_score = globalAlignment(l_nw_ali,SimpleScore()); // compute only score Align<String<ALPHABET>, ArrayGaps> l_m_ali; resize(rows(l_m_ali), 2); assignSource(row(l_m_ali, 0), l_str0); assignSource(row(l_m_ali, 1), l_str1); m_score = globalAlignment(l_m_ali,SimpleScore(), MyersBitVector()); SEQAN_TASSERT(nw_score == m_score); // compute complete alignments Align<String<ALPHABET>, ArrayGaps> l_hm_ali; resize(rows(l_hm_ali), 2); assignSource(row(l_hm_ali, 0), l_str0); assignSource(row(l_hm_ali, 1), l_str1); hm_score = globalAlignment(l_hm_ali, SimpleScore(), MyersHirschberg()); SEQAN_TASSERT(nw_score == hm_score); SEQAN_TASSERT(edit_distance(l_hm_ali) == hm_score); ++test_count; } } SEQAN_DEFINE_TEST(test_align_hirschberger) { int nw_score, hm_score; int test_repeat = 1; int test_count = 0; while(test_count < test_repeat) { // create random sequences String<ALPHABET> str0 = generate_random<ALPHABET>(20); String<ALPHABET> str1 = generate_second_sequence<ALPHABET>(2,str0); erase_sequence_parts(5,str1); // test alignment with random sequences // use needleman wunsch as reference Align<String<ALPHABET>, ArrayGaps> nw_ali; resize(rows(nw_ali), 2); assignSource(row(nw_ali, 0), str0); assignSource(row(nw_ali, 1), str1); nw_score = globalAlignment(nw_ali,SimpleScore()); // compute complete alignments with hirschberg algorithm Align<String<ALPHABET>, ArrayGaps> hirsch_ali; resize(rows(hirsch_ali), 2); assignSource(row(hirsch_ali, 0), str0); assignSource(row(hirsch_ali, 1), str1); hm_score = globalAlignment(hirsch_ali,SimpleScore(), Hirschberg()); SEQAN_TASSERT(nw_score == hm_score); SEQAN_TASSERT(edit_distance(hirsch_ali) == hm_score); ++test_count; } } <commit_msg>Fixing integer overflow warning.<commit_after>#define SEQAN_TEST #include <seqan/sequence.h> #include <seqan/file.h> #include <seqan/align.h> using namespace std; using namespace seqan; template <typename TAlphabet> String<TAlphabet> generate_random(int length_of_sequence) { // init string String<TAlphabet> ret; resize(ret,length_of_sequence); int alphabet_size = ValueSize<TAlphabet>::VALUE; // generate random sequence of length "length_of_sequence" for (int i = 0; i < length_of_sequence; ++i) ret[i] = static_cast<TAlphabet>((rand() >> 4) % alphabet_size); return ret; } template <typename TAlphabet> String<TAlphabet> generate_second_sequence(int error_count,String<TAlphabet> copy_of_org) { int length_of_org = length(copy_of_org); int alphabet_size = ValueSize<TAlphabet>::VALUE; for(int i = 0;i < error_count;++i) { // introduce errors into sequence // 1. choose position int pos = static_cast<int>((int)length_of_org * rand() / (RAND_MAX + 1.0)); // generate new char TAlphabet new_char = static_cast<TAlphabet>((rand() >> 4) % alphabet_size); // replace char copy_of_org[pos] = new_char; } return copy_of_org; } template <typename TAlphabet> void erase_sequence_parts(int erase_count,String<TAlphabet> & sequence) { // erase single characters int len = length(sequence) - 1; for(int i = 0;i < erase_count;++i) { // calc position int pos = static_cast<int>((int)(len - i) * rand() / (RAND_MAX + 1.0)); erase(sequence,pos,pos+1); } } #define ALPHABET Dna int edit_distance(Align<String<ALPHABET>, ArrayGaps> & ali) { int len_ali = length(row(ali,0)); Iterator<Row<Align<String<ALPHABET>, ArrayGaps> >::Type >::Type ali_row_0 = iter(row(ali, 0), 0); Iterator<Row<Align<String<ALPHABET>, ArrayGaps> >::Type >::Type ali_row_1 = iter(row(ali, 1), 0); int score = 0; int i; // iteration ueber das alignment for(i = 0;i < len_ali;++i) { if(isGap(ali_row_0)) { --score; } else if(isGap(ali_row_1)) { --score; } else if(value(ali_row_0) != value(ali_row_1)) { --score; } goNext(ali_row_0); goNext(ali_row_1); } return score; } SEQAN_DEFINE_TEST(test_align_myers_test_short) { int nw_score,m_score,hm_score; int test_repeat = 1; int test_count = 0; while(test_count < test_repeat) { // create random sequences String<ALPHABET> s_str0 = generate_random<ALPHABET>(20); String<ALPHABET> s_str1 = generate_second_sequence<ALPHABET>(3,s_str0); erase_sequence_parts(3,s_str1); // test alignment with random sequences // use needleman wunsch as reference Align<String<ALPHABET>, ArrayGaps> s_nw_ali; resize(rows(s_nw_ali), 2); assignSource(row(s_nw_ali, 0), s_str0); assignSource(row(s_nw_ali, 1), s_str1); nw_score = globalAlignment(s_nw_ali,SimpleScore()); // compute only score Align<String<ALPHABET>, ArrayGaps> s_m_ali; resize(rows(s_m_ali), 2); assignSource(row(s_m_ali, 0), s_str0); assignSource(row(s_m_ali, 1), s_str1); m_score = globalAlignment(s_m_ali,SimpleScore(), MyersBitVector()); SEQAN_TASSERT(nw_score == m_score); // compute complete alignments Align<String<ALPHABET>, ArrayGaps> s_hm_ali; resize(rows(s_hm_ali), 2); assignSource(row(s_hm_ali, 0), s_str0); assignSource(row(s_hm_ali, 1), s_str1); hm_score = globalAlignment(s_hm_ali,SimpleScore(), MyersHirschberg()); SEQAN_TASSERT(nw_score == hm_score); SEQAN_TASSERT(edit_distance(s_hm_ali) == hm_score); ++test_count; } } SEQAN_DEFINE_TEST(test_align_myers_test_long) { int nw_score,m_score,hm_score; int test_repeat = 1; int test_count = 0; while(test_count < test_repeat) { // create random sequences String<ALPHABET> l_str0 = generate_random<ALPHABET>(200); String<ALPHABET> l_str1 = generate_second_sequence<ALPHABET>(10,l_str0); erase_sequence_parts(5,l_str1); // test alignment with random sequences // use needleman wunsch as reference Align<String<ALPHABET>, ArrayGaps> l_nw_ali; resize(rows(l_nw_ali), 2); assignSource(row(l_nw_ali, 0), l_str0); assignSource(row(l_nw_ali, 1), l_str1); nw_score = globalAlignment(l_nw_ali,SimpleScore()); // compute only score Align<String<ALPHABET>, ArrayGaps> l_m_ali; resize(rows(l_m_ali), 2); assignSource(row(l_m_ali, 0), l_str0); assignSource(row(l_m_ali, 1), l_str1); m_score = globalAlignment(l_m_ali,SimpleScore(), MyersBitVector()); SEQAN_TASSERT(nw_score == m_score); // compute complete alignments Align<String<ALPHABET>, ArrayGaps> l_hm_ali; resize(rows(l_hm_ali), 2); assignSource(row(l_hm_ali, 0), l_str0); assignSource(row(l_hm_ali, 1), l_str1); hm_score = globalAlignment(l_hm_ali, SimpleScore(), MyersHirschberg()); SEQAN_TASSERT(nw_score == hm_score); SEQAN_TASSERT(edit_distance(l_hm_ali) == hm_score); ++test_count; } } SEQAN_DEFINE_TEST(test_align_hirschberger) { int nw_score, hm_score; int test_repeat = 1; int test_count = 0; while(test_count < test_repeat) { // create random sequences String<ALPHABET> str0 = generate_random<ALPHABET>(20); String<ALPHABET> str1 = generate_second_sequence<ALPHABET>(2,str0); erase_sequence_parts(5,str1); // test alignment with random sequences // use needleman wunsch as reference Align<String<ALPHABET>, ArrayGaps> nw_ali; resize(rows(nw_ali), 2); assignSource(row(nw_ali, 0), str0); assignSource(row(nw_ali, 1), str1); nw_score = globalAlignment(nw_ali,SimpleScore()); // compute complete alignments with hirschberg algorithm Align<String<ALPHABET>, ArrayGaps> hirsch_ali; resize(rows(hirsch_ali), 2); assignSource(row(hirsch_ali, 0), str0); assignSource(row(hirsch_ali, 1), str1); hm_score = globalAlignment(hirsch_ali,SimpleScore(), Hirschberg()); SEQAN_TASSERT(nw_score == hm_score); SEQAN_TASSERT(edit_distance(hirsch_ali) == hm_score); ++test_count; } } <|endoftext|>
<commit_before>/* Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ #include "UploadOperationFactory.hpp" #include "RpcOperationFactory_p.hpp" // TODO: Instead of this include, add a generated cpp with all needed template instances #include "ServerRpcOperation_p.hpp" #include "IMediaService.hpp" #include "ServerApi.hpp" #include "ServerRpcLayer.hpp" #include "TelegramServerUser.hpp" #include "Debug_p.hpp" #include "RpcError.hpp" #include "RpcProcessingContext.hpp" #include "MTProto/StreamExtraOperators.hpp" #include "FunctionStreamOperators.hpp" #include <QLoggingCategory> Q_LOGGING_CATEGORY(c_serverUploadRpcCategory, "telegram.server.rpc.upload", QtWarningMsg) namespace Telegram { namespace Server { // Generated process methods bool UploadRpcOperation::processGetCdnFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetCdnFile); context.inputStream() >> m_getCdnFile; return !context.inputStream().error(); } bool UploadRpcOperation::processGetCdnFileHashes(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetCdnFileHashes); context.inputStream() >> m_getCdnFileHashes; return !context.inputStream().error(); } bool UploadRpcOperation::processGetFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetFile); context.inputStream() >> m_getFile; return !context.inputStream().error(); } bool UploadRpcOperation::processGetWebFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetWebFile); context.inputStream() >> m_getWebFile; return !context.inputStream().error(); } bool UploadRpcOperation::processReuploadCdnFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runReuploadCdnFile); context.inputStream() >> m_reuploadCdnFile; return !context.inputStream().error(); } bool UploadRpcOperation::processSaveBigFilePart(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runSaveBigFilePart); context.inputStream() >> m_saveBigFilePart; return !context.inputStream().error(); } bool UploadRpcOperation::processSaveFilePart(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runSaveFilePart); context.inputStream() >> m_saveFilePart; return !context.inputStream().error(); } // End of generated process methods // Generated run methods void UploadRpcOperation::runGetCdnFile() { // TLFunctions::TLUploadGetCdnFile &arguments = m_getCdnFile; if (processNotImplementedMethod(TLValue::UploadGetCdnFile)) { return; } TLUploadCdnFile result; sendRpcReply(result); } void UploadRpcOperation::runGetCdnFileHashes() { // TLFunctions::TLUploadGetCdnFileHashes &arguments = m_getCdnFileHashes; if (processNotImplementedMethod(TLValue::UploadGetCdnFileHashes)) { return; } TLVector<TLCdnFileHash> result; sendRpcReply(result); } void UploadRpcOperation::runGetFile() { TLFunctions::TLUploadGetFile &arguments = m_getFile; FileDescriptor descriptor; switch (arguments.location.tlType) { case TLValue::InputFileLocation: descriptor = api()->mediaService()->getSecretFileDescriptor( arguments.location.volumeId, arguments.location.localId, arguments.location.secret ); break; case TLValue::InputDocumentFileLocation: descriptor = api()->mediaService()->getDocumentFileDescriptor( arguments.location.id, arguments.location.accessHash ); break; default: qCWarning(c_serverUploadRpcCategory) << CALL_INFO << "Not implemented" << arguments.location.tlType.toString(); sendRpcError(RpcError()); return; } if (!descriptor.isValid()) { qCWarning(c_serverUploadRpcCategory) << CALL_INFO << "Invalid descriptor"; sendRpcError(RpcError()); return; } QIODevice *file = api()->mediaService()->beginReadFile(descriptor); if (!file) { qCWarning(c_serverUploadRpcCategory) << CALL_INFO << "Unable to read file"; sendRpcError(RpcError()); return; } file->seek(arguments.offset); TLUploadFile result; result.tlType = TLValue::UploadFile; result.type.tlType = TLValue::StorageFilePng; result.mtime = descriptor.date; result.bytes = file->read(arguments.limit); api()->mediaService()->endReadFile(file); sendRpcReply(result); } void UploadRpcOperation::runGetWebFile() { // TLFunctions::TLUploadGetWebFile &arguments = m_getWebFile; if (processNotImplementedMethod(TLValue::UploadGetWebFile)) { return; } TLUploadWebFile result; sendRpcReply(result); } void UploadRpcOperation::runReuploadCdnFile() { // TLFunctions::TLUploadReuploadCdnFile &arguments = m_reuploadCdnFile; if (processNotImplementedMethod(TLValue::UploadReuploadCdnFile)) { return; } TLVector<TLCdnFileHash> result; sendRpcReply(result); } void UploadRpcOperation::runSaveBigFilePart() { // TLFunctions::TLUploadSaveBigFilePart &arguments = m_saveBigFilePart; if (processNotImplementedMethod(TLValue::UploadSaveBigFilePart)) { return; } bool result; sendRpcReply(result); } void UploadRpcOperation::runSaveFilePart() { TLFunctions::TLUploadSaveFilePart &arguments = m_saveFilePart; bool result = api()->mediaService()->uploadFilePart(arguments.fileId, arguments.filePart, arguments.bytes); sendRpcReply(result); } // End of generated run methods void UploadRpcOperation::setRunMethod(UploadRpcOperation::RunMethod method) { m_runMethod = method; } UploadRpcOperation::ProcessingMethod UploadRpcOperation::getMethodForRpcFunction(TLValue function) { switch (function) { // Generated methodForRpcFunction cases case TLValue::UploadGetCdnFile: return &UploadRpcOperation::processGetCdnFile; case TLValue::UploadGetCdnFileHashes: return &UploadRpcOperation::processGetCdnFileHashes; case TLValue::UploadGetFile: return &UploadRpcOperation::processGetFile; case TLValue::UploadGetWebFile: return &UploadRpcOperation::processGetWebFile; case TLValue::UploadReuploadCdnFile: return &UploadRpcOperation::processReuploadCdnFile; case TLValue::UploadSaveBigFilePart: return &UploadRpcOperation::processSaveBigFilePart; case TLValue::UploadSaveFilePart: return &UploadRpcOperation::processSaveFilePart; // End of generated methodForRpcFunction cases default: return nullptr; } } RpcOperation *UploadOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context) { return processRpcCallImpl<UploadRpcOperation>(layer, context); } } // Server namespace } // Telegram namespace <commit_msg>Server: Refactor Upload::runGetFile()<commit_after>/* Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ #include "UploadOperationFactory.hpp" #include "RpcOperationFactory_p.hpp" // TODO: Instead of this include, add a generated cpp with all needed template instances #include "ServerRpcOperation_p.hpp" #include "IMediaService.hpp" #include "ServerApi.hpp" #include "ServerRpcLayer.hpp" #include "TelegramServerUser.hpp" #include "Debug_p.hpp" #include "RpcError.hpp" #include "RpcProcessingContext.hpp" #include "MTProto/StreamExtraOperators.hpp" #include "FunctionStreamOperators.hpp" #include <QLoggingCategory> Q_LOGGING_CATEGORY(c_serverUploadRpcCategory, "telegram.server.rpc.upload", QtWarningMsg) namespace Telegram { namespace Server { // Generated process methods bool UploadRpcOperation::processGetCdnFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetCdnFile); context.inputStream() >> m_getCdnFile; return !context.inputStream().error(); } bool UploadRpcOperation::processGetCdnFileHashes(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetCdnFileHashes); context.inputStream() >> m_getCdnFileHashes; return !context.inputStream().error(); } bool UploadRpcOperation::processGetFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetFile); context.inputStream() >> m_getFile; return !context.inputStream().error(); } bool UploadRpcOperation::processGetWebFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runGetWebFile); context.inputStream() >> m_getWebFile; return !context.inputStream().error(); } bool UploadRpcOperation::processReuploadCdnFile(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runReuploadCdnFile); context.inputStream() >> m_reuploadCdnFile; return !context.inputStream().error(); } bool UploadRpcOperation::processSaveBigFilePart(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runSaveBigFilePart); context.inputStream() >> m_saveBigFilePart; return !context.inputStream().error(); } bool UploadRpcOperation::processSaveFilePart(RpcProcessingContext &context) { setRunMethod(&UploadRpcOperation::runSaveFilePart); context.inputStream() >> m_saveFilePart; return !context.inputStream().error(); } // End of generated process methods // Generated run methods void UploadRpcOperation::runGetCdnFile() { // TLFunctions::TLUploadGetCdnFile &arguments = m_getCdnFile; if (processNotImplementedMethod(TLValue::UploadGetCdnFile)) { return; } TLUploadCdnFile result; sendRpcReply(result); } void UploadRpcOperation::runGetCdnFileHashes() { // TLFunctions::TLUploadGetCdnFileHashes &arguments = m_getCdnFileHashes; if (processNotImplementedMethod(TLValue::UploadGetCdnFileHashes)) { return; } TLVector<TLCdnFileHash> result; sendRpcReply(result); } void UploadRpcOperation::runGetFile() { TLFunctions::TLUploadGetFile &arguments = m_getFile; const TLInputFileLocation &location = arguments.location; FileDescriptor descriptor; switch (arguments.location.tlType) { case TLValue::InputFileLocation: descriptor = api()->mediaService()->getSecretFileDescriptor( location.volumeId, location.localId, location.secret ); break; case TLValue::InputDocumentFileLocation: descriptor = api()->mediaService()->getDocumentFileDescriptor( location.id, location.accessHash ); break; default: qCWarning(c_serverUploadRpcCategory) << CALL_INFO << "Not implemented" << location.tlType.toString(); sendRpcError(RpcError()); return; } if (!descriptor.isValid()) { qCWarning(c_serverUploadRpcCategory) << CALL_INFO << "Invalid descriptor"; sendRpcError(RpcError()); return; } QIODevice *file = api()->mediaService()->beginReadFile(descriptor); if (!file) { qCWarning(c_serverUploadRpcCategory) << CALL_INFO << "Unable to read file"; sendRpcError(RpcError()); return; } file->seek(arguments.offset); TLUploadFile result; result.tlType = TLValue::UploadFile; result.type.tlType = TLValue::StorageFilePng; result.mtime = descriptor.date; result.bytes = file->read(arguments.limit); api()->mediaService()->endReadFile(file); sendRpcReply(result); } void UploadRpcOperation::runGetWebFile() { // TLFunctions::TLUploadGetWebFile &arguments = m_getWebFile; if (processNotImplementedMethod(TLValue::UploadGetWebFile)) { return; } TLUploadWebFile result; sendRpcReply(result); } void UploadRpcOperation::runReuploadCdnFile() { // TLFunctions::TLUploadReuploadCdnFile &arguments = m_reuploadCdnFile; if (processNotImplementedMethod(TLValue::UploadReuploadCdnFile)) { return; } TLVector<TLCdnFileHash> result; sendRpcReply(result); } void UploadRpcOperation::runSaveBigFilePart() { // TLFunctions::TLUploadSaveBigFilePart &arguments = m_saveBigFilePart; if (processNotImplementedMethod(TLValue::UploadSaveBigFilePart)) { return; } bool result; sendRpcReply(result); } void UploadRpcOperation::runSaveFilePart() { TLFunctions::TLUploadSaveFilePart &arguments = m_saveFilePart; bool result = api()->mediaService()->uploadFilePart(arguments.fileId, arguments.filePart, arguments.bytes); sendRpcReply(result); } // End of generated run methods void UploadRpcOperation::setRunMethod(UploadRpcOperation::RunMethod method) { m_runMethod = method; } UploadRpcOperation::ProcessingMethod UploadRpcOperation::getMethodForRpcFunction(TLValue function) { switch (function) { // Generated methodForRpcFunction cases case TLValue::UploadGetCdnFile: return &UploadRpcOperation::processGetCdnFile; case TLValue::UploadGetCdnFileHashes: return &UploadRpcOperation::processGetCdnFileHashes; case TLValue::UploadGetFile: return &UploadRpcOperation::processGetFile; case TLValue::UploadGetWebFile: return &UploadRpcOperation::processGetWebFile; case TLValue::UploadReuploadCdnFile: return &UploadRpcOperation::processReuploadCdnFile; case TLValue::UploadSaveBigFilePart: return &UploadRpcOperation::processSaveBigFilePart; case TLValue::UploadSaveFilePart: return &UploadRpcOperation::processSaveFilePart; // End of generated methodForRpcFunction cases default: return nullptr; } } RpcOperation *UploadOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context) { return processRpcCallImpl<UploadRpcOperation>(layer, context); } } // Server namespace } // Telegram namespace <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Juan Garcia-Prieto <juangpc@gmail.com>; * Lorenz Esch <lesch@mgh.harvard.edu>; * Wayne Mead <wayne.mead@uth.tmc.edu>; * John C. Mosher <John.C.Mosher@uth.tmc.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * @version dev * @date September, 2019 * * @section LICENSE * * Copyright (C) 2019, Juan Garcia-Prieto, Lorenz Esch, Matti Hamalainen, Wayne Mead, John C. Mosher. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Application for anonymizing patient and personal health information from a fiff file. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "settingscontrollerCL.h" #include "apphandler.h" #include <utils/generics/applicationlogger.h> //============================================================================================================= // Eigen //============================================================================================================= //============================================================================================================= // QT INCLUDES //============================================================================================================= //#include <QApplication> //#include <QCoreApplication> //#include <QMainWindow> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace UTILSLIB; //============================================================================================================= // MAIN //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char* argv[]) { qInstallMessageHandler(ApplicationLogger::customLogWriter); QScopedPointer<QCoreApplication> qtApp(MNEANONYMIZE::AppHandler::createApplication(argc, argv)); qtApp->setOrganizationName("MNE-CPP Project"); qtApp->setApplicationName("MNE Anonymize"); qtApp->setApplicationVersion("dev"); QScopedPointer<MNEANONYMIZE::SettingsControllerCL> controller(MNEANONYMIZE::AppHandler::dispatch(*qtApp)); // if (qobject_cast<QApplication *>(qtApp.data())) { // // to do -> develop GUI version... // //create reader object and parse data // MainWindow w; // w.show(); // } else { // // start non-GUI version... // MNEANONYMIZE::SettingsControllerCL controllerCL(qtApp->arguments()); // } return qtApp->exec(); } <commit_msg>main only includes necessary, adapt dispatch call<commit_after>//============================================================================================================= /** * @file main.cpp * @author Juan Garcia-Prieto <juangpc@gmail.com>; * Lorenz Esch <lesch@mgh.harvard.edu>; * Wayne Mead <wayne.mead@uth.tmc.edu>; * John C. Mosher <John.C.Mosher@uth.tmc.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * @version dev * @date September, 2019 * * @section LICENSE * * Copyright (C) 2019, Juan Garcia-Prieto, Lorenz Esch, Matti Hamalainen, Wayne Mead, John C. Mosher. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Application for anonymizing patient and personal health information from a fiff file. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "apphandler.h" #include <utils/generics/applicationlogger.h> //============================================================================================================= // Eigen //============================================================================================================= //============================================================================================================= // QT INCLUDES //============================================================================================================= //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace UTILSLIB; //============================================================================================================= // MAIN //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char* argv[]) { qInstallMessageHandler(ApplicationLogger::customLogWriter); QScopedPointer<QCoreApplication> qtApp(MNEANONYMIZE::AppHandler::createApplication(argc, argv)); qtApp->setOrganizationName("MNE-CPP Project"); qtApp->setApplicationName("MNE Anonymize"); qtApp->setApplicationVersion("dev"); QScopedPointer<QObject> controller(MNEANONYMIZE::AppHandler::dispatch(*qtApp)); // if (qobject_cast<QApplication *>(qtApp.data())) { // // to do -> develop GUI version... // //create reader object and parse data // MainWindow w; // w.show(); // } else { // // start non-GUI version... // MNEANONYMIZE::SettingsControllerCL controllerCL(qtApp->arguments()); // } return qtApp->exec(); } <|endoftext|>
<commit_before>/** * \file * \brief chip::lowLevelInitialization() implementation for STM32F7 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" #include "distortos/chip/CMSIS-proxy.h" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { RCC->AHB1ENR |= #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE RCC_AHB1ENR_GPIOAEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE RCC_AHB1ENR_GPIOBEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE RCC_AHB1ENR_GPIOCEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE RCC_AHB1ENR_GPIODEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE RCC_AHB1ENR_GPIOEEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE RCC_AHB1ENR_GPIOFEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE RCC_AHB1ENR_GPIOGEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE RCC_AHB1ENR_GPIOHEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE RCC_AHB1ENR_GPIOIEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE RCC_AHB1ENR_GPIOJEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE RCC_AHB1ENR_GPIOKEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE 0; } } // namespace chip } // namespace distortos <commit_msg>Handle new flash options in chip::lowLevelInitialization() for STM32F7<commit_after>/** * \file * \brief chip::lowLevelInitialization() implementation for STM32F7 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" #include "distortos/chip/CMSIS-proxy.h" #include "distortos/chip/STM32F7-FLASH.hpp" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { #ifdef CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(true); #else // !def CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(false); #endif // !def CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE #ifdef CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE enableArtAccelerator(); #else // !def CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE disableArtAccelerator(); #endif // !def CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE RCC->AHB1ENR |= #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE RCC_AHB1ENR_GPIOAEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE RCC_AHB1ENR_GPIOBEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE RCC_AHB1ENR_GPIOCEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE RCC_AHB1ENR_GPIODEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE RCC_AHB1ENR_GPIOEEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE RCC_AHB1ENR_GPIOFEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE RCC_AHB1ENR_GPIOGEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE RCC_AHB1ENR_GPIOHEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE RCC_AHB1ENR_GPIOIEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE RCC_AHB1ENR_GPIOJEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE RCC_AHB1ENR_GPIOKEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE 0; } } // namespace chip } // namespace distortos <|endoftext|>
<commit_before>#include "Halide.h" #define AUTOTUNE_HOOK(x) #define BASELINE_HOOK(x) using namespace Halide; Var x, y, c; Func haar_x(Func in) { Func out; out(x, y, c) = select(c == 0, (in(2*x, y) + in(2*x+1, y)), (in(2*x, y) - in(2*x+1, y)))/2; out.unroll(c, 2); return out; } Func inverse_haar_x(Func in) { Func out; out(x, y) = select(x%2 == 0, in(x/2, y, 0) + in(x/2, y, 1), in(x/2, y, 0) - in(x/2, y, 1)); out.unroll(x, 2); return out; } const float D0 = 0.4829629131445341f; const float D1 = 0.83651630373780772f; const float D2 = 0.22414386804201339f; const float D3 = -0.12940952255126034f; /* const float D0 = 0.34150635f; const float D1 = 0.59150635f; const float D2 = 0.15849365f; const float D3 = -0.1830127f; */ Func daubechies_x(Func in) { Func out; out(x, y, c) = select(c == 0, D0*in(2*x-1, y) + D1*in(2*x, y) + D2*in(2*x+1, y) + D3*in(2*x+2, y), D3*in(2*x-1, y) - D2*in(2*x, y) + D1*in(2*x+1, y) - D0*in(2*x+2, y)); //out.unroll(c, 2); return out; } Func inverse_daubechies_x(Func in) { Func out; out(x, y) = select(x%2 == 0, D2*in(x/2, y, 0) + D1*in(x/2, y, 1) + D0*in(x/2+1, y, 0) + D3*in(x/2+1, y, 1), D3*in(x/2, y, 0) - D0*in(x/2, y, 1) + D1*in(x/2+1, y, 0) - D2*in(x/2+1, y, 1)); //out.unroll(x, 2); return out; } int main(int argc, char **argv) { ImageParam image(Float(32), 2); ImageParam wavelet(Float(32), 3); // Add a boundary condition for daubechies Func clamped; clamped(x, y) = image(clamp(x, 0, image.width()-1), clamp(y, 0, image.height()-1)); Func wavelet_clamped; wavelet_clamped(x, y, c) = wavelet(clamp(x, 0, wavelet.width()-1), clamp(y, 0, wavelet.height()-1), c); // Func inv_haar_x = inverse_haar_x(wavelet_clamped); // inv_haar_x.compile_to_file("inverse_haar_x", wavelet); // Func for_haar_x = haar_x(clamped); // for_haar_x.compile_to_file("haar_x", image); Func inv_daub_x = inverse_daubechies_x(wavelet_clamped); //inv_daub_x.compile_to_file("inverse_daubechies_x", wavelet); AUTOTUNE_HOOK(inv_daub_x); inv_daub_x.unroll(x, 2).vectorize(x, 8).parallel(y); BASELINE_HOOK(inv_daub_x); // Func for_daub_x = daubechies_x(clamped); //for_daub_x.compile_to_file("daubechies_x", image); return 0; } <commit_msg>halide: Update apps/wavelet for reference-by-name<commit_after>#include "Halide.h" #define AUTOTUNE_HOOK(x) #define BASELINE_HOOK(x) using namespace Halide; Var x("x"), y("y"), c("c"); Func haar_x(Func in) { Func out; out(x, y, c) = select(c == 0, (in(2*x, y) + in(2*x+1, y)), (in(2*x, y) - in(2*x+1, y)))/2; out.unroll(c, 2); return out; } Func inverse_haar_x(Func in) { Func out; out(x, y) = select(x%2 == 0, in(x/2, y, 0) + in(x/2, y, 1), in(x/2, y, 0) - in(x/2, y, 1)); out.unroll(x, 2); return out; } const float D0 = 0.4829629131445341f; const float D1 = 0.83651630373780772f; const float D2 = 0.22414386804201339f; const float D3 = -0.12940952255126034f; /* const float D0 = 0.34150635f; const float D1 = 0.59150635f; const float D2 = 0.15849365f; const float D3 = -0.1830127f; */ Func daubechies_x(Func in) { Func out; out(x, y, c) = select(c == 0, D0*in(2*x-1, y) + D1*in(2*x, y) + D2*in(2*x+1, y) + D3*in(2*x+2, y), D3*in(2*x-1, y) - D2*in(2*x, y) + D1*in(2*x+1, y) - D0*in(2*x+2, y)); //out.unroll(c, 2); return out; } Func inverse_daubechies_x(Func in) { Func out("inv_daub_x"); out(x, y) = select(x%2 == 0, D2*in(x/2, y, 0) + D1*in(x/2, y, 1) + D0*in(x/2+1, y, 0) + D3*in(x/2+1, y, 1), D3*in(x/2, y, 0) - D0*in(x/2, y, 1) + D1*in(x/2+1, y, 0) - D2*in(x/2+1, y, 1)); //out.unroll(x, 2); return out; } int main(int argc, char **argv) { ImageParam image(Float(32), 2); ImageParam wavelet(Float(32), 3); // Add a boundary condition for daubechies Func clamped; clamped(x, y) = image(clamp(x, 0, image.width()-1), clamp(y, 0, image.height()-1)); Func wavelet_clamped("wavelet_clamped"); wavelet_clamped(x, y, c) = wavelet(clamp(x, 0, wavelet.width()-1), clamp(y, 0, wavelet.height()-1), c); // Func inv_haar_x = inverse_haar_x(wavelet_clamped); // inv_haar_x.compile_to_file("inverse_haar_x", wavelet); // Func for_haar_x = haar_x(clamped); // for_haar_x.compile_to_file("haar_x", image); Func inv_daub_x = inverse_daubechies_x(wavelet_clamped); //inv_daub_x.compile_to_file("inverse_daubechies_x", wavelet); AUTOTUNE_HOOK(inv_daub_x); inv_daub_x.unroll(x, 2).vectorize(x, 8).parallel(y); BASELINE_HOOK(inv_daub_x); // Func for_daub_x = daubechies_x(clamped); //for_daub_x.compile_to_file("daubechies_x", image); return 0; } <|endoftext|>
<commit_before>#ifndef slic3r_TransformationMatrix_hpp_ #define slic3r_TransformationMatrix_hpp_ #include "libslic3r.h" #include "Point.hpp" namespace Slic3r { class TransformationMatrix { public: TransformationMatrix(); TransformationMatrix(const std::vector<double> &entries_row_maj); TransformationMatrix( double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34); TransformationMatrix(const TransformationMatrix &other); TransformationMatrix& operator= (TransformationMatrix other); void swap(TransformationMatrix &other); bool operator== (const TransformationMatrix &other) const; bool operator!= (const TransformationMatrix &other) const { return !(*this == other); }; /// matrix entries double m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34; /// return the row-major form of the represented transformation matrix /// for admesh transform std::vector<double> matrix3x4f() const; /// return the determinante of the matrix double determinante() const; /// returns the inverse of the matrix TransformationMatrix inverse() const; /// multiplies the parameter-matrix from the left (this=left*this) void applyLeft(const TransformationMatrix &left); /// multiplies the parameter-matrix from the left (out=left*this) TransformationMatrix multiplyLeft(const TransformationMatrix &left) const; /// multiplies the parameter-matrix from the right (this=this*right) void applyRight(const TransformationMatrix &right); /// multiplies the parameter-matrix from the right (out=this*right) TransformationMatrix multiplyRight(const TransformationMatrix &right) const; /// generates an eye matrix. static TransformationMatrix mat_eye(); /// generates a per axis scaling matrix static TransformationMatrix mat_scale(double x, double y, double z); /// generates an uniform scaling matrix static TransformationMatrix mat_scale(double scale); /// generates a reflection matrix by coordinate axis static TransformationMatrix mat_mirror(const Axis &axis); /// generates a reflection matrix by arbitrary vector static TransformationMatrix mat_mirror(const Vectorf3 &normal); /// generates a translation matrix static TransformationMatrix mat_translation(double x, double y, double z); /// generates a translation matrix static TransformationMatrix mat_translation(const Vectorf3 &vector); /// generates a rotation matrix around coodinate axis static TransformationMatrix mat_rotation(double angle_rad, const Axis &axis); /// generates a rotation matrix around arbitrary axis static TransformationMatrix mat_rotation(double angle_rad, const Vectorf3 &axis); /// generates a rotation matrix defined by unit quaternion q1*i + q2*j + q3*k + q4 static TransformationMatrix mat_rotation(double q1, double q2, double q3, double q4); /// generates a rotation matrix by specifying a vector (origin) that is to be rotated /// to be colinear with another vector (target) static TransformationMatrix mat_rotation(Vectorf3 origin, Vectorf3 target); /// performs a matrix multiplication static TransformationMatrix multiply(const TransformationMatrix &left, const TransformationMatrix &right); }; } #endif <commit_msg>Trafo class description<commit_after>#ifndef slic3r_TransformationMatrix_hpp_ #define slic3r_TransformationMatrix_hpp_ #include "libslic3r.h" #include "Point.hpp" namespace Slic3r { /* The TransformationMatrix class was created to keep track of the transformations applied to the objects from the GUI. Reloading these objects will now preserve their orientation. As usual in engineering vectors are treated as column vectors. Note that if they are treated as row vectors, the order is inversed: (') denotes the transponse and column vectors Column: out' = M1 * M2 * in' Row: out = in * M2' * M1' Every vector gets a 4th component w added, with positions lying in hyperplane w=1 and direction vectors lying in hyperplane w=0 Using this, affine transformations (scaling, rotating, shearing, translating and their combinations) can be represented as 4x4 Matri. The 4th row equals [0 0 0 1] in order to not alter the w component. The other entries are represented by the class properties mij (i-th row [1,2,3], j-th column [1,2,3,4]). The 4th row is not explicitly stored, it is hard coded in the multiply function. Column vectors have to be multiplied from the right side. */ class TransformationMatrix { public: TransformationMatrix(); TransformationMatrix(const std::vector<double> &entries_row_maj); TransformationMatrix( double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34); TransformationMatrix(const TransformationMatrix &other); TransformationMatrix& operator= (TransformationMatrix other); void swap(TransformationMatrix &other); bool operator== (const TransformationMatrix &other) const; bool operator!= (const TransformationMatrix &other) const { return !(*this == other); }; /// matrix entries double m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34; /// return the row-major form of the represented transformation matrix /// for admesh transform std::vector<double> matrix3x4f() const; /// return the determinante of the matrix double determinante() const; /// returns the inverse of the matrix TransformationMatrix inverse() const; /// multiplies the parameter-matrix from the left (this=left*this) void applyLeft(const TransformationMatrix &left); /// multiplies the parameter-matrix from the left (out=left*this) TransformationMatrix multiplyLeft(const TransformationMatrix &left) const; /// multiplies the parameter-matrix from the right (this=this*right) void applyRight(const TransformationMatrix &right); /// multiplies the parameter-matrix from the right (out=this*right) TransformationMatrix multiplyRight(const TransformationMatrix &right) const; /// generates an eye matrix. static TransformationMatrix mat_eye(); /// generates a per axis scaling matrix static TransformationMatrix mat_scale(double x, double y, double z); /// generates an uniform scaling matrix static TransformationMatrix mat_scale(double scale); /// generates a reflection matrix by coordinate axis static TransformationMatrix mat_mirror(const Axis &axis); /// generates a reflection matrix by arbitrary vector static TransformationMatrix mat_mirror(const Vectorf3 &normal); /// generates a translation matrix static TransformationMatrix mat_translation(double x, double y, double z); /// generates a translation matrix static TransformationMatrix mat_translation(const Vectorf3 &vector); /// generates a rotation matrix around coodinate axis static TransformationMatrix mat_rotation(double angle_rad, const Axis &axis); /// generates a rotation matrix around arbitrary axis static TransformationMatrix mat_rotation(double angle_rad, const Vectorf3 &axis); /// generates a rotation matrix defined by unit quaternion q1*i + q2*j + q3*k + q4 static TransformationMatrix mat_rotation(double q1, double q2, double q3, double q4); /// generates a rotation matrix by specifying a vector (origin) that is to be rotated /// to be colinear with another vector (target) static TransformationMatrix mat_rotation(Vectorf3 origin, Vectorf3 target); /// performs a matrix multiplication static TransformationMatrix multiply(const TransformationMatrix &left, const TransformationMatrix &right); }; } #endif <|endoftext|>
<commit_before>#include "splm.h" #include "splm_util.h" #include <ranking-manager/RankQueryProperty.h> #include <ranking-manager/RankDocumentProperty.h> #include <ranking-manager/BM25Ranker.h> #include <ranking-manager/PlmLanguageRanker.h> #include <ranking-manager/ClosestPositionTermProximityMeasure.h> #include <cmath> using namespace std; namespace sf1r { void SPLM::getSmoothedTfDocument( vector<double>& smoothed_tf, int c, const int *sentOffs, const int *collOffs, const map<int, int>& wordmapping, const int *W, int numSentences, double **U, double **S, int dim ) { if (dim > numSentences) dim = numSentences; set<int> chosenIndices; int s_start = 0; for (int i = collOffs[c]; i < collOffs[c + 1]; i++) { map<int, int>::const_iterator it = wordmapping.find(W[i]); if (it == wordmapping.end()) continue; int Ui = it->second; if (chosenIndices.find(Ui) != chosenIndices.end()) continue; chosenIndices.insert(Ui); double val = 0.; for (int j = 0; j < dim; j++) { val += fabs(U[Ui][j] * S[0][j]); } if (i >= sentOffs[s_start+1]) s_start++; smoothed_tf.push_back(val * (sentOffs[s_start + 1] - sentOffs[s_start])); } } void SPLM::getSmoothedTfSentence( vector<double>& smoothed_tf, int s, const int *sentOffs, const map<int, int>& wordmapping, const int *W, int numSentences, double **U, double **S ) { set<int> chosenIndices; for (int i = sentOffs[s]; i < sentOffs[s + 1]; i++) { map<int, int>::const_iterator it = wordmapping.find(W[i]); if (it == wordmapping.end()) continue; int Ui = it->second; if (chosenIndices.find(Ui) != chosenIndices.end()) continue; chosenIndices.insert(Ui); double val = 0.; for (int j = 0; j < numSentences; j++) { val += fabs(U[Ui][j] * S[0][j]); } smoothed_tf.push_back(val * (sentOffs[s + 1] - sentOffs[s])); } } void SPLM::generateSummary( vector<pair<UString, vector<UString> > >& summary_list, const Corpus& corpus, int lengthLimit, SPLM::SPLM_Alg algorithm, // double alpha, double beta, int iter, int topic, int D, int E, float mu, float lambda ) { const TermProximityMeasure* termProximityMeasure = new MinClosestPositionTermProximityMeasure; PlmLanguageRanker plm(termProximityMeasure, mu, lambda); int nWords = corpus.nwords(); int nColls = corpus.ncolls(); const int *sentOffs = corpus.get_sent_offs(); const int *docOffs = corpus.get_doc_offs(); const int *collOffs = corpus.get_coll_offs(); const int *W = corpus.get_word_seq(); int s_start = 0; int s_end = 0; int d_start = 0; int d_end = 0; for (int c = 0 ; c < nColls; ++c) { // Advance s_end and d_end indices while (sentOffs[s_end] < collOffs[c + 1]) ++s_end; while (docOffs[d_end] < collOffs[c + 1]) ++d_end; // Translates original word numbers into numbers in the range (0, # of words in the collection - 1) map<int, int> collWordMap; SPLMUtil::getCollectionWordMapping(collWordMap, collOffs, c, W); bool SMOOTH = true; int docI = d_start; // Current document index int s_start_doc = s_start; // Sentence index marking start of a document int s_end_doc = s_start; // Sentence index marking end of a document set<pair<double, int> > result; // (score, sentence index) pairs int s = s_start; vector<vector<double> > smoothedDocuments; vector<map<int, vector<double> > > smoothedQueries; for(int docIndex = d_start; docIndex < d_end; docIndex++) { while (sentOffs[s_end_doc] < docOffs[docIndex + 1]) ++s_end_doc; int numOfS_doc = s_end_doc - s_start_doc; map<int, vector<double> > smoothedQueryMap; if (s_end_doc == s_start_doc || (int) collWordMap.size() <= numOfS_doc || !SMOOTH) { smoothedDocuments.push_back(vector<double>()); smoothedQueries.push_back(smoothedQueryMap); } else { double **TF_doc = SPLMUtil::getTF(collWordMap, s_start_doc, s_end_doc, sentOffs, W); double **S_doc = mat_alloc(1, numOfS_doc); while (sentOffs[s] < docOffs[docIndex + 1]) s++; vector<double> smoothedDoc; // if SVD switch (algorithm) { case SPLM_SVD: { double **U_doc = mat_alloc(collWordMap.size(), numOfS_doc); double **V_doc = mat_alloc(numOfS_doc, numOfS_doc); mat_svd(TF_doc, collWordMap.size(), numOfS_doc, U_doc, S_doc[0], V_doc); getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, collWordMap, W, numOfS_doc, U_doc, S_doc); mat_free(U_doc); mat_free(V_doc); } break; case SPLM_RI: { double **TF_s = SPLM::generateIndexVectors(TF_doc, collWordMap.size(), (s_end_doc - s_start_doc), D, E); for(int m = 0; m < numOfS_doc; m++) S_doc[0][m] = 1.0; getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, collWordMap, W, numOfS_doc, TF_s, S_doc); mat_free(TF_s); } break; case SPLM_RI_SVD: { double **U_doc = mat_alloc(collWordMap.size(), numOfS_doc); double **V_doc = mat_alloc(numOfS_doc, numOfS_doc); double **TF_s = generateIndexVectors(TF_doc, collWordMap.size(), s_end_doc - s_start_doc, D, E); mat_svd(TF_s, collWordMap.size(), numOfS_doc, U_doc, S_doc[0], V_doc); getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, collWordMap, W, numOfS_doc, U_doc,S_doc); mat_free(U_doc); mat_free(V_doc); mat_free(TF_s); } break; // case SPLM_LDA: // { // set<int> vocabulary = SPLM::getVocabSet(s_end_doc - s_start_doc, collWordMap.size(), TF_doc); // map<int, int> vocabMap; // int vocabIndex = 0; // vector<std::string> vocabVec; // for (set<int>::iterator iter = vocabulary.begin(); iter != vocabulary.end(); ++iter) // { // stringstream ss; // ss << *iter; // vocabVec.push_back(ss.str()); // vocabMap[*iter] = vocabIndex; // vocabIndex++; // } // vector<vector<pair<size_t,size_t> > > matrixVec = getMatrixVec( // s_end_doc - s_start_doc, collWordMap.size(), TF_doc, vocabMap); // BOW *bw = new BOW(); // bw->loadCorpusFileVectors(vocabVec, matrixVec); // LDA *ldaModel = new LDA; // ldaModel->loadCorpus(bw); // ldaModel->inference(iter, alpha, beta, topic); // double **theta, **phi; // ldaModel->exportModel(theta, phi, (size_t) (s_end_doc - s_start_doc), (size_t) collWordMap.size(), (size_t) topic); // double **phi_T = mat_transpose(phi, topic, collWordMap.size()); // for(int m = 0; m < numOfS_doc; m++) // S_doc[0][m] = 1.0; // getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, // collWordMap, W, topic, phi_T, S_doc); // mat_free(phi_T); // } // break; default: break; } smoothedDocuments.push_back(smoothedDoc); mat_free(S_doc); mat_free(TF_doc); } s_start_doc = s_end_doc; } bool activated =false; for (s = s_start ; s < s_end; ++s) { float sentenceScore = 0.; // Construct RankQueryProperty (used for proximity calculation) RankQueryProperty rqp; SPLMUtil::getRankQueryProperty(rqp, sentOffs, s, W, collOffs[c+1] - collOffs[c]); vector<double> query_tf; vector<double> query_tf_doc; if (!activated) { while (sentOffs[s_end_doc] < docOffs[docI + 1]) ++s_end_doc; double **TF_doc = SPLMUtil::getTF(collWordMap, s_start_doc, s_end_doc, sentOffs, W); s_end_doc = s_start; for (int i = 0; i < s_end - s_start; i++) { query_tf_doc.push_back(.01); } activated = true; mat_free(TF_doc); } // Used to only compare occurrences of words that occur in a sentence set<int> uniqueWords; uniqueWords.insert(&W[sentOffs[s]], &W[sentOffs[s + 1]]); map<int,int> sentenceWordMapping; SPLMUtil::getWordMapping(sentenceWordMapping, uniqueWords); // Changing to a new document if (sentOffs[s] > docOffs[docI]) { docI++; while (sentOffs[s_end_doc] < docOffs[docI]) ++s_end_doc; s_start_doc = s; } for (int docIndex = d_start; docIndex < d_end; docIndex++) { RankDocumentProperty rdp; SPLMUtil::getRankDocumentProperty(rdp, nWords, docOffs, docIndex, W, sentenceWordMapping); vector<double> temp; vector<double> smoothedDocument; if (SMOOTH == true) smoothedDocument = smoothedDocuments[docIndex - d_start]; //sentenceScore += plm.getScoreSVD(rqp, rdp, query_tf_doc, temp, smoothedDocument); if (algorithm == SPLM_NONE) sentenceScore += plm.getScore(rqp, rdp); else sentenceScore += plm.getScoreSVD(rqp, rdp, query_tf_doc, temp, smoothedDocument); } if (sentOffs[s + 1] - sentOffs[s] > lengthLimit) result.insert(make_pair(sentenceScore, s)); } summary_list.push_back(make_pair(UString(), vector<UString>())); summary_list.back().first.assign(corpus.get_coll_name(c)); SPLMUtil::selectSentences(summary_list.back().second, corpus, sentOffs, W, result); s_start = s_end; d_start = d_end; } } void SPLM::getVocabSet(set<int>& vocabulary, int row, int col, double **TF) { for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { if (TF[i][j] > 0) { vocabulary.insert(i); break; } } } } double **SPLM::generateIndexVectors(double **TF, int row, int col, int D, int E) { D = col; double value; if (D < E / 2) value = -1; else if (D < E) value = 1; else value = 0; double **indexVec = mat_alloc(col, D); for (int i = 0; i < col; i++) { for (int j = 0; j < D; j++) { indexVec[i][j] = value; } } double **smoothedTF = mat_alloc(row, D); mat_mul(TF, row, col, indexVec, col, D, smoothedTF); mat_free(indexVec); return smoothedTF; } } <commit_msg>rewrite SPLM::generateIndexVectors()<commit_after>#include "splm.h" #include "splm_util.h" #include <ranking-manager/RankQueryProperty.h> #include <ranking-manager/RankDocumentProperty.h> #include <ranking-manager/BM25Ranker.h> #include <ranking-manager/PlmLanguageRanker.h> #include <ranking-manager/ClosestPositionTermProximityMeasure.h> #include <cmath> using namespace std; namespace sf1r { void SPLM::getSmoothedTfDocument( vector<double>& smoothed_tf, int c, const int *sentOffs, const int *collOffs, const map<int, int>& wordmapping, const int *W, int numSentences, double **U, double **S, int dim ) { if (dim > numSentences) dim = numSentences; set<int> chosenIndices; int s_start = 0; for (int i = collOffs[c]; i < collOffs[c + 1]; i++) { map<int, int>::const_iterator it = wordmapping.find(W[i]); if (it == wordmapping.end()) continue; int Ui = it->second; if (chosenIndices.find(Ui) != chosenIndices.end()) continue; chosenIndices.insert(Ui); double val = 0.; for (int j = 0; j < dim; j++) { val += fabs(U[Ui][j] * S[0][j]); } if (i >= sentOffs[s_start+1]) s_start++; smoothed_tf.push_back(val * (sentOffs[s_start + 1] - sentOffs[s_start])); } } void SPLM::getSmoothedTfSentence( vector<double>& smoothed_tf, int s, const int *sentOffs, const map<int, int>& wordmapping, const int *W, int numSentences, double **U, double **S ) { set<int> chosenIndices; for (int i = sentOffs[s]; i < sentOffs[s + 1]; i++) { map<int, int>::const_iterator it = wordmapping.find(W[i]); if (it == wordmapping.end()) continue; int Ui = it->second; if (chosenIndices.find(Ui) != chosenIndices.end()) continue; chosenIndices.insert(Ui); double val = 0.; for (int j = 0; j < numSentences; j++) { val += fabs(U[Ui][j] * S[0][j]); } smoothed_tf.push_back(val * (sentOffs[s + 1] - sentOffs[s])); } } void SPLM::generateSummary( vector<pair<UString, vector<UString> > >& summary_list, const Corpus& corpus, int lengthLimit, SPLM::SPLM_Alg algorithm, // double alpha, double beta, int iter, int topic, int D, int E, float mu, float lambda ) { const TermProximityMeasure* termProximityMeasure = new MinClosestPositionTermProximityMeasure; PlmLanguageRanker plm(termProximityMeasure, mu, lambda); int nWords = corpus.nwords(); int nColls = corpus.ncolls(); const int *sentOffs = corpus.get_sent_offs(); const int *docOffs = corpus.get_doc_offs(); const int *collOffs = corpus.get_coll_offs(); const int *W = corpus.get_word_seq(); int s_start = 0; int s_end = 0; int d_start = 0; int d_end = 0; for (int c = 0 ; c < nColls; ++c) { // Advance s_end and d_end indices while (sentOffs[s_end] < collOffs[c + 1]) ++s_end; while (docOffs[d_end] < collOffs[c + 1]) ++d_end; // Translates original word numbers into numbers in the range (0, # of words in the collection - 1) map<int, int> collWordMap; SPLMUtil::getCollectionWordMapping(collWordMap, collOffs, c, W); bool SMOOTH = true; int docI = d_start; // Current document index int s_start_doc = s_start; // Sentence index marking start of a document int s_end_doc = s_start; // Sentence index marking end of a document set<pair<double, int> > result; // (score, sentence index) pairs int s = s_start; vector<vector<double> > smoothedDocuments; vector<map<int, vector<double> > > smoothedQueries; for(int docIndex = d_start; docIndex < d_end; docIndex++) { while (sentOffs[s_end_doc] < docOffs[docIndex + 1]) ++s_end_doc; int numOfS_doc = s_end_doc - s_start_doc; map<int, vector<double> > smoothedQueryMap; if (s_end_doc == s_start_doc || (int) collWordMap.size() <= numOfS_doc || !SMOOTH) { smoothedDocuments.push_back(vector<double>()); smoothedQueries.push_back(smoothedQueryMap); } else { double **TF_doc = SPLMUtil::getTF(collWordMap, s_start_doc, s_end_doc, sentOffs, W); double **S_doc = mat_alloc(1, numOfS_doc); while (sentOffs[s] < docOffs[docIndex + 1]) s++; vector<double> smoothedDoc; // if SVD switch (algorithm) { case SPLM_SVD: { double **U_doc = mat_alloc(collWordMap.size(), numOfS_doc); double **V_doc = mat_alloc(numOfS_doc, numOfS_doc); mat_svd(TF_doc, collWordMap.size(), numOfS_doc, U_doc, S_doc[0], V_doc); getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, collWordMap, W, numOfS_doc, U_doc, S_doc); mat_free(U_doc); mat_free(V_doc); } break; case SPLM_RI: { double **TF_s = SPLM::generateIndexVectors(TF_doc, collWordMap.size(), (s_end_doc - s_start_doc), D, E); for(int m = 0; m < numOfS_doc; m++) S_doc[0][m] = 1.0; getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, collWordMap, W, numOfS_doc, TF_s, S_doc); mat_free(TF_s); } break; case SPLM_RI_SVD: { double **U_doc = mat_alloc(collWordMap.size(), numOfS_doc); double **V_doc = mat_alloc(numOfS_doc, numOfS_doc); double **TF_s = generateIndexVectors(TF_doc, collWordMap.size(), s_end_doc - s_start_doc, D, E); mat_svd(TF_s, collWordMap.size(), numOfS_doc, U_doc, S_doc[0], V_doc); getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, collWordMap, W, numOfS_doc, U_doc,S_doc); mat_free(U_doc); mat_free(V_doc); mat_free(TF_s); } break; // case SPLM_LDA: // { // set<int> vocabulary = SPLM::getVocabSet(s_end_doc - s_start_doc, collWordMap.size(), TF_doc); // map<int, int> vocabMap; // int vocabIndex = 0; // vector<std::string> vocabVec; // for (set<int>::iterator iter = vocabulary.begin(); iter != vocabulary.end(); ++iter) // { // stringstream ss; // ss << *iter; // vocabVec.push_back(ss.str()); // vocabMap[*iter] = vocabIndex; // vocabIndex++; // } // vector<vector<pair<size_t,size_t> > > matrixVec = getMatrixVec( // s_end_doc - s_start_doc, collWordMap.size(), TF_doc, vocabMap); // BOW *bw = new BOW(); // bw->loadCorpusFileVectors(vocabVec, matrixVec); // LDA *ldaModel = new LDA; // ldaModel->loadCorpus(bw); // ldaModel->inference(iter, alpha, beta, topic); // double **theta, **phi; // ldaModel->exportModel(theta, phi, (size_t) (s_end_doc - s_start_doc), (size_t) collWordMap.size(), (size_t) topic); // double **phi_T = mat_transpose(phi, topic, collWordMap.size()); // for(int m = 0; m < numOfS_doc; m++) // S_doc[0][m] = 1.0; // getSmoothedTfDocument(smoothedDoc, docIndex, sentOffs, docOffs, // collWordMap, W, topic, phi_T, S_doc); // mat_free(phi_T); // } // break; default: break; } smoothedDocuments.push_back(smoothedDoc); mat_free(S_doc); mat_free(TF_doc); } s_start_doc = s_end_doc; } bool activated =false; for (s = s_start ; s < s_end; ++s) { float sentenceScore = 0.; // Construct RankQueryProperty (used for proximity calculation) RankQueryProperty rqp; SPLMUtil::getRankQueryProperty(rqp, sentOffs, s, W, collOffs[c+1] - collOffs[c]); vector<double> query_tf; vector<double> query_tf_doc; if (!activated) { while (sentOffs[s_end_doc] < docOffs[docI + 1]) ++s_end_doc; double **TF_doc = SPLMUtil::getTF(collWordMap, s_start_doc, s_end_doc, sentOffs, W); s_end_doc = s_start; for (int i = 0; i < s_end - s_start; i++) { query_tf_doc.push_back(.01); } activated = true; mat_free(TF_doc); } // Used to only compare occurrences of words that occur in a sentence set<int> uniqueWords; uniqueWords.insert(&W[sentOffs[s]], &W[sentOffs[s + 1]]); map<int,int> sentenceWordMapping; SPLMUtil::getWordMapping(sentenceWordMapping, uniqueWords); // Changing to a new document if (sentOffs[s] > docOffs[docI]) { docI++; while (sentOffs[s_end_doc] < docOffs[docI]) ++s_end_doc; s_start_doc = s; } for (int docIndex = d_start; docIndex < d_end; docIndex++) { RankDocumentProperty rdp; SPLMUtil::getRankDocumentProperty(rdp, nWords, docOffs, docIndex, W, sentenceWordMapping); vector<double> temp; vector<double> smoothedDocument; if (SMOOTH == true) smoothedDocument = smoothedDocuments[docIndex - d_start]; //sentenceScore += plm.getScoreSVD(rqp, rdp, query_tf_doc, temp, smoothedDocument); if (algorithm == SPLM_NONE) sentenceScore += plm.getScore(rqp, rdp); else sentenceScore += plm.getScoreSVD(rqp, rdp, query_tf_doc, temp, smoothedDocument); } if (sentOffs[s + 1] - sentOffs[s] > lengthLimit) result.insert(make_pair(sentenceScore, s)); } summary_list.push_back(make_pair(UString(), vector<UString>())); summary_list.back().first.assign(corpus.get_coll_name(c)); SPLMUtil::selectSentences(summary_list.back().second, corpus, sentOffs, W, result); s_start = s_end; d_start = d_end; } } void SPLM::getVocabSet(set<int>& vocabulary, int row, int col, double **TF) { for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { if (TF[i][j] > 0) { vocabulary.insert(i); break; } } } } double **SPLM::generateIndexVectors(double **TF, int row, int col, int D, int E) { D = col; double **indexVec = mat_alloc(col, D); for (int i = 0; i < col; i++) { for (int j = 0; j < D; j++) { indexVec[i][j] = rand() % 3 - 1; } } double **smoothedTF = mat_alloc(row, D); mat_mul(TF, row, col, indexVec, col, D, smoothedTF); mat_free(indexVec); return smoothedTF; } } <|endoftext|>
<commit_before>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ /* * Copyright (c) 2008 litl, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <config.h> #include <string.h> #include "jsapi-util.h" #include "jsapi-wrapper.h" JSBool gjs_string_to_utf8 (JSContext *context, const JS::Value value, char **utf8_string_p) { JSString *str; gsize len; char *bytes; JS_BeginRequest(context); if (!value.isString()) { gjs_throw(context, "Value is not a string, cannot convert to UTF-8"); JS_EndRequest(context); return false; } str = value.toString(); len = JS_GetStringEncodingLength(context, str); if (len == (gsize)(-1)) { JS_EndRequest(context); return false; } if (utf8_string_p) { bytes = JS_EncodeStringToUTF8(context, str); *utf8_string_p = bytes; } JS_EndRequest(context); return true; } bool gjs_string_from_utf8(JSContext *context, const char *utf8_string, ssize_t n_bytes, JS::MutableHandleValue value_p) { jschar *u16_string; glong u16_string_length; GError *error; /* intentionally using n_bytes even though glib api suggests n_chars; with * n_chars (from g_utf8_strlen()) the result appears truncated */ error = NULL; u16_string = g_utf8_to_utf16(utf8_string, n_bytes, NULL, &u16_string_length, &error); if (!u16_string) { gjs_throw(context, "Failed to convert UTF-8 string to " "JS string: %s", error->message); g_error_free(error); return false; } JS_BeginRequest(context); /* Avoid a copy - assumes that g_malloc == js_malloc == malloc */ JS::RootedString str(context, JS_NewUCString(context, u16_string, u16_string_length)); if (str) value_p.setString(str); JS_EndRequest(context); return str != NULL; } JSBool gjs_string_to_filename(JSContext *context, const JS::Value filename_val, char **filename_string_p) { GError *error; gchar *tmp, *filename_string; /* gjs_string_to_filename verifies that filename_val is a string */ if (!gjs_string_to_utf8(context, filename_val, &tmp)) { /* exception already set */ return false; } error = NULL; filename_string = g_filename_from_utf8(tmp, -1, NULL, NULL, &error); if (!filename_string) { gjs_throw_g_error(context, error); g_free(tmp); return false; } *filename_string_p = filename_string; g_free(tmp); return true; } bool gjs_string_from_filename(JSContext *context, const char *filename_string, ssize_t n_bytes, JS::MutableHandleValue value_p) { gsize written; GError *error; gchar *utf8_string; error = NULL; utf8_string = g_filename_to_utf8(filename_string, n_bytes, NULL, &written, &error); if (error) { gjs_throw(context, "Could not convert UTF-8 string '%s' to a filename: '%s'", filename_string, error->message); g_error_free(error); g_free(utf8_string); return false; } if (!gjs_string_from_utf8(context, utf8_string, written, value_p)) return false; g_free(utf8_string); return true; } /** * gjs_string_get_uint16_data: * @context: js context * @value: a JS::Value * @data_p: address to return allocated data buffer * @len_p: address to return length of data (number of 16-bit integers) * * Get the binary data (as a sequence of 16-bit integers) in the JSString * contained in @value. * Throws a JS exception if value is not a string. * * Returns: false if exception thrown **/ bool gjs_string_get_uint16_data(JSContext *context, JS::Value value, guint16 **data_p, gsize *len_p) { const jschar *js_data; bool retval = false; JS_BeginRequest(context); if (!value.isString()) { gjs_throw(context, "Value is not a string, can't return binary data from it"); goto out; } js_data = JS_GetStringCharsAndLength(context, value.toString(), len_p); if (js_data == NULL) goto out; *data_p = (guint16*) g_memdup(js_data, sizeof(*js_data)*(*len_p)); retval = true; out: JS_EndRequest(context); return retval; } /** * gjs_string_to_ucs4: * @cx: a #JSContext * @value: JS::Value containing a string * @ucs4_string_p: return location for a #gunichar array * @len_p: return location for @ucs4_string_p length * * Returns: true on success, false otherwise in which case a JS error is thrown */ bool gjs_string_to_ucs4(JSContext *cx, JS::HandleValue value, gunichar **ucs4_string_p, size_t *len_p) { if (ucs4_string_p == NULL) return true; if (!value.isString()) { gjs_throw(cx, "Value is not a string, cannot convert to UCS-4"); return false; } JSAutoRequest ar(cx); JS::RootedString str(cx, value.toString()); size_t utf16_len; GError *error = NULL; const jschar *utf16 = JS_GetStringCharsAndLength(cx, str, &utf16_len); if (utf16 == NULL) { gjs_throw(cx, "Failed to get UTF-16 string data"); return false; } if (ucs4_string_p != NULL) { long length; *ucs4_string_p = g_utf16_to_ucs4(utf16, utf16_len, NULL, &length, &error); if (*ucs4_string_p == NULL) { gjs_throw(cx, "Failed to convert UTF-16 string to UCS-4: %s", error->message); g_clear_error(&error); return false; } if (len_p != NULL) *len_p = (size_t) length; } return true; } /** * gjs_string_from_ucs4: * @cx: a #JSContext * @ucs4_string: string of #gunichar * @n_chars: number of characters in @ucs4_string or -1 for zero-terminated * @value_p: JS::Value that will be filled with a string * * Returns: true on success, false otherwise in which case a JS error is thrown */ bool gjs_string_from_ucs4(JSContext *cx, const gunichar *ucs4_string, ssize_t n_chars, JS::MutableHandleValue value_p) { uint16_t *u16_string; long u16_string_length; GError *error = NULL; u16_string = g_ucs4_to_utf16(ucs4_string, n_chars, NULL, &u16_string_length, &error); if (!u16_string) { gjs_throw(cx, "Failed to convert UCS-4 string to UTF-16: %s", error->message); g_error_free(error); return false; } JSAutoRequest ar(cx); /* Avoid a copy - assumes that g_malloc == js_malloc == malloc */ JS::RootedString str(cx, JS_NewUCString(cx, u16_string, u16_string_length)); if (str == NULL) { gjs_throw(cx, "Failed to convert UCS-4 string to UTF-16"); return false; } value_p.setString(str); return true; } /** * gjs_get_string_id: * @context: a #JSContext * @id: a jsid that is an object hash key (could be an int or string) * @name_p place to store ASCII string version of key * * If the id is not a string ID, return false and set *name_p to %NULL. * Otherwise, return true and fill in *name_p with ASCII name of id. * * Returns: true if *name_p is non-%NULL **/ bool gjs_get_string_id (JSContext *context, jsid id, char **name_p) { JS::Value id_val; if (!JS_IdToValue(context, id, &id_val)) return false; if (id_val.isString()) { return gjs_string_to_utf8(context, id_val, name_p); } else { *name_p = NULL; return false; } } /** * gjs_unichar_from_string: * @string: A string * @result: (out): A unicode character * * If successful, @result is assigned the Unicode codepoint * corresponding to the first full character in @string. This * function handles characters outside the BMP. * * If @string is empty, @result will be 0. An exception will * be thrown if @string can not be represented as UTF-8. */ bool gjs_unichar_from_string (JSContext *context, JS::Value value, gunichar *result) { char *utf8_str; if (gjs_string_to_utf8(context, value, &utf8_str)) { *result = g_utf8_get_char(utf8_str); g_free(utf8_str); return true; } return false; } jsid gjs_intern_string_to_id (JSContext *context, const char *string) { JSString *str; jsid id; JS_BeginRequest(context); str = JS_InternString(context, string); id = INTERNED_STRING_TO_JSID(context, str); JS_EndRequest(context); return id; } <commit_msg>jsapi-util-string: Misc mozjs31 changes<commit_after>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ /* * Copyright (c) 2008 litl, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <config.h> #include <string.h> #include "jsapi-util.h" #include "jsapi-wrapper.h" JSBool gjs_string_to_utf8 (JSContext *context, const JS::Value value, char **utf8_string_p) { gsize len; char *bytes; JS_BeginRequest(context); if (!value.isString()) { gjs_throw(context, "Value is not a string, cannot convert to UTF-8"); JS_EndRequest(context); return false; } JS::RootedString str(context, value.toString()); len = JS_GetStringEncodingLength(context, str); if (len == (gsize)(-1)) { JS_EndRequest(context); return false; } if (utf8_string_p) { bytes = JS_EncodeStringToUTF8(context, str); *utf8_string_p = bytes; } JS_EndRequest(context); return true; } bool gjs_string_from_utf8(JSContext *context, const char *utf8_string, ssize_t n_bytes, JS::MutableHandleValue value_p) { jschar *u16_string; glong u16_string_length; GError *error; /* intentionally using n_bytes even though glib api suggests n_chars; with * n_chars (from g_utf8_strlen()) the result appears truncated */ error = NULL; u16_string = g_utf8_to_utf16(utf8_string, n_bytes, NULL, &u16_string_length, &error); if (!u16_string) { gjs_throw(context, "Failed to convert UTF-8 string to " "JS string: %s", error->message); g_error_free(error); return false; } JS_BeginRequest(context); /* Avoid a copy - assumes that g_malloc == js_malloc == malloc */ JS::RootedString str(context, JS_NewUCString(context, u16_string, u16_string_length)); if (str) value_p.setString(str); JS_EndRequest(context); return str != NULL; } JSBool gjs_string_to_filename(JSContext *context, const JS::Value filename_val, char **filename_string_p) { GError *error; gchar *tmp, *filename_string; /* gjs_string_to_filename verifies that filename_val is a string */ if (!gjs_string_to_utf8(context, filename_val, &tmp)) { /* exception already set */ return false; } error = NULL; filename_string = g_filename_from_utf8(tmp, -1, NULL, NULL, &error); if (!filename_string) { gjs_throw_g_error(context, error); g_free(tmp); return false; } *filename_string_p = filename_string; g_free(tmp); return true; } bool gjs_string_from_filename(JSContext *context, const char *filename_string, ssize_t n_bytes, JS::MutableHandleValue value_p) { gsize written; GError *error; gchar *utf8_string; error = NULL; utf8_string = g_filename_to_utf8(filename_string, n_bytes, NULL, &written, &error); if (error) { gjs_throw(context, "Could not convert UTF-8 string '%s' to a filename: '%s'", filename_string, error->message); g_error_free(error); g_free(utf8_string); return false; } if (!gjs_string_from_utf8(context, utf8_string, written, value_p)) return false; g_free(utf8_string); return true; } /** * gjs_string_get_uint16_data: * @context: js context * @value: a JS::Value * @data_p: address to return allocated data buffer * @len_p: address to return length of data (number of 16-bit integers) * * Get the binary data (as a sequence of 16-bit integers) in the JSString * contained in @value. * Throws a JS exception if value is not a string. * * Returns: false if exception thrown **/ bool gjs_string_get_uint16_data(JSContext *context, JS::Value value, guint16 **data_p, gsize *len_p) { const jschar *js_data; bool retval = false; JS_BeginRequest(context); if (!value.isString()) { gjs_throw(context, "Value is not a string, can't return binary data from it"); goto out; } js_data = JS_GetStringCharsAndLength(context, value.toString(), len_p); if (js_data == NULL) goto out; *data_p = (guint16*) g_memdup(js_data, sizeof(*js_data)*(*len_p)); retval = true; out: JS_EndRequest(context); return retval; } /** * gjs_string_to_ucs4: * @cx: a #JSContext * @value: JS::Value containing a string * @ucs4_string_p: return location for a #gunichar array * @len_p: return location for @ucs4_string_p length * * Returns: true on success, false otherwise in which case a JS error is thrown */ bool gjs_string_to_ucs4(JSContext *cx, JS::HandleValue value, gunichar **ucs4_string_p, size_t *len_p) { if (ucs4_string_p == NULL) return true; if (!value.isString()) { gjs_throw(cx, "Value is not a string, cannot convert to UCS-4"); return false; } JSAutoRequest ar(cx); JS::RootedString str(cx, value.toString()); size_t utf16_len; GError *error = NULL; const jschar *utf16 = JS_GetStringCharsAndLength(cx, str, &utf16_len); if (utf16 == NULL) { gjs_throw(cx, "Failed to get UTF-16 string data"); return false; } if (ucs4_string_p != NULL) { long length; *ucs4_string_p = g_utf16_to_ucs4(reinterpret_cast<const gunichar2 *>(utf16), utf16_len, NULL, &length, &error); if (*ucs4_string_p == NULL) { gjs_throw(cx, "Failed to convert UTF-16 string to UCS-4: %s", error->message); g_clear_error(&error); return false; } if (len_p != NULL) *len_p = (size_t) length; } return true; } /** * gjs_string_from_ucs4: * @cx: a #JSContext * @ucs4_string: string of #gunichar * @n_chars: number of characters in @ucs4_string or -1 for zero-terminated * @value_p: JS::Value that will be filled with a string * * Returns: true on success, false otherwise in which case a JS error is thrown */ bool gjs_string_from_ucs4(JSContext *cx, const gunichar *ucs4_string, ssize_t n_chars, JS::MutableHandleValue value_p) { uint16_t *u16_string; long u16_string_length; GError *error = NULL; u16_string = g_ucs4_to_utf16(ucs4_string, n_chars, NULL, &u16_string_length, &error); if (!u16_string) { gjs_throw(cx, "Failed to convert UCS-4 string to UTF-16: %s", error->message); g_error_free(error); return false; } JSAutoRequest ar(cx); /* Avoid a copy - assumes that g_malloc == js_malloc == malloc */ JS::RootedString str(cx, JS_NewUCString(cx, u16_string, u16_string_length)); if (str == NULL) { gjs_throw(cx, "Failed to convert UCS-4 string to UTF-16"); return false; } value_p.setString(str); return true; } /** * gjs_get_string_id: * @context: a #JSContext * @id: a jsid that is an object hash key (could be an int or string) * @name_p place to store ASCII string version of key * * If the id is not a string ID, return false and set *name_p to %NULL. * Otherwise, return true and fill in *name_p with ASCII name of id. * * Returns: true if *name_p is non-%NULL **/ bool gjs_get_string_id (JSContext *context, jsid id, char **name_p) { JS::RootedValue id_val(context); if (!JS_IdToValue(context, id, id_val.address())) return false; if (id_val.isString()) { return gjs_string_to_utf8(context, id_val, name_p); } else { *name_p = NULL; return false; } } /** * gjs_unichar_from_string: * @string: A string * @result: (out): A unicode character * * If successful, @result is assigned the Unicode codepoint * corresponding to the first full character in @string. This * function handles characters outside the BMP. * * If @string is empty, @result will be 0. An exception will * be thrown if @string can not be represented as UTF-8. */ bool gjs_unichar_from_string (JSContext *context, JS::Value value, gunichar *result) { char *utf8_str; if (gjs_string_to_utf8(context, value, &utf8_str)) { *result = g_utf8_get_char(utf8_str); g_free(utf8_str); return true; } return false; } jsid gjs_intern_string_to_id (JSContext *context, const char *string) { JSString *str; jsid id; JS_BeginRequest(context); str = JS_InternString(context, string); id = INTERNED_STRING_TO_JSID(context, str); JS_EndRequest(context); return id; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief input クラス @n 数値、文字列などの入力クラス Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <type_traits> extern "C" { char sci_getch(void); }; namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 標準入力ファンクタ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class def_chainp { const char* str_; char last_; bool unget_; public: def_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { } void unget() { unget_ = true; } char operator() () { if(unget_) { unget_ = false; } else { if(str_ == nullptr) { last_ = sci_getch(); } else { last_ = *str_; if(last_ != 0) { ++str_; } } } return last_; } }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 汎用入力クラス @param[in] INP 入力クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class INP> class basic_input { const char* form_; INP inp_; uint32_t bin_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0 && ch >= '0' && ch <= '1') { a <<= 1; a += ch - '0'; } return a; } uint32_t oct_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0 && ch >= '0' && ch <= '7') { a <<= 3; a += ch - '0'; } return a; } uint32_t dec_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0 && ch >= '0' && ch <= '9') { a *= 10; a += ch - '0'; } return a; } uint32_t hex_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0) { if(ch >= '0' && ch <= '9') { a <<= 4; a += ch - '0'; } else if(ch >= 'A' && ch <= 'F') { a <<= 4; a += ch - 'A' + 10; } else if(ch >= 'a' && ch <= 'f') { a <<= 4; a += ch - 'a' + 10; } else { break; } } return a; } float real_() { uint32_t a = 0; uint32_t b = 0; uint32_t c = 1; char ch; bool p = false; while((ch = inp_()) != 0) { if(ch >= '0' && ch <= '9') { a *= 10; a += ch - '0'; c *= 10; } else if(ch == '.') { b = a; a = 0; c = 1; p = true; } else { break; } } if(p) { return static_cast<float>(b) + static_cast<float>(a) / static_cast<float>(c); } else { return static_cast<float>(a); } } enum class mode : uint8_t { NONE, BIN, OCT, DEC, HEX, FLOAT, }; mode mode_; bool err_; int num_; enum class fmm : uint8_t { none, type, }; void next_() { fmm cm = fmm::none; char ch; while((ch = *form_++) != 0) { switch(cm) { case fmm::none: if(ch == '[') { auto a = inp_(); const char* p = form_; bool ok = false; while((ch = *p++) != 0 && ch != ']') { if(ch == a) ok = true; } form_ = p; if(!ok) { err_ = true; return; } } else if(ch == '%' && *form_ != '%') { cm = fmm::type; } else if(ch != inp_()) { err_ = true; return; } break; case fmm::type: if(ch >= 0x60) ch -= 0x20; if(ch == 'B') { mode_ = mode::BIN; } else if(ch == 'O') { mode_ = mode::OCT; } else if(ch == 'D') { mode_ = mode::DEC; } else if(ch == 'X') { mode_ = mode::HEX; } else if(ch == 'F') { mode_ = mode::FLOAT; } else { err_ = true; } return; } } if(ch == 0 && inp_() == 0) ; else { err_ = true; } } bool neg_() { bool neg = false; auto s = inp_(); if(s == '-') { neg = true; } else if(s == '+') { neg = false; } else inp_.unget(); return neg; } int32_t nb_int_(bool sign = true) { auto neg = neg_(); uint32_t v = 0; switch(mode_) { case mode::BIN: v = bin_(); break; case mode::OCT: v = oct_(); break; case mode::DEC: v = dec_(); break; case mode::HEX: v = hex_(); break; default: err_ = true; break; } if(!err_) { inp_.unget(); next_(); if(!err_) ++num_; } if(sign && neg) return -static_cast<int32_t>(v); else return static_cast<int32_t>(v); } float nb_real_() { bool neg = neg_(); float v = 0.0f; switch(mode_) { case mode::FLOAT: v = real_(); break; default: err_ = true; break; } if(!err_) { inp_.unget(); next_(); if(!err_) ++num_; } if(neg) return -v; else return v; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] form 入力形式 @param[in] inp 変換文字列(nullptrの場合、sci_getch で取得) */ //-----------------------------------------------------------------// basic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp), mode_(mode::NONE), err_(false), num_(0) { next_(); } //-----------------------------------------------------------------// /*! @brief 正常変換数を取得 @return 正常変換数 */ //-----------------------------------------------------------------// int num() const { return num_; } //-----------------------------------------------------------------// /*! @brief テンプレート・オペレーター「%」 @param[in] val 整数型 @return 自分の参照 */ //-----------------------------------------------------------------// template <typename T> basic_input& operator % (T& val) { if(err_) return *this; if(std::is_floating_point<T>::value) { val = nb_real_(); } else { val = nb_int_(std::is_signed<T>::value); } return *this; } //-----------------------------------------------------------------// /*! @brief オペレーター「=」 */ //-----------------------------------------------------------------// basic_input& operator = (const basic_input& in) { return *this; } }; typedef basic_input<def_chainp> input; } <commit_msg>add conversion status<commit_after>#pragma once //=====================================================================// /*! @file @brief input クラス @n 数値、文字列などの入力クラス Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <type_traits> extern "C" { char sci_getch(void); }; namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 標準入力ファンクタ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class def_chainp { const char* str_; char last_; bool unget_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] str 入力文字列(省力された場合「sci_getch」を使う) */ //-----------------------------------------------------------------// def_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { } //-----------------------------------------------------------------// /*! @brief 1文字戻す */ //-----------------------------------------------------------------// void unget() { unget_ = true; } //-----------------------------------------------------------------// /*! @brief ファンクタ(文字取得) @return 文字 */ //-----------------------------------------------------------------// char operator() () { if(unget_) { unget_ = false; } else { if(str_ == nullptr) { last_ = sci_getch(); } else { last_ = *str_; if(last_ != 0) { ++str_; } } } return last_; } }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 汎用入力クラス @param[in] INP 文字入力クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class INP> class basic_input { const char* form_; INP inp_; enum class mode : uint8_t { NONE, BIN, OCT, DEC, HEX, FLOAT, }; mode mode_; bool err_; int num_; uint32_t bin_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0 && ch >= '0' && ch <= '1') { a <<= 1; a += ch - '0'; } return a; } uint32_t oct_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0 && ch >= '0' && ch <= '7') { a <<= 3; a += ch - '0'; } return a; } uint32_t dec_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0 && ch >= '0' && ch <= '9') { a *= 10; a += ch - '0'; } return a; } uint32_t hex_() { uint32_t a = 0; char ch; while((ch = inp_()) != 0) { if(ch >= '0' && ch <= '9') { a <<= 4; a += ch - '0'; } else if(ch >= 'A' && ch <= 'F') { a <<= 4; a += ch - 'A' + 10; } else if(ch >= 'a' && ch <= 'f') { a <<= 4; a += ch - 'a' + 10; } else { break; } } return a; } float real_() { uint32_t a = 0; uint32_t b = 0; uint32_t c = 1; char ch; bool p = false; while((ch = inp_()) != 0) { if(ch >= '0' && ch <= '9') { a *= 10; a += ch - '0'; c *= 10; } else if(ch == '.') { b = a; a = 0; c = 1; p = true; } else { break; } } if(p) { return static_cast<float>(b) + static_cast<float>(a) / static_cast<float>(c); } else { return static_cast<float>(a); } } void next_() { enum class fmm : uint8_t { none, type, }; fmm cm = fmm::none; char ch; while((ch = *form_++) != 0) { switch(cm) { case fmm::none: if(ch == '[') { auto a = inp_(); const char* p = form_; bool ok = false; while((ch = *p++) != 0 && ch != ']') { if(ch == a) ok = true; } form_ = p; if(!ok) { err_ = true; return; } } else if(ch == '%' && *form_ != '%') { cm = fmm::type; } else if(ch != inp_()) { err_ = true; return; } break; case fmm::type: if(ch >= 0x60) ch -= 0x20; if(ch == 'B') { mode_ = mode::BIN; } else if(ch == 'O') { mode_ = mode::OCT; } else if(ch == 'D') { mode_ = mode::DEC; } else if(ch == 'X') { mode_ = mode::HEX; } else if(ch == 'F') { mode_ = mode::FLOAT; } else { err_ = true; } return; } } if(ch == 0 && inp_() == 0) ; else { err_ = true; } } bool neg_() { bool neg = false; auto s = inp_(); if(s == '-') { neg = true; } else if(s == '+') { neg = false; } else inp_.unget(); return neg; } int32_t nb_int_(bool sign = true) { auto neg = neg_(); uint32_t v = 0; switch(mode_) { case mode::BIN: v = bin_(); break; case mode::OCT: v = oct_(); break; case mode::DEC: v = dec_(); break; case mode::HEX: v = hex_(); break; default: err_ = true; break; } if(!err_) { inp_.unget(); next_(); if(!err_) ++num_; } if(sign && neg) return -static_cast<int32_t>(v); else return static_cast<int32_t>(v); } float nb_real_() { bool neg = neg_(); float v = 0.0f; switch(mode_) { case mode::FLOAT: v = real_(); break; default: err_ = true; break; } if(!err_) { inp_.unget(); next_(); if(!err_) ++num_; } if(neg) return -v; else return v; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] form 入力形式 @param[in] inp 変換文字列(nullptrの場合、sci_getch で取得) */ //-----------------------------------------------------------------// basic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp), mode_(mode::NONE), err_(false), num_(0) { next_(); } //-----------------------------------------------------------------// /*! @brief 正常変換数を取得 @return 正常変換数 */ //-----------------------------------------------------------------// int num() const { return num_; } //-----------------------------------------------------------------// /*! @brief 変換ステータスを返す @return 変換が全て正常なら「true」 */ //-----------------------------------------------------------------// bool status() const { return !err_; } //-----------------------------------------------------------------// /*! @brief テンプレート・オペレーター「%」 @param[in] val 整数型 @return 自分の参照 */ //-----------------------------------------------------------------// template <typename T> basic_input& operator % (T& val) { if(err_) return *this; if(std::is_floating_point<T>::value) { val = nb_real_(); } else { val = nb_int_(std::is_signed<T>::value); } return *this; } }; typedef basic_input<def_chainp> input; } <|endoftext|>
<commit_before><commit_msg>Fix baud rate calculation to be dynamic instead of hardcoded. Closes #3<commit_after><|endoftext|>
<commit_before>#include <babylon/mesh/polygonmesh/polygon_mesh_builder.h> #include <babylon/babylon_stl_util.h> #include <babylon/math/path2.h> #include <babylon/math/vector2.h> #include <babylon/mesh/mesh.h> #include <babylon/mesh/polygonmesh/indexed_vector2.h> #include <babylon/mesh/vertex_buffer.h> #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" // conversion from int to char #endif #include <earcut.hpp> #ifdef __GNUC__ #pragma GCC diagnostic pop #endif namespace BABYLON { PolygonMeshBuilder::PolygonMeshBuilder(const std::string& name, const Path2& contours, Scene* scene) : _name{name}, _scene{scene} { std::vector<Vector2> points = contours.getPoints(); _addToepoint(points); _points.add(points); _outlinepoints.add(points); } PolygonMeshBuilder::PolygonMeshBuilder(const std::string& name, const std::vector<Vector2>& contours, Scene* scene) : _name{name}, _scene{scene} { _addToepoint(contours); _points.add(contours); _outlinepoints.add(contours); } PolygonMeshBuilder::~PolygonMeshBuilder() { } void PolygonMeshBuilder::_addToepoint(const std::vector<Vector2>& points) { for (auto& p : points) { Point2D point{{p.x, p.y}}; _epoints.emplace_back(point); } } PolygonMeshBuilder& PolygonMeshBuilder::addHole(const std::vector<Vector2>& hole) { _points.add(hole); PolygonPoints holepoints; holepoints.add(hole); _holes.emplace_back(holepoints); _eholes.emplace_back(_epoints.size()); _addToepoint(hole); return *this; } Mesh* PolygonMeshBuilder::build(bool updatable, float depth) { auto result = Mesh::New(_name, _scene); Float32Array normals; Float32Array positions; Float32Array uvs; auto bounds = _points.computeBounds(); auto& pointElements = _points.elements; for (auto& p : pointElements) { stl_util::concat(normals, {0.f, 1.f, 0.f}); stl_util::concat(positions, {p.x, 0.f, p.y}); stl_util::concat(uvs, {(p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height}); } auto addHoles = [](const std::vector<Point2D>& epoints, const Uint32Array& holeIndices, std::vector<std::vector<Point2D>>& polygon) { // Check if polygon has holes if (holeIndices.empty()) { polygon.emplace_back(epoints); } else { // Determine hole indices using IndexRange = std::array<size_t, 2>; std::vector<IndexRange> holes; for (size_t i = 0, len = holeIndices.size(); i < len; i++) { size_t startIndex = holeIndices[i]; size_t endIndex = i < len - 1 ? holeIndices[i + 1] : epoints.size(); IndexRange range{{startIndex, endIndex}}; holes.emplace_back(range); } // Add outer ring std::vector<Point2D> ring( epoints.begin(), epoints.begin() + static_cast<long>(holes[0][0])); polygon.emplace_back(ring); // Add holes for (auto& holeRange : holes) { std::vector<Point2D> hole( epoints.begin() + static_cast<long>(holeRange[0]), epoints.begin() + static_cast<long>(holeRange[1])); polygon.emplace_back(hole); } } }; std::vector<std::vector<Point2D>> polygon; // Earcut.hpp has no 'holes' argument, adding the holes to the input array addHoles(_epoints, _eholes, polygon); auto res = mapbox::earcut<int32_t>(polygon); Uint32Array indices; for (auto r : res) { indices.emplace_back(r); } if (depth > 0.f) { // get the current pointcount size_t positionscount = (positions.size() / 3); for (auto& p : pointElements) { // add the elements at the depth stl_util::concat(normals, {0.f, -1.f, 0.f}); stl_util::concat(positions, {p.x, -depth, p.y}); stl_util::concat(uvs, {1.f - (p.x - bounds.min.x) / bounds.width, 1.f - (p.y - bounds.min.y) / bounds.height}); } size_t totalCount = indices.size(); for (size_t i = 0; i < totalCount; i += 3) { auto i0 = indices[i + 0]; auto i1 = indices[i + 1]; auto i2 = indices[i + 2]; indices.emplace_back(i2 + positionscount); indices.emplace_back(i1 + positionscount); indices.emplace_back(i0 + positionscount); } // Add the sides addSide(positions, normals, uvs, indices, bounds, _outlinepoints, depth, false); for (auto& hole : _holes) { addSide(positions, normals, uvs, indices, bounds, hole, depth, true); } } result->setVerticesData(VertexBuffer::PositionKind, positions, updatable); result->setVerticesData(VertexBuffer::NormalKind, normals, updatable); result->setVerticesData(VertexBuffer::UVKind, uvs, updatable); result->setIndices(indices); return result; } void PolygonMeshBuilder::addSide(Float32Array& positions, Float32Array& normals, Float32Array& uvs, Uint32Array& indices, const Bounds& bounds, const PolygonPoints& points, float depth, bool flip) { size_t startIndex = positions.size() / 3; float ulength = 0.f; for (size_t i = 0; i < points.elements.size(); ++i) { const auto& p = points.elements[i]; IndexedVector2 p1; if ((i + 1) > points.elements.size() - 1) { p1 = points.elements[0]; } else { p1 = points.elements[i + 1]; } stl_util::concat(positions, {p.x, 0.f, p.y}); stl_util::concat(positions, {p.x, -depth, p.y}); stl_util::concat(positions, {p1.x, 0.f, p1.y}); stl_util::concat(positions, {p1.x, -depth, p1.y}); Vector3 v1(p.x, 0.f, p.y); Vector3 v2(p1.x, 0.f, p1.y); Vector3 v3 = v2.subtract(v1); Vector3 v4(0.f, 1.f, 0.f); Vector3 vn = Vector3::Cross(v3, v4); vn = vn.normalize(); stl_util::concat(uvs, {ulength / bounds.width, 0.f}); stl_util::concat(uvs, {ulength / bounds.width, 1.f}); ulength += v3.length(); stl_util::concat(uvs, {(ulength / bounds.width), 0.f}); stl_util::concat(uvs, {(ulength / bounds.width), 1.f}); if (!flip) { stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); indices.emplace_back(startIndex + 0); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 2); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 3); indices.emplace_back(startIndex + 2); } else { stl_util::concat(normals, {vn.x, vn.y, vn.z}); stl_util::concat(normals, {vn.x, vn.y, vn.z}); stl_util::concat(normals, {vn.x, vn.y, vn.z}); stl_util::concat(normals, {vn.x, vn.y, vn.z}); indices.emplace_back(startIndex + 0); indices.emplace_back(startIndex + 2); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 2); indices.emplace_back(startIndex + 3); } startIndex += 4; } } } // end of namespace BABYLON <commit_msg>Hiding the warning: "Use of GNU statement expression extension".<commit_after>#include <babylon/mesh/polygonmesh/polygon_mesh_builder.h> #include <babylon/babylon_stl_util.h> #include <babylon/math/path2.h> #include <babylon/math/vector2.h> #include <babylon/mesh/mesh.h> #include <babylon/mesh/polygonmesh/indexed_vector2.h> #include <babylon/mesh/vertex_buffer.h> #ifdef __GNUC__ #pragma GCC diagnostic push // Conversion from int to char #pragma GCC diagnostic ignored "-Wconversion" // Use of GNU statement expression extension #pragma GCC diagnostic ignored "-Wgnu" #endif #include <earcut.hpp> #ifdef __GNUC__ #pragma GCC diagnostic pop #endif namespace BABYLON { PolygonMeshBuilder::PolygonMeshBuilder(const std::string& name, const Path2& contours, Scene* scene) : _name{name}, _scene{scene} { std::vector<Vector2> points = contours.getPoints(); _addToepoint(points); _points.add(points); _outlinepoints.add(points); } PolygonMeshBuilder::PolygonMeshBuilder(const std::string& name, const std::vector<Vector2>& contours, Scene* scene) : _name{name}, _scene{scene} { _addToepoint(contours); _points.add(contours); _outlinepoints.add(contours); } PolygonMeshBuilder::~PolygonMeshBuilder() { } void PolygonMeshBuilder::_addToepoint(const std::vector<Vector2>& points) { for (auto& p : points) { Point2D point{{p.x, p.y}}; _epoints.emplace_back(point); } } PolygonMeshBuilder& PolygonMeshBuilder::addHole(const std::vector<Vector2>& hole) { _points.add(hole); PolygonPoints holepoints; holepoints.add(hole); _holes.emplace_back(holepoints); _eholes.emplace_back(_epoints.size()); _addToepoint(hole); return *this; } Mesh* PolygonMeshBuilder::build(bool updatable, float depth) { auto result = Mesh::New(_name, _scene); Float32Array normals; Float32Array positions; Float32Array uvs; auto bounds = _points.computeBounds(); auto& pointElements = _points.elements; for (auto& p : pointElements) { stl_util::concat(normals, {0.f, 1.f, 0.f}); stl_util::concat(positions, {p.x, 0.f, p.y}); stl_util::concat(uvs, {(p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height}); } auto addHoles = [](const std::vector<Point2D>& epoints, const Uint32Array& holeIndices, std::vector<std::vector<Point2D>>& polygon) { // Check if polygon has holes if (holeIndices.empty()) { polygon.emplace_back(epoints); } else { // Determine hole indices using IndexRange = std::array<size_t, 2>; std::vector<IndexRange> holes; for (size_t i = 0, len = holeIndices.size(); i < len; i++) { size_t startIndex = holeIndices[i]; size_t endIndex = i < len - 1 ? holeIndices[i + 1] : epoints.size(); IndexRange range{{startIndex, endIndex}}; holes.emplace_back(range); } // Add outer ring std::vector<Point2D> ring( epoints.begin(), epoints.begin() + static_cast<long>(holes[0][0])); polygon.emplace_back(ring); // Add holes for (auto& holeRange : holes) { std::vector<Point2D> hole( epoints.begin() + static_cast<long>(holeRange[0]), epoints.begin() + static_cast<long>(holeRange[1])); polygon.emplace_back(hole); } } }; std::vector<std::vector<Point2D>> polygon; // Earcut.hpp has no 'holes' argument, adding the holes to the input array addHoles(_epoints, _eholes, polygon); auto res = mapbox::earcut<int32_t>(polygon); Uint32Array indices; for (auto r : res) { indices.emplace_back(r); } if (depth > 0.f) { // get the current pointcount size_t positionscount = (positions.size() / 3); for (auto& p : pointElements) { // add the elements at the depth stl_util::concat(normals, {0.f, -1.f, 0.f}); stl_util::concat(positions, {p.x, -depth, p.y}); stl_util::concat(uvs, {1.f - (p.x - bounds.min.x) / bounds.width, 1.f - (p.y - bounds.min.y) / bounds.height}); } size_t totalCount = indices.size(); for (size_t i = 0; i < totalCount; i += 3) { auto i0 = indices[i + 0]; auto i1 = indices[i + 1]; auto i2 = indices[i + 2]; indices.emplace_back(i2 + positionscount); indices.emplace_back(i1 + positionscount); indices.emplace_back(i0 + positionscount); } // Add the sides addSide(positions, normals, uvs, indices, bounds, _outlinepoints, depth, false); for (auto& hole : _holes) { addSide(positions, normals, uvs, indices, bounds, hole, depth, true); } } result->setVerticesData(VertexBuffer::PositionKind, positions, updatable); result->setVerticesData(VertexBuffer::NormalKind, normals, updatable); result->setVerticesData(VertexBuffer::UVKind, uvs, updatable); result->setIndices(indices); return result; } void PolygonMeshBuilder::addSide(Float32Array& positions, Float32Array& normals, Float32Array& uvs, Uint32Array& indices, const Bounds& bounds, const PolygonPoints& points, float depth, bool flip) { size_t startIndex = positions.size() / 3; float ulength = 0.f; for (size_t i = 0; i < points.elements.size(); ++i) { const auto& p = points.elements[i]; IndexedVector2 p1; if ((i + 1) > points.elements.size() - 1) { p1 = points.elements[0]; } else { p1 = points.elements[i + 1]; } stl_util::concat(positions, {p.x, 0.f, p.y}); stl_util::concat(positions, {p.x, -depth, p.y}); stl_util::concat(positions, {p1.x, 0.f, p1.y}); stl_util::concat(positions, {p1.x, -depth, p1.y}); Vector3 v1(p.x, 0.f, p.y); Vector3 v2(p1.x, 0.f, p1.y); Vector3 v3 = v2.subtract(v1); Vector3 v4(0.f, 1.f, 0.f); Vector3 vn = Vector3::Cross(v3, v4); vn = vn.normalize(); stl_util::concat(uvs, {ulength / bounds.width, 0.f}); stl_util::concat(uvs, {ulength / bounds.width, 1.f}); ulength += v3.length(); stl_util::concat(uvs, {(ulength / bounds.width), 0.f}); stl_util::concat(uvs, {(ulength / bounds.width), 1.f}); if (!flip) { stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); stl_util::concat(normals, {-vn.x, -vn.y, -vn.z}); indices.emplace_back(startIndex + 0); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 2); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 3); indices.emplace_back(startIndex + 2); } else { stl_util::concat(normals, {vn.x, vn.y, vn.z}); stl_util::concat(normals, {vn.x, vn.y, vn.z}); stl_util::concat(normals, {vn.x, vn.y, vn.z}); stl_util::concat(normals, {vn.x, vn.y, vn.z}); indices.emplace_back(startIndex + 0); indices.emplace_back(startIndex + 2); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 1); indices.emplace_back(startIndex + 2); indices.emplace_back(startIndex + 3); } startIndex += 4; } } } // end of namespace BABYLON <|endoftext|>
<commit_before>/* * Copyright (c) 2011 Timo Savola * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. */ #include <cstring> #include <sys/socket.h> #include <netdb.h> #include <concrete/context.hpp> #include <concrete/continuation.hpp> #include <concrete/execution.hpp> #include <concrete/io/buffer.hpp> #include <concrete/io/resolve.hpp> #include <concrete/io/socket.hpp> #include <concrete/objects/dict.hpp> #include <concrete/objects/internal.hpp> #include <concrete/objects/long.hpp> #include <concrete/objects/module.hpp> #include <concrete/objects/tuple.hpp> #include <concrete/portable.hpp> #include <concrete/resource.hpp> #include <concrete/util/noncopyable.hpp> #include <concrete/util/trace.hpp> namespace concrete { class Fork: public Continuation { friend class Pointer; protected: enum { ResolveMode, ConnectMode, WriteMode, }; struct Data: Noncopyable { ~Data() throw () { reset(); } void reset() throw () { resolve.destroy(); socket.destroy(); buffer.destroy(); } bool is_lost() const throw () { return resolve.is_lost() || socket.is_lost() || buffer.is_lost(); } Portable<Object> host; Portable<Object> port; PortableResource<Resolve> resolve; PortableResource<Socket> socket; PortableResource<Buffer> buffer; Portable<uint8_t> mode; Portable<bool> forked; } CONCRETE_PACKED; explicit Fork(unsigned int address) throw (): Continuation(address) { } public: bool initiate(Object &result, const TupleObject &args, const DictObject &kwargs) const { auto address = args.get_item(0).require<TupleObject>(); auto host = address.get_item(0).require<StringObject>(); auto port = address.get_item(1).require<LongObject>().str(); data()->host = host; data()->port = port; initiate_resolve(); return false; } bool resume(Object &result) const { if (data()->forked) return true; if (data()->is_lost()) { data()->reset(); initiate_resolve(); return false; } switch (data()->mode) { case ResolveMode: resume_resolve(); return false; case ConnectMode: resume_connect(); return false; case WriteMode: return resume_write(result); default: throw IntegrityError(address()); } } private: void initiate_resolve() const { Trace("fork: initiate resolve"); auto host = data()->host->cast<StringObject>().string(); auto port = data()->port->cast<StringObject>().string(); data()->resolve.create(host, port); data()->mode = ResolveMode; data()->resolve->suspend_until_resolved(); } void resume_resolve() const { Trace("fork: resume resolve"); auto addrinfo = data()->resolve->addrinfo(); if (addrinfo) initiate_connect(addrinfo); else data()->resolve->suspend_until_resolved(); } void initiate_connect(const struct addrinfo *addrinfo) const { Trace("fork: initiate connect"); int family; socklen_t addrlen = 0; struct sockaddr_storage addr; for (auto i = addrinfo; i; i = i->ai_next) if (i->ai_socktype == SOCK_STREAM) { family = i->ai_family; addrlen = i->ai_addrlen; std::memcpy(&addr, i->ai_addr, addrlen); break; } if (addrlen == 0) throw ResourceError(); data()->socket.create(family, SOCK_STREAM); data()->mode = ConnectMode; data()->socket->suspend_until_connected(reinterpret_cast<struct sockaddr *> (&addr), addrlen); } void resume_connect() const { Trace("fork: resume connect"); if (data()->socket->connected()) initiate_write(); else data()->socket->suspend_until_connected(); } void initiate_write() const { Trace("fork: initiate write"); data()->buffer.create(); data()->mode = WriteMode; auto snapshot = Arena::Active().snapshot(); auto buffer = *data()->buffer; buffer->reset(snapshot.size); data()->forked = true; std::memcpy(buffer->data(), snapshot.base, snapshot.size); data()->forked = false; data()->socket->suspend_until_writable(); } bool resume_write(Object &result) const { Trace("fork: resume write"); auto socket = *data()->socket; auto buffer = *data()->buffer; if (!buffer->write(*socket)) throw ResourceError(); if (buffer->remaining()) { socket->suspend_until_writable(); return false; } else { result = LongObject::New(1); return true; } } Data *data() const { return data_cast<Data>(); } }; } // namespace CONCRETE_INTERNAL_CONTINUATION(ConcreteModule_Fork, Fork) <commit_msg>remove redundant resource destruction<commit_after>/* * Copyright (c) 2011 Timo Savola * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. */ #include <cstring> #include <sys/socket.h> #include <netdb.h> #include <concrete/context.hpp> #include <concrete/continuation.hpp> #include <concrete/execution.hpp> #include <concrete/io/buffer.hpp> #include <concrete/io/resolve.hpp> #include <concrete/io/socket.hpp> #include <concrete/objects/dict.hpp> #include <concrete/objects/internal.hpp> #include <concrete/objects/long.hpp> #include <concrete/objects/module.hpp> #include <concrete/objects/tuple.hpp> #include <concrete/portable.hpp> #include <concrete/resource.hpp> #include <concrete/util/noncopyable.hpp> #include <concrete/util/trace.hpp> namespace concrete { class Fork: public Continuation { friend class Pointer; protected: enum { ResolveMode, ConnectMode, WriteMode, }; struct Data: Noncopyable { void reset() throw () { resolve.destroy(); socket.destroy(); buffer.destroy(); } bool is_lost() const throw () { return resolve.is_lost() || socket.is_lost() || buffer.is_lost(); } Portable<Object> host; Portable<Object> port; PortableResource<Resolve> resolve; PortableResource<Socket> socket; PortableResource<Buffer> buffer; Portable<uint8_t> mode; Portable<bool> forked; } CONCRETE_PACKED; explicit Fork(unsigned int address) throw (): Continuation(address) { } public: bool initiate(Object &result, const TupleObject &args, const DictObject &kwargs) const { auto address = args.get_item(0).require<TupleObject>(); auto host = address.get_item(0).require<StringObject>(); auto port = address.get_item(1).require<LongObject>().str(); data()->host = host; data()->port = port; initiate_resolve(); return false; } bool resume(Object &result) const { if (data()->forked) return true; if (data()->is_lost()) { data()->reset(); initiate_resolve(); return false; } switch (data()->mode) { case ResolveMode: resume_resolve(); return false; case ConnectMode: resume_connect(); return false; case WriteMode: return resume_write(result); default: throw IntegrityError(address()); } } private: void initiate_resolve() const { Trace("fork: initiate resolve"); auto host = data()->host->cast<StringObject>().string(); auto port = data()->port->cast<StringObject>().string(); data()->resolve.create(host, port); data()->mode = ResolveMode; data()->resolve->suspend_until_resolved(); } void resume_resolve() const { Trace("fork: resume resolve"); auto addrinfo = data()->resolve->addrinfo(); if (addrinfo) initiate_connect(addrinfo); else data()->resolve->suspend_until_resolved(); } void initiate_connect(const struct addrinfo *addrinfo) const { Trace("fork: initiate connect"); int family; socklen_t addrlen = 0; struct sockaddr_storage addr; for (auto i = addrinfo; i; i = i->ai_next) if (i->ai_socktype == SOCK_STREAM) { family = i->ai_family; addrlen = i->ai_addrlen; std::memcpy(&addr, i->ai_addr, addrlen); break; } if (addrlen == 0) throw ResourceError(); data()->socket.create(family, SOCK_STREAM); data()->mode = ConnectMode; data()->socket->suspend_until_connected(reinterpret_cast<struct sockaddr *> (&addr), addrlen); } void resume_connect() const { Trace("fork: resume connect"); if (data()->socket->connected()) initiate_write(); else data()->socket->suspend_until_connected(); } void initiate_write() const { Trace("fork: initiate write"); data()->buffer.create(); data()->mode = WriteMode; auto snapshot = Arena::Active().snapshot(); auto buffer = *data()->buffer; buffer->reset(snapshot.size); data()->forked = true; std::memcpy(buffer->data(), snapshot.base, snapshot.size); data()->forked = false; data()->socket->suspend_until_writable(); } bool resume_write(Object &result) const { Trace("fork: resume write"); auto socket = *data()->socket; auto buffer = *data()->buffer; if (!buffer->write(*socket)) throw ResourceError(); if (buffer->remaining()) { socket->suspend_until_writable(); return false; } else { result = LongObject::New(1); return true; } } Data *data() const { return data_cast<Data>(); } }; } // namespace CONCRETE_INTERNAL_CONTINUATION(ConcreteModule_Fork, Fork) <|endoftext|>
<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // Copyright 2016 [bk]door.maus #ifndef LIBGLURG_COMMON_FILE_STREAM_HPP #define LIBGLURG_COMMON_FILE_STREAM_HPP #include <cstddef> #include <cstdint> namespace glurg { class FileStream { public: virtual ~FileStream() = default; virtual std::size_t write(const std::uint8_t* data, std::size_t length) = 0; virtual std::size_t read(std::uint8_t* data, std::size_t length) = 0; virtual std::size_t get_position() = 0; virtual void set_position(std::size_t position); virtual bool get_is_end_of_file() const = 0; }; } #endif <commit_msg>Added mode enumeration to glurg::FileStream.<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // Copyright 2016 [bk]door.maus #ifndef LIBGLURG_COMMON_FILE_STREAM_HPP #define LIBGLURG_COMMON_FILE_STREAM_HPP #include <cstddef> #include <cstdint> namespace glurg { class FileStream { public: enum { mode_read = 0x1, mode_write = 0x2, mode_read_write = mode_read | mode_write }; virtual ~FileStream() = default; virtual std::size_t write(const std::uint8_t* data, std::size_t length) = 0; virtual std::size_t read(std::uint8_t* data, std::size_t length) = 0; virtual std::size_t get_position() = 0; virtual void set_position(std::size_t position); virtual bool get_is_end_of_file() const = 0; }; } #endif <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosio/chain/contracts/abi_serializer.hpp> #include <eosio/chain/contracts/types.hpp> #include <eosio/chain/authority.hpp> #include <eosio/chain/chain_config.hpp> #include <eosio/chain/transaction.hpp> #include <fc/io/raw.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/multiprecision/cpp_int.hpp> using namespace boost; namespace eosio { namespace chain { namespace contracts { using boost::algorithm::ends_with; using std::string; template <typename T> inline fc::variant variant_from_stream(fc::datastream<const char*>& stream) { T temp; fc::raw::unpack( stream, temp ); return fc::variant(temp); } template <typename T> auto pack_unpack() { return std::make_pair<abi_serializer::unpack_function, abi_serializer::pack_function>( []( fc::datastream<const char*>& stream, bool is_array) -> fc::variant { if( is_array ) return variant_from_stream<vector<T>>(stream); return variant_from_stream<T>(stream); }, []( const fc::variant& var, fc::datastream<char*>& ds, bool is_array ){ if( is_array ) fc::raw::pack( ds, var.as<vector<T>>() ); else fc::raw::pack( ds, var.as<T>()); } ); } abi_serializer::abi_serializer( const abi_def& abi ) { configure_built_in_types(); set_abi(abi); } void abi_serializer::configure_built_in_types() { //public_key.hpp built_in_types.emplace("public_key", pack_unpack<public_key_type>()); //asset.hpp built_in_types.emplace("asset", pack_unpack<asset>()); built_in_types.emplace("price", pack_unpack<price>()); //native.hpp built_in_types.emplace("string", pack_unpack<string>()); built_in_types.emplace("time", pack_unpack<fc::time_point_sec>()); built_in_types.emplace("signature", pack_unpack<signature_type>()); built_in_types.emplace("checksum", pack_unpack<checksum_type>()); built_in_types.emplace("field_name", pack_unpack<field_name>()); built_in_types.emplace("fixed_string32", pack_unpack<fixed_string32>()); built_in_types.emplace("fixed_string16", pack_unpack<fixed_string16>()); built_in_types.emplace("type_name", pack_unpack<type_name>()); built_in_types.emplace("bytes", pack_unpack<bytes>()); built_in_types.emplace("uint8", pack_unpack<uint8>()); built_in_types.emplace("uint16", pack_unpack<uint16>()); built_in_types.emplace("uint32", pack_unpack<uint32>()); built_in_types.emplace("uint64", pack_unpack<uint64>()); built_in_types.emplace("uint128", pack_unpack<boost::multiprecision::uint128_t>()); built_in_types.emplace("uint256", pack_unpack<boost::multiprecision::uint256_t>()); built_in_types.emplace("int8", pack_unpack<int8_t>()); built_in_types.emplace("int16", pack_unpack<int16_t>()); built_in_types.emplace("int32", pack_unpack<int32_t>()); built_in_types.emplace("int64", pack_unpack<int64_t>()); built_in_types.emplace("name", pack_unpack<name>()); built_in_types.emplace("field", pack_unpack<field_def>()); built_in_types.emplace("struct_def", pack_unpack<struct_def>()); built_in_types.emplace("fields", pack_unpack<vector<field_def>>()); built_in_types.emplace("account_name", pack_unpack<account_name>()); built_in_types.emplace("permission_name", pack_unpack<permission_name>()); built_in_types.emplace("action_name", pack_unpack<action_name>()); built_in_types.emplace("scope_name", pack_unpack<scope_name>()); built_in_types.emplace("permission_level", pack_unpack<permission_level>()); built_in_types.emplace("action", pack_unpack<action>()); built_in_types.emplace("permission_level_weight", pack_unpack<permission_level_weight>()); built_in_types.emplace("transaction", pack_unpack<transaction>()); built_in_types.emplace("signed_transaction", pack_unpack<signed_transaction>()); built_in_types.emplace("key_weight", pack_unpack<key_weight>()); built_in_types.emplace("authority", pack_unpack<authority>()); built_in_types.emplace("chain_config", pack_unpack<chain_config>()); built_in_types.emplace("type_def", pack_unpack<type_def>()); built_in_types.emplace("action", pack_unpack<action_def>()); built_in_types.emplace("table", pack_unpack<table_def>()); built_in_types.emplace("abi", pack_unpack<abi_def>()); built_in_types.emplace("nonce", pack_unpack<nonce>()); } void abi_serializer::set_abi(const abi_def& abi) { typedefs.clear(); structs.clear(); actions.clear(); tables.clear(); for( const auto& st : abi.structs ) structs[st.name] = st; for( const auto& td : abi.types ) { FC_ASSERT(is_type(td.type), "invalid type", ("type",td.type)); typedefs[td.new_type_name] = td.type; } for( const auto& a : abi.actions ) actions[a.name] = a.type; for( const auto& t : abi.tables ) tables[t.name] = t.type; /** * The ABI vector may contain duplicates which would make it * an invalid ABI */ FC_ASSERT( typedefs.size() == abi.types.size() ); FC_ASSERT( structs.size() == abi.structs.size() ); FC_ASSERT( actions.size() == abi.actions.size() ); FC_ASSERT( tables.size() == abi.tables.size() ); } bool abi_serializer::is_builtin_type(const type_name& type)const { return built_in_types.find(type) != built_in_types.end(); } bool abi_serializer::is_integer(const type_name& type) const { string stype = type; return boost::starts_with(stype, "uint") || boost::starts_with(stype, "int"); } int abi_serializer::get_integer_size(const type_name& type) const { string stype = type; FC_ASSERT( is_integer(type), "${stype} is not an integer type", ("stype",stype)); if( boost::starts_with(stype, "uint") ) { return boost::lexical_cast<int>(stype.substr(4)); } else { return boost::lexical_cast<int>(stype.substr(3)); } } bool abi_serializer::is_struct(const type_name& type)const { return structs.find(resolve_type(type)) != structs.end(); } bool abi_serializer::is_array(const type_name& type)const { return ends_with(string(type), "[]"); } type_name abi_serializer::array_type(const type_name& type)const { if( !is_array(type) ) return type; return type_name(string(type).substr(0, type.size()-2)); } bool abi_serializer::is_type(const type_name& rtype)const { auto type = array_type(rtype); if( built_in_types.find(type) != built_in_types.end() ) return true; if( typedefs.find(type) != typedefs.end() ) return is_type(typedefs.find(type)->second); if( structs.find(type) != structs.end() ) return true; return false; } const struct_def& abi_serializer::get_struct(const type_name& type)const { auto itr = structs.find(resolve_type(type) ); FC_ASSERT( itr != structs.end(), "Unknown struct ${type}", ("type",type) ); return itr->second; } void abi_serializer::validate()const { for( const auto& t : typedefs ) { try { vector<type_name> types_seen{t.first, t.second}; auto itr = typedefs.find(t.second); while( itr != typedefs.end() ) { FC_ASSERT( find(types_seen.begin(), types_seen.end(), itr->second) == types_seen.end(), "Circular reference in type ${type}", ("type",t.first) ); types_seen.emplace_back(itr->second); itr = typedefs.find(itr->second); } } FC_CAPTURE_AND_RETHROW( (t) ) } for( const auto& t : typedefs ) { try { FC_ASSERT(is_type(t.second), "", ("type",t.second) ); } FC_CAPTURE_AND_RETHROW( (t) ) } for( const auto& s : structs ) { try { if( s.second.base != type_name() ) { struct_def current = s.second; vector<type_name> types_seen{current.name}; while( current.base != type_name() ) { const auto& base = get_struct(current.base); //<-- force struct to inherit from another struct FC_ASSERT( find(types_seen.begin(), types_seen.end(), base.name) == types_seen.end(), "Circular reference in struct ${type}", ("type",s.second.name) ); types_seen.emplace_back(base.name); current = base; } } for( const auto& field : s.second.fields ) { try { FC_ASSERT(is_type(field.type) ); } FC_CAPTURE_AND_RETHROW( (field) ) } } FC_CAPTURE_AND_RETHROW( (s) ) } for( const auto& a : actions ) { try { FC_ASSERT(is_type(a.second), "", ("type",a.second) ); } FC_CAPTURE_AND_RETHROW( (a) ) } for( const auto& t : tables ) { try { FC_ASSERT(is_type(t.second), "", ("type",t.second) ); } FC_CAPTURE_AND_RETHROW( (t) ) } } type_name abi_serializer::resolve_type(const type_name& type)const { auto itr = typedefs.find(type); if( itr != typedefs.end() ) return resolve_type(itr->second); return type; } void abi_serializer::binary_to_variant(const type_name& type, fc::datastream<const char *>& stream, fc::mutable_variant_object& obj)const { const auto& st = get_struct(type); if( st.base != type_name() ) { binary_to_variant(resolve_type(st.base), stream, obj); } for( const auto& field : st.fields ) { obj( field.name, binary_to_variant(resolve_type(field.type), stream) ); } } fc::variant abi_serializer::binary_to_variant(const type_name& type, fc::datastream<const char *>& stream)const { type_name rtype = resolve_type(type); auto btype = built_in_types.find(array_type(rtype) ); if( btype != built_in_types.end() ) { return btype->second.first(stream, is_array(rtype)); } if ( is_array(rtype) ) { unsigned int size; fc::raw::unpack(stream, size); vector<fc::variant> vars; vars.resize(size); for (auto& var : vars) { var = binary_to_variant(array_type(rtype), stream); } return fc::variant( std::move(vars) ); } fc::mutable_variant_object mvo; binary_to_variant(rtype, stream, mvo); return fc::variant( std::move(mvo) ); } fc::variant abi_serializer::binary_to_variant(const type_name& type, const bytes& binary)const{ fc::datastream<const char*> ds( binary.data(), binary.size() ); return binary_to_variant(type, ds); } void abi_serializer::variant_to_binary(const type_name& type, const fc::variant& var, fc::datastream<char *>& ds)const { try { auto rtype = resolve_type(type); auto btype = built_in_types.find(array_type(rtype)); if( btype != built_in_types.end() ) { btype->second.second(var, ds, is_array(rtype)); } else if ( is_array(rtype) ) { vector<fc::variant> vars = var.get_array(); fc::raw::pack(ds, (unsigned int)vars.size()); for (const auto& var : vars) { variant_to_binary(array_type(rtype), var, ds); } } else { const auto& st = get_struct(rtype); const auto& vo = var.get_object(); if( st.base != type_name() ) { variant_to_binary(resolve_type(st.base), var, ds); } for( const auto& field : st.fields ) { if( vo.contains( string(field.name).c_str() ) ) { variant_to_binary(field.type, vo[field.name], ds); } else { /// TODO: default construct field and write it out FC_ASSERT( !"missing field in variant object", "Missing '${f}' in variant object", ("f",field.name) ); } } } } FC_CAPTURE_AND_RETHROW( (type)(var) ) } bytes abi_serializer::variant_to_binary(const type_name& type, const fc::variant& var)const { if( !is_type(type) ) { return var.as<bytes>(); } bytes temp( 1024*1024 ); fc::datastream<char*> ds(temp.data(), temp.size() ); variant_to_binary(type, var, ds); temp.resize(ds.tellp()); return temp; } type_name abi_serializer::get_action_type(name action)const { auto itr = actions.find(action); if( itr != actions.end() ) return itr->second; return type_name(); } type_name abi_serializer::get_table_type(name action)const { auto itr = tables.find(action); if( itr != tables.end() ) return itr->second; return type_name(); } } } } <commit_msg>Fix bug caused by packing unsigned int instead of unsigned_int as size<commit_after>/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosio/chain/contracts/abi_serializer.hpp> #include <eosio/chain/contracts/types.hpp> #include <eosio/chain/authority.hpp> #include <eosio/chain/chain_config.hpp> #include <eosio/chain/transaction.hpp> #include <fc/io/raw.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <fc/io/varint.hpp> using namespace boost; namespace eosio { namespace chain { namespace contracts { using boost::algorithm::ends_with; using std::string; template <typename T> inline fc::variant variant_from_stream(fc::datastream<const char*>& stream) { T temp; fc::raw::unpack( stream, temp ); return fc::variant(temp); } template <typename T> auto pack_unpack() { return std::make_pair<abi_serializer::unpack_function, abi_serializer::pack_function>( []( fc::datastream<const char*>& stream, bool is_array) -> fc::variant { if( is_array ) return variant_from_stream<vector<T>>(stream); return variant_from_stream<T>(stream); }, []( const fc::variant& var, fc::datastream<char*>& ds, bool is_array ){ if( is_array ) fc::raw::pack( ds, var.as<vector<T>>() ); else fc::raw::pack( ds, var.as<T>()); } ); } abi_serializer::abi_serializer( const abi_def& abi ) { configure_built_in_types(); set_abi(abi); } void abi_serializer::configure_built_in_types() { //public_key.hpp built_in_types.emplace("public_key", pack_unpack<public_key_type>()); //asset.hpp built_in_types.emplace("asset", pack_unpack<asset>()); built_in_types.emplace("price", pack_unpack<price>()); //native.hpp built_in_types.emplace("string", pack_unpack<string>()); built_in_types.emplace("time", pack_unpack<fc::time_point_sec>()); built_in_types.emplace("signature", pack_unpack<signature_type>()); built_in_types.emplace("checksum", pack_unpack<checksum_type>()); built_in_types.emplace("field_name", pack_unpack<field_name>()); built_in_types.emplace("fixed_string32", pack_unpack<fixed_string32>()); built_in_types.emplace("fixed_string16", pack_unpack<fixed_string16>()); built_in_types.emplace("type_name", pack_unpack<type_name>()); built_in_types.emplace("bytes", pack_unpack<bytes>()); built_in_types.emplace("uint8", pack_unpack<uint8>()); built_in_types.emplace("uint16", pack_unpack<uint16>()); built_in_types.emplace("uint32", pack_unpack<uint32>()); built_in_types.emplace("uint64", pack_unpack<uint64>()); built_in_types.emplace("uint128", pack_unpack<boost::multiprecision::uint128_t>()); built_in_types.emplace("uint256", pack_unpack<boost::multiprecision::uint256_t>()); built_in_types.emplace("int8", pack_unpack<int8_t>()); built_in_types.emplace("int16", pack_unpack<int16_t>()); built_in_types.emplace("int32", pack_unpack<int32_t>()); built_in_types.emplace("int64", pack_unpack<int64_t>()); built_in_types.emplace("name", pack_unpack<name>()); built_in_types.emplace("field", pack_unpack<field_def>()); built_in_types.emplace("struct_def", pack_unpack<struct_def>()); built_in_types.emplace("fields", pack_unpack<vector<field_def>>()); built_in_types.emplace("account_name", pack_unpack<account_name>()); built_in_types.emplace("permission_name", pack_unpack<permission_name>()); built_in_types.emplace("action_name", pack_unpack<action_name>()); built_in_types.emplace("scope_name", pack_unpack<scope_name>()); built_in_types.emplace("permission_level", pack_unpack<permission_level>()); built_in_types.emplace("action", pack_unpack<action>()); built_in_types.emplace("permission_level_weight", pack_unpack<permission_level_weight>()); built_in_types.emplace("transaction", pack_unpack<transaction>()); built_in_types.emplace("signed_transaction", pack_unpack<signed_transaction>()); built_in_types.emplace("key_weight", pack_unpack<key_weight>()); built_in_types.emplace("authority", pack_unpack<authority>()); built_in_types.emplace("chain_config", pack_unpack<chain_config>()); built_in_types.emplace("type_def", pack_unpack<type_def>()); built_in_types.emplace("action", pack_unpack<action_def>()); built_in_types.emplace("table", pack_unpack<table_def>()); built_in_types.emplace("abi", pack_unpack<abi_def>()); built_in_types.emplace("nonce", pack_unpack<nonce>()); } void abi_serializer::set_abi(const abi_def& abi) { typedefs.clear(); structs.clear(); actions.clear(); tables.clear(); for( const auto& st : abi.structs ) structs[st.name] = st; for( const auto& td : abi.types ) { FC_ASSERT(is_type(td.type), "invalid type", ("type",td.type)); typedefs[td.new_type_name] = td.type; } for( const auto& a : abi.actions ) actions[a.name] = a.type; for( const auto& t : abi.tables ) tables[t.name] = t.type; /** * The ABI vector may contain duplicates which would make it * an invalid ABI */ FC_ASSERT( typedefs.size() == abi.types.size() ); FC_ASSERT( structs.size() == abi.structs.size() ); FC_ASSERT( actions.size() == abi.actions.size() ); FC_ASSERT( tables.size() == abi.tables.size() ); } bool abi_serializer::is_builtin_type(const type_name& type)const { return built_in_types.find(type) != built_in_types.end(); } bool abi_serializer::is_integer(const type_name& type) const { string stype = type; return boost::starts_with(stype, "uint") || boost::starts_with(stype, "int"); } int abi_serializer::get_integer_size(const type_name& type) const { string stype = type; FC_ASSERT( is_integer(type), "${stype} is not an integer type", ("stype",stype)); if( boost::starts_with(stype, "uint") ) { return boost::lexical_cast<int>(stype.substr(4)); } else { return boost::lexical_cast<int>(stype.substr(3)); } } bool abi_serializer::is_struct(const type_name& type)const { return structs.find(resolve_type(type)) != structs.end(); } bool abi_serializer::is_array(const type_name& type)const { return ends_with(string(type), "[]"); } type_name abi_serializer::array_type(const type_name& type)const { if( !is_array(type) ) return type; return type_name(string(type).substr(0, type.size()-2)); } bool abi_serializer::is_type(const type_name& rtype)const { auto type = array_type(rtype); if( built_in_types.find(type) != built_in_types.end() ) return true; if( typedefs.find(type) != typedefs.end() ) return is_type(typedefs.find(type)->second); if( structs.find(type) != structs.end() ) return true; return false; } const struct_def& abi_serializer::get_struct(const type_name& type)const { auto itr = structs.find(resolve_type(type) ); FC_ASSERT( itr != structs.end(), "Unknown struct ${type}", ("type",type) ); return itr->second; } void abi_serializer::validate()const { for( const auto& t : typedefs ) { try { vector<type_name> types_seen{t.first, t.second}; auto itr = typedefs.find(t.second); while( itr != typedefs.end() ) { FC_ASSERT( find(types_seen.begin(), types_seen.end(), itr->second) == types_seen.end(), "Circular reference in type ${type}", ("type",t.first) ); types_seen.emplace_back(itr->second); itr = typedefs.find(itr->second); } } FC_CAPTURE_AND_RETHROW( (t) ) } for( const auto& t : typedefs ) { try { FC_ASSERT(is_type(t.second), "", ("type",t.second) ); } FC_CAPTURE_AND_RETHROW( (t) ) } for( const auto& s : structs ) { try { if( s.second.base != type_name() ) { struct_def current = s.second; vector<type_name> types_seen{current.name}; while( current.base != type_name() ) { const auto& base = get_struct(current.base); //<-- force struct to inherit from another struct FC_ASSERT( find(types_seen.begin(), types_seen.end(), base.name) == types_seen.end(), "Circular reference in struct ${type}", ("type",s.second.name) ); types_seen.emplace_back(base.name); current = base; } } for( const auto& field : s.second.fields ) { try { FC_ASSERT(is_type(field.type) ); } FC_CAPTURE_AND_RETHROW( (field) ) } } FC_CAPTURE_AND_RETHROW( (s) ) } for( const auto& a : actions ) { try { FC_ASSERT(is_type(a.second), "", ("type",a.second) ); } FC_CAPTURE_AND_RETHROW( (a) ) } for( const auto& t : tables ) { try { FC_ASSERT(is_type(t.second), "", ("type",t.second) ); } FC_CAPTURE_AND_RETHROW( (t) ) } } type_name abi_serializer::resolve_type(const type_name& type)const { auto itr = typedefs.find(type); if( itr != typedefs.end() ) return resolve_type(itr->second); return type; } void abi_serializer::binary_to_variant(const type_name& type, fc::datastream<const char *>& stream, fc::mutable_variant_object& obj)const { const auto& st = get_struct(type); if( st.base != type_name() ) { binary_to_variant(resolve_type(st.base), stream, obj); } for( const auto& field : st.fields ) { obj( field.name, binary_to_variant(resolve_type(field.type), stream) ); } } fc::variant abi_serializer::binary_to_variant(const type_name& type, fc::datastream<const char *>& stream)const { type_name rtype = resolve_type(type); auto btype = built_in_types.find(array_type(rtype) ); if( btype != built_in_types.end() ) { return btype->second.first(stream, is_array(rtype)); } if ( is_array(rtype) ) { fc::unsigned_int size; fc::raw::unpack(stream, size); vector<fc::variant> vars; vars.resize(size); for (auto& var : vars) { var = binary_to_variant(array_type(rtype), stream); } return fc::variant( std::move(vars) ); } fc::mutable_variant_object mvo; binary_to_variant(rtype, stream, mvo); return fc::variant( std::move(mvo) ); } fc::variant abi_serializer::binary_to_variant(const type_name& type, const bytes& binary)const{ fc::datastream<const char*> ds( binary.data(), binary.size() ); return binary_to_variant(type, ds); } void abi_serializer::variant_to_binary(const type_name& type, const fc::variant& var, fc::datastream<char *>& ds)const { try { auto rtype = resolve_type(type); auto btype = built_in_types.find(array_type(rtype)); if( btype != built_in_types.end() ) { btype->second.second(var, ds, is_array(rtype)); } else if ( is_array(rtype) ) { vector<fc::variant> vars = var.get_array(); fc::raw::pack(ds, (fc::unsigned_int)vars.size()); for (const auto& var : vars) { variant_to_binary(array_type(rtype), var, ds); } } else { const auto& st = get_struct(rtype); const auto& vo = var.get_object(); if( st.base != type_name() ) { variant_to_binary(resolve_type(st.base), var, ds); } for( const auto& field : st.fields ) { if( vo.contains( string(field.name).c_str() ) ) { variant_to_binary(field.type, vo[field.name], ds); } else { /// TODO: default construct field and write it out FC_ASSERT( !"missing field in variant object", "Missing '${f}' in variant object", ("f",field.name) ); } } } } FC_CAPTURE_AND_RETHROW( (type)(var) ) } bytes abi_serializer::variant_to_binary(const type_name& type, const fc::variant& var)const { if( !is_type(type) ) { return var.as<bytes>(); } bytes temp( 1024*1024 ); fc::datastream<char*> ds(temp.data(), temp.size() ); variant_to_binary(type, var, ds); temp.resize(ds.tellp()); return temp; } type_name abi_serializer::get_action_type(name action)const { auto itr = actions.find(action); if( itr != actions.end() ) return itr->second; return type_name(); } type_name abi_serializer::get_table_type(name action)const { auto itr = tables.find(action); if( itr != tables.end() ) return itr->second; return type_name(); } } } } <|endoftext|>
<commit_before>#include "mainboard.h" #include <QApplication> #include "menu.h" #include "chesslogic.h" #include "QDebug" int main(int argc, char *argv[]) { QApplication a(argc, argv); //MainBoard w; //w.show(); ChessLogic cl(1); int** arr = cl.GetBoard(); for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { qDebug() << arr[i][j]; } } Menu m; m.show(); return a.exec(); } <commit_msg>Calling new functions<commit_after>#include "mainboard.h" #include <QApplication> #include "menu.h" #include "chesslogic.h" #include "QDebug" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainBoard w; w.initializeBoard(); //initializing the QLabel & QPushButton objects w.initializeFigures();//initializing QIcons (figures) w.createBoard(); //creating the board and the QpushButtons on top of the board w.createFigures(); w.disableButtons();//disabling unsued buttons at newgame w.show(); /*other menus, new game options etc... ChessLogic cl(1); int** arr = cl.GetBoard(); for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { qDebug() << arr[i][j]; } } Menu m; m.show();*/ return a.exec(); } <|endoftext|>
<commit_before>#include "../../include/server0/listFiles.hpp" bool listFiles(Client& client){ //checking allowance and sending what's up about this DIR* directory = opendir(client.path.c_str()); struct dirent* redfile = NULL; client.packet.clear(); if( directory == NULL ){ client.packet << VoidDirectory; client.socket.send( client.packet ); std::cout << client.name() << " -> Could not open the directory" << std::endl; return false; }//else client.packet << ServerReady; client.socket.send( client.packet ); client.packet.clear(); std::cout << client.name() << " -> Server ready to list" << std::endl; if(client.path == "./Public/"){ client.packet << 8 << static_cast<sf::Int32>('P') << static_cast<sf::Int32>('r') << static_cast<sf::Int32>('i') << static_cast<sf::Int32>('v') << static_cast<sf::Int32>('a') << static_cast<sf::Int32>('t') << static_cast<sf::Int32>('t') << static_cast<sf::Int32>('/'); client.socket.send( client.packet ); client.packet.clear(); } while( (redfile = readdir( directory )) != NULL ){ std::string tmp( redfile->d_name ); if( !fileExist(client.path + tmp) ){ tmp += "/"; } client.packet << static_cast<unsigned int>( tmp.length() ); for( unsigned short i(0) ; i < tmp.length() ; ++i ){ client.packet << static_cast<sf::Int32>( tmp[i] ); } client.socket.send( client.packet ); client.packet.clear(); } client.packet << 0 << EndOfStream; client.socket.send( client.packet ); client.packet.clear(); std::cout << client.name() << " -> file listed" << std::endl; return true; } <commit_msg>error fix<commit_after>#include "../../include/server0/listFiles.hpp" bool listFiles(Client& client){ //checking allowance and sending what's up about this DIR* directory = opendir(client.path.c_str()); struct dirent* redfile = NULL; client.packet.clear(); if( directory == NULL ){ client.packet << VoidDirectory; client.socket.send( client.packet ); std::cout << client.name() << " -> Could not open the directory" << std::endl; return false; }//else client.packet << ServerReady; client.socket.send( client.packet ); client.packet.clear(); std::cout << client.name() << " -> Server ready to list" << std::endl; if(client.path == "./Public/"){ client.packet << 8 << static_cast<sf::Int32>('P') << static_cast<sf::Int32>('r') << static_cast<sf::Int32>('i') << static_cast<sf::Int32>('v') << static_cast<sf::Int32>('a') << static_cast<sf::Int32>('t') << static_cast<sf::Int32>('e') << static_cast<sf::Int32>('/'); client.socket.send( client.packet ); client.packet.clear(); } while( (redfile = readdir( directory )) != NULL ){ std::string tmp( redfile->d_name ); if( !fileExist(client.path + tmp) ){ tmp += "/"; } client.packet << static_cast<unsigned int>( tmp.length() ); for( unsigned short i(0) ; i < tmp.length() ; ++i ){ client.packet << static_cast<sf::Int32>( tmp[i] ); } client.socket.send( client.packet ); client.packet.clear(); } client.packet << 0 << EndOfStream; client.socket.send( client.packet ); client.packet.clear(); std::cout << client.name() << " -> file listed" << std::endl; return true; } <|endoftext|>
<commit_before>// main.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Utilities.h" // Functions to load in a single image or all images Mat loadImage(char* location, char* file); Mat* loadImages(int numberOfImages, char* location, char** files); // A function which temporarily resizes images before showing them void showImage(char* name, Mat image); // "Sign" functions - used to detect bus stop signs Mat findSign(Mat image); Mat binaryImage(Mat image); Mat backProjection(Mat image, Mat yellow); Mat getHue(Mat image); Mat templateMatching(Mat image, Mat templateImage); // "Number" function - used to detect the stop number from the sign void digitRecognition(Mat image); int _tmain(int argc, _TCHAR* argv[]) { cout << "Using OpenCV " << CV_VERSION << endl; char* testLocation = "Media/Test Images/"; // Location of bus stop sign images // Bus stop sign images char* testFiles[] = { "2809 a.jpg", "2809 b.jpg", "2830 a.jpg", "2830 b.jpg", "2838 a.jpg", "2838 b.jpg", "2838 c.jpg", "2838 d.jpg", "2839 a.jpg", "2839 b.jpg", "2839 c.jpg", "2839 d.jpg" }; char* templateLocation = "Media/Templates/"; // Location of sample stop sign images // Sample stop sign images char* templateFiles[] = { "stop.png", "stop&no.png", "stop2.png", "stop&no2.png", "yellow.png" }; Mat sign = loadImage(testLocation, testFiles[6]); Mat templateSign = loadImage(templateLocation, templateFiles[2]); Mat yellow = loadImage(templateLocation, templateFiles[4]); showImage("Bus Stop Sign", sign); Mat hsvSign = findSign(sign); Mat binary = binaryImage(sign); Mat backProjSign = backProjection(sign, yellow); //Mat templateMatch = templateMatching(sign, templateSign); Mat templateMatch = templateMatching(sign, yellow); showImage("HSV", hsvSign); showImage("Binary", binary); showImage("Back Projection", backProjSign); showImage("Template Matching", templateMatch); waitKey(0); /*int numberOfTestImages = sizeof(testFiles) / sizeof(testFiles[0]); Mat* busStops = loadImages(numberOfTestImages, testLocation, testFiles); int numberOfTemplateImages = sizeof(templateFiles) / sizeof(templateFiles[0]); Mat* templates = loadImages(numberOfTemplateImages, templateLocation, templateFiles); for (int i = 0; i < numberOfTestImages; i++) { cout << "Processing image " << (i + 1) << endl; showImage("Sign", busStops[i]); Mat hsvSign = findSign(busStops[i]); Mat binary = binaryImage(busStops[i]); Mat backProjSign = backProjection(busStops[i], templates[4]); Mat templateMatch; if (i == 0 || i == 1) { // templates[0] or templates[1] templateMatch = templateMatching(busStops[i], templates[0]); } else { // templates[2] or templates[3] templateMatch = templateMatching(busStops[i], templates[2]); } showImage("HSV", hsvSign); showImage("Binary", binary); showImage("Back Projection", backProjSign); showImage("Template Matching", templateMatch); waitKey(0); }*/ return 0; } Mat loadImage(char* location, char* file) { string filename(location); filename.append(file); Mat image = imread(filename, 1); return image; } Mat* loadImages(int numberOfImages, char* location, char** files) { Mat* images = new Mat[numberOfImages]; for (int i = 0; i < numberOfImages; i++) { string filename(location); filename.append(files[i]); cout << "Loading image " << (i + 1) << ": " << filename << endl; images[i] = imread(filename, 1); } return images; } void showImage(char* name, Mat image) { resize(image, image, Size(image.cols / 4, image.rows / 4)); imshow(name, image); return; } Mat findSign(Mat image) { Mat hsv; cvtColor(image, hsv, CV_BGR2HSV); inRange(hsv, Scalar(15, 135, 140), Scalar(30, 255, 255), hsv); return hsv; } Mat binaryImage(Mat image) { Mat greyImage, binaryResult; cvtColor(image, greyImage, CV_BGR2GRAY); threshold(greyImage, binaryResult, 200, 255, THRESH_BINARY); return binaryResult; } Mat backProjection(Mat image, Mat yellow) { Mat imageHue = getHue(image); Mat yellowHue = getHue(yellow); Mat hist; int histSize = 180; float hue_range[] = { 0, 180 }; const float* ranges = { hue_range }; calcHist(&yellowHue, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false); normalize(hist, hist, 0, 255, NORM_MINMAX, -1, Mat()); Mat backProject; calcBackProject(&imageHue, 1, 0, hist, backProject, &ranges, 1, true); return backProject; } Mat getHue(Mat image) { Mat hsv, hue; cvtColor(image, hsv, CV_BGR2HSV); hue.create(hsv.size(), hsv.depth()); int ch[] = { 0, 0 }; mixChannels(&hsv, 1, &hue, 1, ch, 1); return hue; } Mat templateMatching(Mat image, Mat templateImage) { Mat result; Mat imageDisplay; image.copyTo(imageDisplay); int rows = image.rows - templateImage.rows + 1; int cols = image.cols - templateImage.cols + 1; result.create(rows, cols, CV_32FC1); matchTemplate(image, templateImage, result, CV_TM_SQDIFF); normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat()); double minVal, maxVal; Point minLoc, maxLoc, matchLoc; minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat()); matchLoc = minLoc; rectangle(imageDisplay, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0); rectangle(result, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0); /*showImage("Image", imageDisplay); showImage("Result", result); waitKey(0);*/ //return result; return imageDisplay; } void digitRecognition(Mat image) { // TODO: recognise numbers from sign return; }<commit_msg>changed type of 'digitRecognition()' to return an int<commit_after>// main.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Utilities.h" // Functions to load in a single image or all images Mat loadImage(char* location, char* file); Mat* loadImages(int numberOfImages, char* location, char** files); // A function which temporarily resizes images before showing them void showImage(char* name, Mat image); // "Sign" functions - used to detect bus stop signs Mat findSign(Mat image); Mat binaryImage(Mat image); Mat backProjection(Mat image, Mat yellow); Mat getHue(Mat image); Mat templateMatching(Mat image, Mat templateImage); // "Number" function - used to detect the stop number from the sign int digitRecognition(Mat image); int _tmain(int argc, _TCHAR* argv[]) { cout << "Using OpenCV " << CV_VERSION << endl; char* testLocation = "Media/Test Images/"; // Location of bus stop sign images // Bus stop sign images char* testFiles[] = { "2809 a.jpg", "2809 b.jpg", "2830 a.jpg", "2830 b.jpg", "2838 a.jpg", "2838 b.jpg", "2838 c.jpg", "2838 d.jpg", "2839 a.jpg", "2839 b.jpg", "2839 c.jpg", "2839 d.jpg" }; char* templateLocation = "Media/Templates/"; // Location of sample stop sign images // Sample stop sign images char* templateFiles[] = { "stop.png", "stop&no.png", "stop2.png", "stop&no2.png", "yellow.png" }; Mat sign = loadImage(testLocation, testFiles[6]); Mat templateSign = loadImage(templateLocation, templateFiles[2]); Mat yellow = loadImage(templateLocation, templateFiles[4]); showImage("Bus Stop Sign", sign); Mat hsvSign = findSign(sign); Mat binary = binaryImage(sign); Mat backProjSign = backProjection(sign, yellow); //Mat templateMatch = templateMatching(sign, templateSign); Mat templateMatch = templateMatching(sign, yellow); showImage("HSV", hsvSign); showImage("Binary", binary); showImage("Back Projection", backProjSign); showImage("Template Matching", templateMatch); waitKey(0); /*int numberOfTestImages = sizeof(testFiles) / sizeof(testFiles[0]); Mat* busStops = loadImages(numberOfTestImages, testLocation, testFiles); int numberOfTemplateImages = sizeof(templateFiles) / sizeof(templateFiles[0]); Mat* templates = loadImages(numberOfTemplateImages, templateLocation, templateFiles); for (int i = 0; i < numberOfTestImages; i++) { cout << "Processing image " << (i + 1) << endl; showImage("Sign", busStops[i]); Mat hsvSign = findSign(busStops[i]); Mat binary = binaryImage(busStops[i]); Mat backProjSign = backProjection(busStops[i], templates[4]); Mat templateMatch; if (i == 0 || i == 1) { // templates[0] or templates[1] templateMatch = templateMatching(busStops[i], templates[0]); } else { // templates[2] or templates[3] templateMatch = templateMatching(busStops[i], templates[2]); } showImage("HSV", hsvSign); showImage("Binary", binary); showImage("Back Projection", backProjSign); showImage("Template Matching", templateMatch); waitKey(0); }*/ return 0; } Mat loadImage(char* location, char* file) { string filename(location); filename.append(file); Mat image = imread(filename, 1); return image; } Mat* loadImages(int numberOfImages, char* location, char** files) { Mat* images = new Mat[numberOfImages]; for (int i = 0; i < numberOfImages; i++) { string filename(location); filename.append(files[i]); cout << "Loading image " << (i + 1) << ": " << filename << endl; images[i] = imread(filename, 1); } return images; } void showImage(char* name, Mat image) { resize(image, image, Size(image.cols / 4, image.rows / 4)); imshow(name, image); return; } Mat findSign(Mat image) { Mat hsv; cvtColor(image, hsv, CV_BGR2HSV); inRange(hsv, Scalar(15, 135, 140), Scalar(30, 255, 255), hsv); return hsv; } Mat binaryImage(Mat image) { Mat greyImage, binaryResult; cvtColor(image, greyImage, CV_BGR2GRAY); threshold(greyImage, binaryResult, 200, 255, THRESH_BINARY); return binaryResult; } Mat backProjection(Mat image, Mat yellow) { Mat imageHue = getHue(image); Mat yellowHue = getHue(yellow); Mat hist; int histSize = 180; float hue_range[] = { 0, 180 }; const float* ranges = { hue_range }; calcHist(&yellowHue, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false); normalize(hist, hist, 0, 255, NORM_MINMAX, -1, Mat()); Mat backProject; calcBackProject(&imageHue, 1, 0, hist, backProject, &ranges, 1, true); return backProject; } Mat getHue(Mat image) { Mat hsv, hue; cvtColor(image, hsv, CV_BGR2HSV); hue.create(hsv.size(), hsv.depth()); int ch[] = { 0, 0 }; mixChannels(&hsv, 1, &hue, 1, ch, 1); return hue; } Mat templateMatching(Mat image, Mat templateImage) { Mat result; Mat imageDisplay; image.copyTo(imageDisplay); int rows = image.rows - templateImage.rows + 1; int cols = image.cols - templateImage.cols + 1; result.create(rows, cols, CV_32FC1); matchTemplate(image, templateImage, result, CV_TM_SQDIFF); normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat()); double minVal, maxVal; Point minLoc, maxLoc, matchLoc; minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat()); matchLoc = minLoc; rectangle(imageDisplay, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0); rectangle(result, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0); /*showImage("Image", imageDisplay); showImage("Result", result); waitKey(0);*/ //return result; return imageDisplay; } int digitRecognition(Mat image) { // TODO: recognise numbers from sign return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/status_area/status_area_view.h" #include "ash/ash_export.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "base/utf_string_conversions.h" #include "grit/ui_resources.h" #include "ui/aura/root_window.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { StatusAreaView::StatusAreaView() : status_mock_(*ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_AURA_STATUS_MOCK)) { } StatusAreaView::~StatusAreaView() { } gfx::Size StatusAreaView::GetPreferredSize() { return gfx::Size(status_mock_.width(), status_mock_.height()); } void StatusAreaView::OnPaint(gfx::Canvas* canvas) { canvas->DrawBitmapInt(status_mock_, 0, 0); } ASH_EXPORT views::Widget* CreateStatusArea() { StatusAreaView* status_area_view = new StatusAreaView; views::Widget* widget = new views::Widget; views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); gfx::Size ps = status_area_view->GetPreferredSize(); params.bounds = gfx::Rect(0, 0, ps.width(), ps.height()); params.delegate = status_area_view; params.parent = Shell::GetInstance()->GetContainer( ash::internal::kShellWindowId_StatusContainer); params.transparent = true; widget->Init(params); widget->SetContentsView(status_area_view); widget->Show(); widget->GetNativeView()->SetName("StatusAreaView"); return widget; } } // namespace internal } // namespace ash <commit_msg>Turn off initial focus on the status area to fix aura_shell_unittests<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/status_area/status_area_view.h" #include "ash/ash_export.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "base/utf_string_conversions.h" #include "grit/ui_resources.h" #include "ui/aura/root_window.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { StatusAreaView::StatusAreaView() : status_mock_(*ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_AURA_STATUS_MOCK)) { } StatusAreaView::~StatusAreaView() { } gfx::Size StatusAreaView::GetPreferredSize() { return gfx::Size(status_mock_.width(), status_mock_.height()); } void StatusAreaView::OnPaint(gfx::Canvas* canvas) { canvas->DrawBitmapInt(status_mock_, 0, 0); } ASH_EXPORT views::Widget* CreateStatusArea() { StatusAreaView* status_area_view = new StatusAreaView; views::Widget* widget = new views::Widget; views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); gfx::Size ps = status_area_view->GetPreferredSize(); params.bounds = gfx::Rect(0, 0, ps.width(), ps.height()); params.delegate = status_area_view; params.parent = Shell::GetInstance()->GetContainer( ash::internal::kShellWindowId_StatusContainer); params.transparent = true; widget->Init(params); widget->set_focus_on_creation(false); widget->SetContentsView(status_area_view); widget->Show(); widget->GetNativeView()->SetName("StatusAreaView"); return widget; } } // namespace internal } // namespace ash <|endoftext|>
<commit_before>#ifndef ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__ #define ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__ #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/topology/Conversions.hh> #include <aleph/topology/Intersections.hh> #include <aleph/topology/SimplicialComplex.hh> #include <initializer_list> #include <map> #include <ostream> #include <stdexcept> #include <utility> #include <vector> namespace aleph { /** Partitions a simplicial complex according to its $\phi$-persistence values. This follows the persistent intersection homology algorithm in: Persistent Intersection Homology\n Paul Bendich and John Harer\n The function uses a simplicial complex \f$K\f$ and a function \f$\phi\f$ that determines whether a simplex is proper or not. The function is going to create a new simplicial complex. This complex contains all proper simplices (in their original order) followed by all improper ones. */ template <class Simplex, class Function> std::pair<topology::SimplicialComplex<Simplex>, std::size_t> partition( const topology::SimplicialComplex<Simplex>& K, Function phi ) { topology::SimplicialComplex<Simplex> L; for( auto&& simplex : K ) { if( phi(simplex) ) L.push_back( simplex ); } auto s = L.size(); for( auto&& simplex : K ) { if( !phi(simplex) ) L.push_back( simplex ); } return std::make_pair( L, s ); } /** @class Perversity @brief Perversity model in the sense of intersection homology Models a perversity in the sense of intersection homology. The class ensures that all values satisfy \f -1 \leq p_k \leq k-1 \f */ class Perversity { public: /** Creates a new perversity from a range of values. The values must be at least implicitly convertible to integers. */ template <class InputIterator> Perversity( InputIterator begin, InputIterator end ) : _values( begin, end ) { for( std::size_t k = 0; k < _values.size(); k++ ) { if( _values[k] < -1 ) _values[k] = -1; // There is an index shift going on here: since $k$ runs from $0$ // to $d-1$, there is no need to shift the upper bound. else if( _values[k] > static_cast<int>( k ) ) _values[k] = static_cast<int>( k ); } } /** Creates a new perversity from an initializer list of values */ Perversity( std::initializer_list<int> values ) : Perversity( values.begin(), values.end() ) { } /** Queries the perversity value in a given dimension $d$. Invalid dimension values only cause the function to return a zero. */ int operator()( std::size_t d ) const noexcept { if( d < _values.size() + 1 ) return _values[ static_cast<std::size_t>( d-1 ) ]; else return 0; } using const_iterator = typename std::vector<int>::const_iterator; const_iterator begin() const noexcept { return _values.begin(); } const_iterator end() const noexcept { return _values.end(); } private: std::vector<int> _values; }; std::ostream& operator<<( std::ostream& o, const Perversity p ) { o << "["; for( auto it = p.begin(); it != p.end(); ++it ) { if( it != p.begin() ) o << ","; o << *it; } o << "]"; return o; } template <class Simplex> auto calculateIntersectionHomology( const aleph::topology::SimplicialComplex<Simplex>& K, const std::vector< aleph::topology::SimplicialComplex<Simplex> >& X, const Perversity& p, bool useOriginalIndexing = false ) -> std::vector< PersistenceDiagram<typename Simplex::DataType> > { // 0. Check consistency of strata // 1. Create allowability function based on the dimensionality of the // intersection of simplices with individual strata. // 2. Calculate $phi$-persistence // 3. Convert the result into a persistence diagram. // Check consistency of filtration ----------------------------------- // // The maximum dimension of each complex in the filtration has to // match the dimension of the simplicial complex. { std::size_t minDimension = K.dimension(); std::size_t maxDimension = 0; for( auto&& x : X ) { if( !K.empty() ) { minDimension = std::min( minDimension, x.dimension() ); maxDimension = std::max( maxDimension, x.dimension() ); } } if( maxDimension != K.dimension() ) throw std::runtime_error( "Invalid filtration" ); } // Check whether simplex is allowable -------------------------------- std::map<Simplex, bool> phi; { auto d = K.dimension(); for( auto&& s : K ) { bool admissible = true; // Note that I am letting the index start at $k = 2$ because this // is in consistent with the original definition given by Goresky // and MacPherson. By default, this behaviour is *not* active. for( std::size_t k = useOriginalIndexing ? 2 : 1; k <= d; k++ ) { // The notation follows Bendich and Harer, so $i$ is actually // referring to a dimension instead of an index. Beware! auto i = s.dimension(); auto intersection = aleph::topology::lastLexicographicalIntersection( X.at( d - k ), s ); auto dimension = intersection.empty() ? -1 : static_cast<long>( intersection.dimension() ); admissible = admissible && intersection.empty() ? true : static_cast<long>( dimension ) <= ( long(i) - long(k) + long( p(k) ) ); } phi[s] = admissible; } } // Partition according to allowable simplices ------------------------ aleph::topology::SimplicialComplex<Simplex> L; std::size_t s = 0; std::tie( L, s ) = aleph::partition( K, [&phi] ( const Simplex& s ) { return phi.at(s); } ); // Calculate persistent intersection homology ------------------------ auto boundaryMatrix = aleph::topology::makeBoundaryMatrix( L, s ); using IndexType = typename decltype(boundaryMatrix)::Index; bool includeAllUnpairedCreators = true; auto pairing = aleph::calculatePersistencePairing( boundaryMatrix, includeAllUnpairedCreators, static_cast<IndexType>(s) ); auto persistenceDiagrams = aleph::makePersistenceDiagrams( pairing, L ); return persistenceDiagrams; } } // namespace aleph #endif <commit_msg>Implemented improved perversity model for intersection homology<commit_after>#ifndef ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__ #define ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__ #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/topology/Conversions.hh> #include <aleph/topology/Intersections.hh> #include <aleph/topology/SimplicialComplex.hh> #include <initializer_list> #include <map> #include <ostream> #include <stdexcept> #include <utility> #include <vector> namespace aleph { /** Partitions a simplicial complex according to its $\phi$-persistence values. This follows the persistent intersection homology algorithm in: Persistent Intersection Homology\n Paul Bendich and John Harer\n The function uses a simplicial complex \f$K\f$ and a function \f$\phi\f$ that determines whether a simplex is proper or not. The function is going to create a new simplicial complex. This complex contains all proper simplices (in their original order) followed by all improper ones. */ template <class Simplex, class Function> std::pair<topology::SimplicialComplex<Simplex>, std::size_t> partition( const topology::SimplicialComplex<Simplex>& K, Function phi ) { topology::SimplicialComplex<Simplex> L; for( auto&& simplex : K ) { if( phi(simplex) ) L.push_back( simplex ); } auto s = L.size(); for( auto&& simplex : K ) { if( !phi(simplex) ) L.push_back( simplex ); } return std::make_pair( L, s ); } /** @class Perversity @brief Perversity model in the sense of persistent intersection homology Models a perversity in the sense of persistent intersection homology, following the definitions of Bendich. The class ensures that all values satisfy \f -1 \leq p_k \leq k-1 \f */ class Perversity { public: /** Creates a new perversity from a range of values. The values must be at least implicitly convertible to integers. */ template <class InputIterator> Perversity( InputIterator begin, InputIterator end ) : _values( begin, end ) { for( std::size_t k = 0; k < _values.size(); k++ ) { if( _values[k] < -1 ) _values[k] = -1; // There is an index shift going on here: since $k$ runs from $0$ // to $d-1$, there is no need to shift the upper bound. else if( _values[k] > static_cast<int>( k ) ) _values[k] = static_cast<int>( k ); } } /** Creates a new perversity from an initializer list of values */ Perversity( std::initializer_list<int> values ) : Perversity( values.begin(), values.end() ) { } /** Queries the perversity value in a given dimension $d$. Invalid dimension values only cause the function to return a zero. */ int operator()( std::size_t d ) const noexcept { if( d < _values.size() + 1 ) return _values[ static_cast<std::size_t>( d-1 ) ]; else return 0; } using const_iterator = typename std::vector<int>::const_iterator; const_iterator begin() const noexcept { return _values.begin(); } const_iterator end() const noexcept { return _values.end(); } private: std::vector<int> _values; }; /** @class PerversityGM @brief Perversity model in the sense of intersection homology Models a perversity in the sense of intersection homology, following Goresky and MacPherson. The class ensures that all values satisfy \f p_{k+1} = p_k \mathrm{ or } p_{k+1} = p_k + 1 \f and \f$p_2 = 0\f$. */ class PerversityGM { public: /** Creates a new perversity from a range of values. The values must be at least implicitly convertible to integers. */ template <class InputIterator> PerversityGM( InputIterator begin, InputIterator end ) : _values( begin, end ) { for( std::size_t k = 1; k < _values.size(); k++ ) { if( _values[k] != _values[k-1] && _values[k] != _values[k-1] + 1 ) _values[k] = _values[k-1] + 1; } } /** Creates a new perversity from an initializer list of values */ PerversityGM( std::initializer_list<int> values ) : PerversityGM( values.begin(), values.end() ) { } /** Queries the perversity value in a given dimension \p d. Invalid dimension values only cause the function to return a zero. */ unsigned operator()( std::size_t d ) const noexcept { if( d < _values.size() + 2 ) return _values[ static_cast<std::size_t>( d-2 ) ]; else return 0; } using const_iterator = typename std::vector<unsigned>::const_iterator; const_iterator begin() const noexcept { return _values.begin(); } const_iterator end() const noexcept { return _values.end(); } private: std::vector<unsigned> _values; }; std::ostream& operator<<( std::ostream& o, const Perversity p ) { o << "["; for( auto it = p.begin(); it != p.end(); ++it ) { if( it != p.begin() ) o << ","; o << *it; } o << "]"; return o; } template <class Simplex, class Perversity> auto calculateIntersectionHomology( const aleph::topology::SimplicialComplex<Simplex>& K, const std::vector< aleph::topology::SimplicialComplex<Simplex> >& X, const Perversity& p, bool useOriginalIndexing = false ) -> std::vector< PersistenceDiagram<typename Simplex::DataType> > { // 0. Check consistency of strata // 1. Create allowability function based on the dimensionality of the // intersection of simplices with individual strata. // 2. Calculate $phi$-persistence // 3. Convert the result into a persistence diagram. // Check consistency of filtration ----------------------------------- // // The maximum dimension of each complex in the filtration has to // match the dimension of the simplicial complex. { std::size_t minDimension = K.dimension(); std::size_t maxDimension = 0; for( auto&& x : X ) { if( !K.empty() ) { minDimension = std::min( minDimension, x.dimension() ); maxDimension = std::max( maxDimension, x.dimension() ); } } if( maxDimension != K.dimension() ) throw std::runtime_error( "Invalid filtration" ); } // Check whether simplex is allowable -------------------------------- std::map<Simplex, bool> phi; { auto d = K.dimension(); for( auto&& s : K ) { bool admissible = true; // Note that I am letting the index start at $k = 2$ because this // is in consistent with the original definition given by Goresky // and MacPherson. By default, this behaviour is *not* active. for( std::size_t k = useOriginalIndexing ? 2 : 1; k <= d; k++ ) { // The notation follows Bendich and Harer, so $i$ is actually // referring to a dimension instead of an index. Beware! auto i = s.dimension(); auto intersection = aleph::topology::lastLexicographicalIntersection( X.at( d - k ), s ); auto dimension = intersection.empty() ? -1 : static_cast<long>( intersection.dimension() ); admissible = admissible && intersection.empty() ? true : static_cast<long>( dimension ) <= ( long(i) - long(k) + long( p(k) ) ); } phi[s] = admissible; } } // Partition according to allowable simplices ------------------------ aleph::topology::SimplicialComplex<Simplex> L; std::size_t s = 0; std::tie( L, s ) = aleph::partition( K, [&phi] ( const Simplex& s ) { return phi.at(s); } ); // Calculate persistent intersection homology ------------------------ auto boundaryMatrix = aleph::topology::makeBoundaryMatrix( L, s ); using IndexType = typename decltype(boundaryMatrix)::Index; bool includeAllUnpairedCreators = true; auto pairing = aleph::calculatePersistencePairing( boundaryMatrix, includeAllUnpairedCreators, static_cast<IndexType>(s) ); auto persistenceDiagrams = aleph::makePersistenceDiagrams( pairing, L ); return persistenceDiagrams; } } // namespace aleph #endif <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "OrbitGgp/GgpClient.h" #include <QDebug> #include <QEventLoop> #include <QPointer> #include <QProcess> #include <QTimer> #include "OrbitBase/Logging.h" #include "OrbitGgp/GgpInstance.h" const int InstanceRequestTimeoutInMilliseconds = 10'000; GgpClient::ResultOrQString<GgpClient> GgpClient::Create() { QProcess ggp_process{}; ggp_process.setProgram("ggp"); ggp_process.setArguments({"version"}); ggp_process.start(QIODevice::ReadOnly); ggp_process.waitForFinished(); if (ggp_process.exitStatus() != QProcess::NormalExit || ggp_process.exitCode() != 0) { return QString{ "Ggp command line process failed with error: %1 (exit code: %2)"} .arg(ggp_process.errorString().arg(ggp_process.exitCode())); } const QByteArray process_result = ggp_process.readAllStandardOutput(); const QList<QByteArray> tokens = process_result.split(' '); if (tokens.size() < 2) { return QString{ "The current version of GGP is not supported by this integration."}; } GgpClient client{}; client.version_ = tokens.first().toStdString(); return client; } void GgpClient::GetInstancesAsync( const std::function<void(ResultOrQString<QVector<GgpInstance>>)>& callback) { CHECK(callback); const auto ggp_process = QPointer{new QProcess{}}; ggp_process->setProgram("ggp"); ggp_process->setArguments({"instance", "list", "-s"}); const auto timeout_timer = QPointer{new QTimer{}}; QObject::connect( timeout_timer, &QTimer::timeout, timeout_timer, [ggp_process, timeout_timer, callback, this]() { callback(QString("Ggp list instances request timed out after %1 ms.") .arg(InstanceRequestTimeoutInMilliseconds)); ggp_process->terminate(); ggp_process->waitForFinished(); number_of_requests_running_--; if (ggp_process != nullptr) ggp_process->deleteLater(); timeout_timer->deleteLater(); }); QObject::connect( ggp_process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>( &QProcess::finished), ggp_process, [callback, ggp_process, timeout_timer, this]( const int exit_code, const QProcess::ExitStatus exit_status) { if (exit_status != QProcess::NormalExit || exit_code != 0) { callback( QString{"Ggp list instances request failed with error: %1 (exit " "code: %2)"} .arg(ggp_process->errorString()) .arg(exit_code)); return; } number_of_requests_running_--; const QByteArray jsonData = ggp_process->readAllStandardOutput(); callback(GgpInstance::GetListFromJson(jsonData)); ggp_process->deleteLater(); if (timeout_timer != nullptr) { timeout_timer->stop(); timeout_timer->deleteLater(); } }); number_of_requests_running_++; ggp_process->start(QIODevice::ReadOnly); timeout_timer->start(InstanceRequestTimeoutInMilliseconds); }<commit_msg>Refactored running the ggp process with GgpClient<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "OrbitGgp/GgpClient.h" #include <QDebug> #include <QEventLoop> #include <QPointer> #include <QProcess> #include <QTimer> #include "OrbitBase/Logging.h" #include "OrbitGgp/GgpInstance.h" namespace { constexpr int kDefaultTimeoutInMs = 10'000; void RunProcessWithTimeout( const QString& program, const QStringList& arguments, const std::function<void(GgpClient::ResultOrQString<QByteArray>)>& callback, int timeout_in_ms = kDefaultTimeoutInMs) { const auto process = QPointer{new QProcess{}}; process->setProgram(program); process->setArguments(arguments); const auto timeout_timer = QPointer{new QTimer{}}; QObject::connect( timeout_timer, &QTimer::timeout, timeout_timer, [process, timeout_timer, callback, timeout_in_ms]() { QString error_message = QString{"Process request timed out after %1ms"}.arg(timeout_in_ms); callback(outcome::failure(error_message)); process->terminate(); process->waitForFinished(); if (process != nullptr) process->deleteLater(); timeout_timer->deleteLater(); }); QObject::connect( process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>( &QProcess::finished), process, [process, timeout_timer, callback]( const int exit_code, const QProcess::ExitStatus exit_status) { if (exit_status != QProcess::NormalExit || exit_code != 0) { callback(outcome::failure( QString{"Ggp list instances request failed with error: %1 (exit " "code: %2)"} .arg(process->errorString()) .arg(exit_code))); return; } callback(outcome::success(process->readAllStandardOutput())); process->deleteLater(); if (timeout_timer != nullptr) { timeout_timer->stop(); timeout_timer->deleteLater(); } }); process->start(QIODevice::ReadOnly); timeout_timer->start(timeout_in_ms); } } // namespace GgpClient::ResultOrQString<GgpClient> GgpClient::Create() { QProcess ggp_process{}; ggp_process.setProgram("ggp"); ggp_process.setArguments({"version"}); ggp_process.start(QIODevice::ReadOnly); ggp_process.waitForFinished(); if (ggp_process.exitStatus() != QProcess::NormalExit || ggp_process.exitCode() != 0) { return QString{ "Ggp command line process failed with error: %1 (exit code: %2)"} .arg(ggp_process.errorString().arg(ggp_process.exitCode())); } const QByteArray process_result = ggp_process.readAllStandardOutput(); const QList<QByteArray> tokens = process_result.split(' '); if (tokens.size() < 2) { return QString{ "The current version of GGP is not supported by this integration."}; } GgpClient client{}; client.version_ = tokens.first().toStdString(); return client; } void GgpClient::GetInstancesAsync( const std::function<void(ResultOrQString<QVector<GgpInstance>>)>& callback) { CHECK(callback); number_of_requests_running_++; RunProcessWithTimeout( "ggp", {"instance", "list", "-s"}, [callback, this](ResultOrQString<QByteArray> result) { number_of_requests_running_--; if (!result) { callback(result.error()); return; } callback(GgpInstance::GetListFromJson(result.value())); }); }<|endoftext|>
<commit_before>// // This file contains the class InputDialog. // An InputDialog object prompts for an input string using a simple // dialog box. The InputDialog class is also a good example of how // to use the ROOT GUI classes via the interpreter. Since interpreted // classes can not call virtual functions via base class pointers, all // GUI objects are used by composition instead of by inheritance. // // This file contains also some utility functions that use // the InputDialog class to either get a string, integer or // floating point number. There are also two functions showing // how to use the file open and save dialogs. The utility functions are: // // const char *OpenFileDialog() // const char *SaveFileDialog() // const char *GetStringDialog(const char *prompt, const char *defval) // Int_t GetIntegerDialog(const char *prompt, Int_t defval) // Float_t GetFloatDialog(const char *prompt, Float_t defval) // // To use the InputDialog class and the utility functions you just // have to load the dialogs.C file as follows: // .L dialogs.C // // Now you can use them like: // { // const char *file = OpenFileDialog(); // Int_t run = GetIntegerDialog("Give run number:", 0); // Int_t event = GetIntegerDialog("Give event number:", 0); // printf("analyse run %d, event %d from file %s\n", run ,event, file); // } // /////////////////////////////////////////////////////////////////////////// // // // Input Dialog Widget // // // /////////////////////////////////////////////////////////////////////////// class InputDialog { private: TGTransientFrame *fDialog; // transient frame, main dialog window TGTextEntry *fTE; // text entry widget containing TList *fWidgets; // keep track of widgets to be deleted in dtor char *fRetStr; // address to store return string public: InputDialog(const char *prompt, const char *defval, char *retstr); ~InputDialog(); void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2); }; InputDialog::~InputDialog() { // Cleanup dialog. fWidgets->Delete(); delete fWidgets; delete fTE; delete fDialog; } InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr) { // Create simple input dialog. fWidgets = new TList; TGWindow *main = gClient->GetRoot(); fDialog = new TGTransientFrame(main, main, 10, 10); // command to be executed by buttons and text entry widget char cmd[128]; sprintf(cmd, "{long r__ptr=0x%x; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", this); // create prompt label and textentry widget TGLabel *label = new TGLabel(fDialog, prompt); fWidgets->Add(label); TGTextBuffer *tbuf = new TGTextBuffer(256); //will be deleted by TGtextEntry tbuf->AddText(0, defval); fTE = new TGTextEntry(fDialog, tbuf); fTE->Resize(260, fTE->GetDefaultHeight()); fTE->SetCommand(cmd); TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0); TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5); fWidgets->Add(l1); fWidgets->Add(l2); fDialog->AddFrame(label, l1); fDialog->AddFrame(fTE, l2); // create frame and layout hints for Ok and Cancel buttons TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth); TGLayoutHints *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0); // put hf as last in list to be deleted fWidgets->Add(l3); // create OK and Cancel buttons in their own frame (hf) UInt_t nb = 0, width = 0, height = 0; TGTextButton *b; b = new TGTextButton(hf, "&Ok", cmd, 1); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; b = new TGTextButton(hf, "&Cancel", cmd, 2); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; // place button frame (hf) at the bottom TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5); fWidgets->Add(l4); fWidgets->Add(hf); fDialog->AddFrame(hf, l4); // keep buttons centered and with the same width hf->Resize((width + 20) * nb, height); // set dialog title fDialog->SetWindowName("Get Input"); // map all widgets and calculate size of dialog fDialog->MapSubwindows(); width = fDialog->GetDefaultWidth(); height = fDialog->GetDefaultHeight(); fDialog->Resize(width, height); // position relative to the parent window (which is the root window) Window_t wdum; int ax, ay; gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(), (((TGFrame *) main)->GetWidth() - width) >> 1, (((TGFrame *) main)->GetHeight() - height) >> 1, ax, ay, wdum); fDialog->Move(ax, ay); fDialog->SetWMPosition(ax, ay); // make the message box non-resizable fDialog->SetWMSize(width, height); fDialog->SetWMSizeHints(width, height, width, height, 0, 0); fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize | kMWMDecorMinimize | kMWMDecorMenu, kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize | kMWMFuncMinimize, kMWMInputModeless); // popup dialog and wait till user replies fDialog->MapWindow(); fRetStr = retstr; gClient->WaitFor(fDialog); } void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle button and text enter events switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_BUTTON: switch (parm1) { case 1: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; case 2: fRetStr[0] = 0; delete this; break; } default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; default: break; } break; default: break; } } //--- Utility Functions -------------------------------------------------------- const char *OpenFileDialog() { // Prompt for file to be opened. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gOpenAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gOpenAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi); return fi.fFilename; } const char *SaveFileDialog() { // Prompt for file to be saved. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gSaveAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gSaveAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi); return fi.fFilename; } const char *GetStringDialog(const char *prompt, const char *defval) { // Prompt for string. The typed in string is returned. static char answer[128]; new InputDialog(prompt, defval, answer); return answer; } Int_t GetIntegerDialog(const char *prompt, Int_t defval) { // Prompt for integer. The typed in integer is returned. static char answer[32]; char defv[32]; sprintf(defv, "%d", defval); new InputDialog(prompt, defv, answer); return atoi(answer); } Float_t GetFloatDialog(const char *prompt, Float_t defval) { // Prompt for float. The typed in float is returned. static char answer[32]; char defv[32]; sprintf(defv, "%f", defval); new InputDialog(prompt, defv, answer); return atof(answer); } <commit_msg>correct printf to create cmd string<commit_after>// // This file contains the class InputDialog. // An InputDialog object prompts for an input string using a simple // dialog box. The InputDialog class is also a good example of how // to use the ROOT GUI classes via the interpreter. Since interpreted // classes can not call virtual functions via base class pointers, all // GUI objects are used by composition instead of by inheritance. // // This file contains also some utility functions that use // the InputDialog class to either get a string, integer or // floating point number. There are also two functions showing // how to use the file open and save dialogs. The utility functions are: // // const char *OpenFileDialog() // const char *SaveFileDialog() // const char *GetStringDialog(const char *prompt, const char *defval) // Int_t GetIntegerDialog(const char *prompt, Int_t defval) // Float_t GetFloatDialog(const char *prompt, Float_t defval) // // To use the InputDialog class and the utility functions you just // have to load the dialogs.C file as follows: // .L dialogs.C // // Now you can use them like: // { // const char *file = OpenFileDialog(); // Int_t run = GetIntegerDialog("Give run number:", 0); // Int_t event = GetIntegerDialog("Give event number:", 0); // printf("analyse run %d, event %d from file %s\n", run ,event, file); // } // /////////////////////////////////////////////////////////////////////////// // // // Input Dialog Widget // // // /////////////////////////////////////////////////////////////////////////// class InputDialog { private: TGTransientFrame *fDialog; // transient frame, main dialog window TGTextEntry *fTE; // text entry widget containing TList *fWidgets; // keep track of widgets to be deleted in dtor char *fRetStr; // address to store return string public: InputDialog(const char *prompt, const char *defval, char *retstr); ~InputDialog(); void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2); }; InputDialog::~InputDialog() { // Cleanup dialog. fWidgets->Delete(); delete fWidgets; delete fTE; delete fDialog; } InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr) { // Create simple input dialog. fWidgets = new TList; TGWindow *main = gClient->GetRoot(); fDialog = new TGTransientFrame(main, main, 10, 10); // command to be executed by buttons and text entry widget char cmd[128]; sprintf(cmd, "{long r__ptr=0x%lx; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", (Long_t)this); // create prompt label and textentry widget TGLabel *label = new TGLabel(fDialog, prompt); fWidgets->Add(label); TGTextBuffer *tbuf = new TGTextBuffer(256); //will be deleted by TGtextEntry tbuf->AddText(0, defval); fTE = new TGTextEntry(fDialog, tbuf); fTE->Resize(260, fTE->GetDefaultHeight()); fTE->SetCommand(cmd); TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0); TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5); fWidgets->Add(l1); fWidgets->Add(l2); fDialog->AddFrame(label, l1); fDialog->AddFrame(fTE, l2); // create frame and layout hints for Ok and Cancel buttons TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth); TGLayoutHints *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0); // put hf as last in list to be deleted fWidgets->Add(l3); // create OK and Cancel buttons in their own frame (hf) UInt_t nb = 0, width = 0, height = 0; TGTextButton *b; b = new TGTextButton(hf, "&Ok", cmd, 1); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; b = new TGTextButton(hf, "&Cancel", cmd, 2); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; // place button frame (hf) at the bottom TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5); fWidgets->Add(l4); fWidgets->Add(hf); fDialog->AddFrame(hf, l4); // keep buttons centered and with the same width hf->Resize((width + 20) * nb, height); // set dialog title fDialog->SetWindowName("Get Input"); // map all widgets and calculate size of dialog fDialog->MapSubwindows(); width = fDialog->GetDefaultWidth(); height = fDialog->GetDefaultHeight(); fDialog->Resize(width, height); // position relative to the parent window (which is the root window) Window_t wdum; int ax, ay; gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(), (((TGFrame *) main)->GetWidth() - width) >> 1, (((TGFrame *) main)->GetHeight() - height) >> 1, ax, ay, wdum); fDialog->Move(ax, ay); fDialog->SetWMPosition(ax, ay); // make the message box non-resizable fDialog->SetWMSize(width, height); fDialog->SetWMSizeHints(width, height, width, height, 0, 0); fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize | kMWMDecorMinimize | kMWMDecorMenu, kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize | kMWMFuncMinimize, kMWMInputModeless); // popup dialog and wait till user replies fDialog->MapWindow(); fRetStr = retstr; gClient->WaitFor(fDialog); } void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle button and text enter events switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_BUTTON: switch (parm1) { case 1: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; case 2: fRetStr[0] = 0; delete this; break; } default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; default: break; } break; default: break; } } //--- Utility Functions -------------------------------------------------------- const char *OpenFileDialog() { // Prompt for file to be opened. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gOpenAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gOpenAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi); return fi.fFilename; } const char *SaveFileDialog() { // Prompt for file to be saved. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gSaveAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gSaveAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi); return fi.fFilename; } const char *GetStringDialog(const char *prompt, const char *defval) { // Prompt for string. The typed in string is returned. static char answer[128]; new InputDialog(prompt, defval, answer); return answer; } Int_t GetIntegerDialog(const char *prompt, Int_t defval) { // Prompt for integer. The typed in integer is returned. static char answer[32]; char defv[32]; sprintf(defv, "%d", defval); new InputDialog(prompt, defv, answer); return atoi(answer); } Float_t GetFloatDialog(const char *prompt, Float_t defval) { // Prompt for float. The typed in float is returned. static char answer[32]; char defv[32]; sprintf(defv, "%f", defval); new InputDialog(prompt, defv, answer); return atof(answer); } <|endoftext|>
<commit_before>#include <bits/stdc++.h> // using GCC/G++ using namespace std; // linked list node class class Node { public: int val; Node *next; Node(int x) { val = x; next = nullptr; } }; /** * 2.1 Remove Duplicates * O(N^2) time algorithm */ void removeDuplicates(Node *head) { Node *curr = head; while(curr->next) { Node *scout = curr; while(scout->next) { if(scout->next->val == curr->val) { scout->next = scout->next->next; } scout = scout->next; } curr = curr->next; } } /* * Alternate approach with Hash Table/Set * O(n) run time + O(n) extra space */ void removeDuplicatesSet(Node *head) { unordered_set<int> HashSet; Node *curr = head; HashSet.insert(curr->val); while(curr->next) { if(HashSet.find(curr->next->val) != HashSet.end()) curr->next = curr->next->next; else HashSet.insert(curr->next->val); curr = curr->next; } } /** * 2.2 Kth to Last Element * O(n) algorithm with two pointers */ Node* kthToLast(Node *head, unsigned int k) { Node *curr = head, *ret = nullptr; unsigned int count = 0; while(curr) { count++; if(count >= k) { if(count == k) ret = head; ret = ret->next; } curr = curr->next; } return ret; } /** * 2.3 Delete Middle Node * O(1) time algorithm. Not really * deleting the node, just overwriting. */ void deleteMiddleNode(Node *node) { Node *temp = node->next; node->val = temp->val; node->next = temp->next; delete temp; // No GC in C++ } /** * 2.4 Partition List * O(n) time algo with O(n) extra space * This paritioning is unstable. */ Node* partitionList(Node *head, int pivot) { Node *newHead = head, *newTail = head, *curr=head; while(curr) { Node *temp = curr; if(curr->val < pivot) { curr->next = newHead; newHead = curr; } else { newTail->next = curr; newTail = newTail->next; } curr = temp->next; } newTail->next = nullptr; return newHead; } int main() { return 0; } <commit_msg>syncing ctci.<commit_after>#include <bits/stdc++.h> // using GCC/G++ using namespace std; // linked list node class class Node { public: int val; Node *next; Node(int x) { val = x; next = nullptr; } }; /** * 2.1 Remove Duplicates * O(N^2) time algorithm */ void removeDuplicates(Node *head) { Node *curr = head; while(curr->next) { Node *scout = curr; while(scout->next) { if(scout->next->val == curr->val) { scout->next = scout->next->next; } scout = scout->next; } curr = curr->next; } } /* * Alternate approach with Hash Table/Set * O(n) run time + O(n) extra space */ void removeDuplicatesSet(Node *head) { unordered_set<int> HashSet; Node *curr = head; HashSet.insert(curr->val); while(curr->next) { if(HashSet.find(curr->next->val) != HashSet.end()) curr->next = curr->next->next; else HashSet.insert(curr->next->val); curr = curr->next; } } /** * 2.2 Kth to Last Element * O(n) algorithm with two pointers */ Node* kthToLast(Node *head, unsigned int k) { Node *curr = head, *ret = nullptr; unsigned int count = 0; while(curr) { count++; if(count >= k) { if(count == k) ret = head; ret = ret->next; } curr = curr->next; } return ret; } /** * 2.3 Delete Middle Node * O(1) time algorithm. Not really * deleting the node, just overwriting. */ void deleteMiddleNode(Node *node) { Node *temp = node->next; node->val = temp->val; node->next = temp->next; delete temp; // No GC in C++ } /** * 2.4 Partition List * O(n) time algo with O(n) extra space * This paritioning is unstable. */ Node* partitionList(Node *head, int pivot) { Node *newHead = head, *newTail = head, *curr=head; while(curr) { Node *temp = curr; if(curr->val < pivot) { curr->next = newHead; newHead = curr; } else { newTail->next = curr; newTail = newTail->next; } curr = temp->next; } newTail->next = nullptr; return newHead; } /** * 2.5 Sum Lists * Case 1: Numbers stored in reverse order * O(max(n, m)) iterative algorithm * with O(max(n, m)) extra space */ Node* listSum(Node *a, Node *b) { if(!a) return b; if(!b) return a; Node *newHead, *curr, *curra = a, *currb = b; int carry = 0, temp; while(curra || currb) { temp = (curra ? curra->val : 0) + (currb ? currb->val : 0); curr = new Node(temp%10 + carry); if(!newHead) newHead = curr; carry = temp/10; curr = curr->next; } if(carry > 0) curr = new Node(carry); return newHead; } /** * 2.5 Sum Lists * Case 2: Numbers stored in normal decimal order * */ Node* listSumRec(Node *a, Node *b) { int lena = getLen(a), lenb = getLen(b); } int main() { return 0; } <|endoftext|>
<commit_before>/* * The MIT License * * Copyright 2017-2018 Norwegian University of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FMI4CPP_MODELEXCHANGESLAVE_HPP #define FMI4CPP_MODELEXCHANGESLAVE_HPP #include <memory> #include "ModelExchangeInstance.hpp" #include "FmuSlave.hpp" #include "Solver.hpp" namespace fmi4cpp::fmi2 { class ModelExchangeSlave : public FmuSlave { private: std::unique_ptr<Solver> solver_; std::unique_ptr<ModelExchangeInstance> instance_; std::shared_ptr<CoSimulationModelDescription> csModelDescription; std::vector<fmi2Real > x_; std::vector<fmi2Real > dx_; std::vector<fmi2Real > z_; std::vector<fmi2Real > pz_; fmi2EventInfo eventInfo_; bool eventIteration(); public: ModelExchangeSlave(std::unique_ptr<ModelExchangeInstance> &instance_, std::unique_ptr<Solver> &solver); std::shared_ptr<CoSimulationModelDescription> getModelDescription() const override; fmi2Status doStep(double stepSize) override; fmi2Status cancelStep() override; fmi2Status setupExperiment(double startTime, double stopTime, double tolerance) override; fmi2Status enterInitializationMode() override; fmi2Status exitInitializationMode() override; fmi2Status reset() override; fmi2Status terminate() override; fmi2Status getFMUstate(fmi2FMUstate &state) override; fmi2Status setFMUstate(fmi2FMUstate state) override; fmi2Status freeFMUstate(fmi2FMUstate &state) override; fmi2Status serializeFMUstate(const fmi2FMUstate &state, std::vector<fmi2Byte> &serializedState) override; fmi2Status deSerializeFMUstate(fmi2FMUstate &state, const std::vector<fmi2Byte> &serializedState) override; fmi2Status getDirectionalDerivative(const std::vector<fmi2ValueReference> &vUnkownRef, const std::vector<fmi2ValueReference> &vKnownRef, const std::vector<fmi2Real> &dvKnownRef, std::vector<fmi2Real> &dvUnknownRef) const override; fmi2Status readInteger(fmi2ValueReference vr, fmi2Integer &ref) const override; fmi2Status readInteger(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2Integer> &ref) const override; fmi2Status readReal(fmi2ValueReference vr, fmi2Real &ref) const override; fmi2Status readReal(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2Real> &ref) const override; fmi2Status readString(fmi2ValueReference vr, fmi2String &ref) const override; fmi2Status readString(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2String> &ref) const override; fmi2Status readBoolean(fmi2ValueReference vr, fmi2Boolean &ref) const override; fmi2Status readBoolean(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2Boolean> &ref) const override; fmi2Status writeInteger(fmi2ValueReference vr, fmi2Integer value) override; fmi2Status writeInteger(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2Integer> &values) override; fmi2Status writeReal(fmi2ValueReference vr, fmi2Real value) override; fmi2Status writeReal(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2Real> &values) override; fmi2Status writeString(fmi2ValueReference vr, fmi2String value) override; fmi2Status writeString(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2String> &values) override; fmi2Status writeBoolean(fmi2ValueReference vr, fmi2Boolean value) override; fmi2Status writeBoolean(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2Boolean> &values) override; }; } #endif //FMI4CPP_MODELEXCHANGESLAVE_HPP <commit_msg>cleanup<commit_after>/* * The MIT License * * Copyright 2017-2018 Norwegian University of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FMI4CPP_MODELEXCHANGESLAVE_HPP #define FMI4CPP_MODELEXCHANGESLAVE_HPP #include <memory> #include "ModelExchangeInstance.hpp" #include "FmuSlave.hpp" #include "Solver.hpp" namespace fmi4cpp::fmi2 { class ModelExchangeSlave : public FmuSlave { private: std::unique_ptr<Solver> solver_; std::unique_ptr<ModelExchangeInstance> instance_; std::shared_ptr<CoSimulationModelDescription> csModelDescription; std::vector<fmi2Real > x_; std::vector<fmi2Real > dx_; std::vector<fmi2Real > z_; std::vector<fmi2Real > pz_; fmi2EventInfo eventInfo_; bool eventIteration(); public: ModelExchangeSlave(std::unique_ptr<ModelExchangeInstance> &instance, std::unique_ptr<Solver> &solver); std::shared_ptr<CoSimulationModelDescription> getModelDescription() const override; fmi2Status doStep(double stepSize) override; fmi2Status cancelStep() override; fmi2Status setupExperiment(double startTime, double stopTime, double tolerance) override; fmi2Status enterInitializationMode() override; fmi2Status exitInitializationMode() override; fmi2Status reset() override; fmi2Status terminate() override; fmi2Status getFMUstate(fmi2FMUstate &state) override; fmi2Status setFMUstate(fmi2FMUstate state) override; fmi2Status freeFMUstate(fmi2FMUstate &state) override; fmi2Status serializeFMUstate(const fmi2FMUstate &state, std::vector<fmi2Byte> &serializedState) override; fmi2Status deSerializeFMUstate(fmi2FMUstate &state, const std::vector<fmi2Byte> &serializedState) override; fmi2Status getDirectionalDerivative(const std::vector<fmi2ValueReference> &vUnknownRef, const std::vector<fmi2ValueReference> &vKnownRef, const std::vector<fmi2Real> &dvKnownRef, std::vector<fmi2Real> &dvUnknownRef) const override; fmi2Status readInteger(fmi2ValueReference vr, fmi2Integer &ref) const override; fmi2Status readInteger(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2Integer> &ref) const override; fmi2Status readReal(fmi2ValueReference vr, fmi2Real &ref) const override; fmi2Status readReal(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2Real> &ref) const override; fmi2Status readString(fmi2ValueReference vr, fmi2String &ref) const override; fmi2Status readString(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2String> &ref) const override; fmi2Status readBoolean(fmi2ValueReference vr, fmi2Boolean &ref) const override; fmi2Status readBoolean(const std::vector<fmi2ValueReference> &vr, std::vector<fmi2Boolean> &ref) const override; fmi2Status writeInteger(fmi2ValueReference vr, fmi2Integer value) override; fmi2Status writeInteger(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2Integer> &values) override; fmi2Status writeReal(fmi2ValueReference vr, fmi2Real value) override; fmi2Status writeReal(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2Real> &values) override; fmi2Status writeString(fmi2ValueReference vr, fmi2String value) override; fmi2Status writeString(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2String> &values) override; fmi2Status writeBoolean(fmi2ValueReference vr, fmi2Boolean value) override; fmi2Status writeBoolean(const std::vector<fmi2ValueReference> &vr, const std::vector<fmi2Boolean> &values) override; }; } #endif //FMI4CPP_MODELEXCHANGESLAVE_HPP <|endoftext|>
<commit_before>#ifndef MJOLNIR_BOX_INTEARACTION_BASE #define MJOLNIR_BOX_INTEARACTION_BASE #include <mjolnir/core/ExternalInteractionBase.hpp> namespace mjolnir { /*! @brief Interaction between particle and a region based on their distance. * * @details shapeT represents the shape. It provides a method to calculate * * distance between particle and the shape, force direction, and * * neighbor-list. */ template<typename traitsT, typename potentialT, typename shapeT> class ExternalDistanceInteraction final : public ExternalForceInteractionBase<traitsT> { public: typedef traitsT traits_type; typedef potentialT potential_type; typedef shapeT shape_type; typedef ExternalInteractionBase<traits_type> base_type; typedef typename base_type::real_type real_type; typedef typename base_type::coordinate_type coordinate_type; typedef typename base_type::system_type system_type; typedef typename base_type::boundary_type boundary_type; typedef typename base_type::particle_type particle_type; public: ~ExternalDistanceInteraction() override = default; ExternalDistanceInteraction(shape_type&& shape, potential_type&& pot) : shape_(std::move(shape)), potential_(std::move(pot)) {} /*! @brief initialize spatial partition (e.g. CellList) * * @details before calling `calc_(force|energy)`, this should be called. */ void initialize(const system_type& sys, const real_type dt) override { this->shape_.set_cutoff(potential_.max_cutoff_length()); this->shape_.initialize(sys); this->shape_.update(sys); } /*! @brief update parameters (e.g. dt, temperature, ionic strength, ...) * * @details A method that change system parameters (e.g. Annealing), * * the method is bound to call this function after changing * * parameters. */ void reconstruct(const system_type& sys, const real_type dt) override { this->potential_.update(sys); this->shape_.set_cutoff(potential_.max_cutoff_length()); this->shape_.update(sys); } //! @brief calculate force, update spatial partition (reduce mergin) inside. void calc_force (system_type&) override; //! @brief calculate energy, do nothing else. real_type calc_energy(system_type const&) const override; std::string name() const noexcept {return "ExternalDistance";} private: shape_type shape_; potential_type potential_; }; template<typename traitsT, typename potT, typename spaceT> void ExternalDistanceInteraction<traitsT, potT, spaceT>::calc_force( system_type& sys) { this->shape_.update(sys); // update neighbor list... for(std::size_t i : this->shape_.neighbors()) { const real_type dist = this->shape_.calc_distance(sys[i].position, sys.boundary()); const real_type dV = potential_.derivative(i, dist); if(dV == 0.0){continue;} sys[i].force += -dV * shape_.calc_force_direction(sys[i].position, sys.boundary()); } return ; } template<typename traitsT, typename potT, typename spaceT> real_type ExternalDistanceInteraction<traitsT, potT, spaceT>::calc_energy( const system_type& sys) const { real_type E = 0.0; for(std::size_t i : this->shape_.neighbors()) { const real_type d = this->shape_.calc_distance(sys[i].position, sys.boundary()); E += this->potential_.potential(i, d); } return E; } } // mjolnir #endif//MJOLNIR_BOX_INTEARACTION_BASE <commit_msg>refactor members of ExternalDistance<commit_after>#ifndef MJOLNIR_BOX_INTEARACTION_BASE #define MJOLNIR_BOX_INTEARACTION_BASE #include <mjolnir/core/ExternalInteractionBase.hpp> namespace mjolnir { /*! @brief Interaction between particle and a region based on their distance. * * @details shapeT represents the shape. It provides a method to calculate * * distance between particle and the shape, force direction, and * * neighbor-list. */ template<typename traitsT, typename potentialT, typename shapeT> class ExternalDistanceInteraction final : public ExternalForceInteractionBase<traitsT> { public: typedef traitsT traits_type; typedef potentialT potential_type; typedef shapeT shape_type; typedef ExternalInteractionBase<traits_type> base_type; typedef typename base_type::real_type real_type; typedef typename base_type::coordinate_type coordinate_type; typedef typename base_type::system_type system_type; typedef typename base_type::boundary_type boundary_type; typedef typename base_type::particle_type particle_type; public: ExternalDistanceInteraction(shape_type&& shape, potential_type&& pot) : shape_(std::move(shape)), potential_(std::move(pot)) {} ~ExternalDistanceInteraction() override = default; // calculate force, update spatial partition (reduce mergin) inside. void calc_force (system_type&) override; real_type calc_energy(system_type const&) const override; /*! @brief initialize spatial partition (e.g. CellList) * * @details before calling `calc_(force|energy)`, this should be called. */ void initialize(const system_type& sys, const real_type dt) override { this->potential_.update(sys); // update system parameters this->shape_.set_cutoff(potential_.max_cutoff_length()); this->shape_.initialize(sys); this->shape_.update(sys); } /*! @brief update parameters (e.g. dt, temperature, ionic strength, ...) * * @details A method that change system parameters (e.g. Annealing), * * the method is bound to call this function after changing * * parameters. */ void reconstruct(const system_type& sys, const real_type dt) override { this->potential_.update(sys); // update system parameters this->shape_.reconstruct(sys, this->potential_); } std::string name() const noexcept {return "ExternalDistance";} private: shape_type shape_; potential_type potential_; }; template<typename traitsT, typename potT, typename spaceT> void ExternalDistanceInteraction<traitsT, potT, spaceT>::calc_force( system_type& sys) { this->shape_.update(sys); // update neighbor list... for(std::size_t i : this->shape_.neighbors()) { const auto& ri = sys[i].position; const real_type dist = this->shape_.calc_distance(ri, sys.boundary()); const real_type dV = this->potential_.derivative(i, dist); if(dV == 0.0){continue;} const auto f = shape_.calc_force_direction(ri, sys.boundary()); sys[i].force += -dV * f; } return ; } template<typename traitsT, typename potT, typename spaceT> real_type ExternalDistanceInteraction<traitsT, potT, spaceT>::calc_energy( const system_type& sys) const { real_type E = 0.0; for(std::size_t i : this->shape_.neighbors()) { const auto& ri = sys[i].position; const real_type d = this->shape_.calc_distance(ri, sys.boundary()); E += this->potential_.potential(i, d); } return E; } } // mjolnir #endif//MJOLNIR_BOX_INTEARACTION_BASE <|endoftext|>
<commit_before>#pragma once #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <limits.h> #include "oqpi/platform.hpp" #include "oqpi/error_handling.hpp" #include "oqpi/synchronization/sync_common.hpp" namespace oqpi { //---------------------------------------------------------------------------------------------- // Forward declaration of this platform mutex implementation using mutex_impl = class posix_mutex; //---------------------------------------------------------------------------------------------- class posix_mutex { protected: //------------------------------------------------------------------------------------------ struct mutex_wrapper { ~mutex_wrapper() { pthread_mutex_destroy(&mutex); } pthread_mutex_t mutex; }; protected: //------------------------------------------------------------------------------------------ using native_handle_type = mutex_wrapper*; protected: //------------------------------------------------------------------------------------------ posix_mutex(const std::string &name, sync_object_creation_options creationOption, bool lockImmediately) : handle_(nullptr), name_(name) { if (name_.empty() && creationOption != sync_object_creation_options::open_existing) { // Local mutex. handle_ = new mutex_wrapper; initMutex(false, lockImmediately); } else { // Global mutex. if (!isNameValid(name)) { oqpi_error("the name \"%s\" you provided is not valid for shared memory.", name_.c_str()); return; } // Mode applies only to future accesses of the newly created file. auto mode = S_IRUSR; auto flags = O_CREAT | O_EXCL | O_RDWR; auto fileDescriptor = shm_open(name_.c_str(), flags, mode); // Open existing mutex. if (fileDescriptor == -1 && creationOption != sync_object_creation_options::create_if_nonexistent) { // If O_EXCL and O_CREAT are specified, and a shared memory object with the given name already exists, // an error is returned. // Remove flags (O_EXCL, O_CREAT) and try to open shared memory that already exists. flags &= ~O_CREAT; flags &= ~O_EXCL; while (fileDescriptor == -1) { // Now since if the mode is still S_IRUSR, then shm_open with O_RDWR flags will fail until write permission given (after mutex was initialized). fileDescriptor = shm_open(name_.c_str(), flags, 0); if (fileDescriptor == -1) { if (errno == EACCES) { // If errno == EACCES, then caller does not have write permission on the object. Mutex is currently being initialized. Sleep 10 ms. const auto timeToSleep = timespec{ 0, (long)1e7 }; nanosleep(&timeToSleep, NULL); } else { oqpi_error("shm_open failed with error code %d", errno); oqpi_error("Was not able to properly get handle of global mutex."); return; } } } // Map the object into the caller's address space. handle_ = reinterpret_cast<mutex_wrapper *>(mmap(NULL, sizeof(*handle_), PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0)); if (lockImmediately) { oqpi_verify(lock()); } } // Create new mutex. else if(fileDescriptor != -1 && creationOption != sync_object_creation_options::open_existing) { // Allocate shared memory. if(ftruncate(fileDescriptor, sizeof(mutex_wrapper)) == -1) { oqpi_error("ftruncate() failed with error code %d", errno); } // Map the object into the caller's address space. handle_ = reinterpret_cast<mutex_wrapper *>(mmap(NULL, sizeof(*handle_), PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0)); initMutex(true, lockImmediately); // Now allow for read and write access. fchmod(fileDescriptor, S_IRUSR | S_IWUSR); } else { oqpi_error("Was not able to open or create a posix_mutex with the creation option specified."); } close(fileDescriptor); } } //------------------------------------------------------------------------------------------ ~posix_mutex() { if (handle_ != nullptr) { if (name_.empty()) { // Local mutex. delete handle_; } else { // Global mutex. // Removes any mappings for those entire pages containing any part of the address space of the process starting at handle_. const auto error = munmap(handle_, sizeof(*handle_)); if (error == -1) { oqpi_error("munmap failed with error code %d", errno); } } handle_ = nullptr; } if(!name_.empty()) { // Removes shared memory object name, and, once all processes have unmapped the object, de-allocates and destroys the contents // of the associated memory region. const auto error = shm_unlink(name_.c_str()); if (error == -1) { oqpi_error("munmap failed with error code %d", errno); } name_ = ""; } } //------------------------------------------------------------------------------------------ posix_mutex(posix_mutex &&other) : handle_(other.handle_), name_(other.name_) { other.handle_ = nullptr; other.name_ = ""; } //------------------------------------------------------------------------------------------ posix_mutex &operator=(posix_mutex &&rhs) { if (this != &rhs && !isValid()) { handle_ = rhs.handle_; name_ = rhs.name_; rhs.handle_ = nullptr; rhs.name_ = ""; } return (*this); } protected: //------------------------------------------------------------------------------------------ // User interface native_handle_type getNativeHandle() const { return handle_; } //------------------------------------------------------------------------------------------ bool isValid() const { return handle_ != nullptr; } //------------------------------------------------------------------------------------------ bool lock() { return pthread_mutex_lock(&handle_->mutex) == 0; } //------------------------------------------------------------------------------------------ bool tryLock() { return pthread_mutex_trylock(&handle_->mutex) == 0; } //------------------------------------------------------------------------------------------ template<typename _Rep, typename _Period> bool tryLockFor(const std::chrono::duration<_Rep, _Period> &relTime) { auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(relTime); const auto secs = std::chrono::duration_cast<std::chrono::seconds>(nanoseconds); nanoseconds -= secs; const auto timeout = timespec{secs.count(), nanoseconds.count()}; return pthread_mutex_timedlock(&handle_->mutex, &timeout) == 0; } //------------------------------------------------------------------------------------------ void unlock() { const auto error = pthread_mutex_unlock(&handle_->mutex); if(error != 0) { oqpi_error("pthread_mutex_unlock failed with error number %d", error); } } private: //------------------------------------------------------------------------------------------ void initMutex(bool processShared, bool lockImmediately) { auto attr = pthread_mutexattr_t{}; auto error = pthread_mutexattr_init(&attr); if (error != 0) { oqpi_error("pthread_mutexattr_init failed with error number %d", error); } pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); if (processShared) { pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); } error = pthread_mutex_init(&handle_->mutex, &attr); if (error != 0) { oqpi_error("pthread_mutex_init failed with error number %d", error); } pthread_mutexattr_destroy(&attr); if (lockImmediately) { oqpi_verify(lock()); } } //------------------------------------------------------------------------------------------ bool isNameValid(const std::string &name) const { // Note that name must be in the form of /somename; that is, a null-terminated string of up to NAME_MAX // characters consisting of an initial slash, followed by one or more characters, none of which are slashes. return (name.length() < NAME_MAX && name.length() > 1 && name[0] == '/' && std::find(name.begin() + 1, name.end(), '/') == name.end()); } private: //------------------------------------------------------------------------------------------ // Not copyable posix_mutex(const posix_mutex &) = delete; posix_mutex &operator=(const posix_mutex &) = delete; private: //------------------------------------------------------------------------------------------ native_handle_type handle_; std::string name_; }; } /*oqpi*/ <commit_msg>Reverted this change to master<commit_after>#pragma once #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <limits.h> #include "oqpi/platform.hpp" #include "oqpi/error_handling.hpp" #include "oqpi/synchronization/sync_common.hpp" namespace oqpi { //---------------------------------------------------------------------------------------------- // Forward declaration of this platform mutex implementation using mutex_impl = class posix_mutex; //---------------------------------------------------------------------------------------------- class posix_mutex { protected: //------------------------------------------------------------------------------------------ struct mutex_wrapper { ~mutex_wrapper() { pthread_mutex_destroy(&mutex); } pthread_mutex_t mutex; }; protected: //------------------------------------------------------------------------------------------ using native_handle_type = mutex_wrapper*; protected: //------------------------------------------------------------------------------------------ posix_mutex(const std::string &name, sync_object_creation_options creationOption, bool lockImmediately) : handle_(nullptr), name_(name) { if (name_.empty() && creationOption != sync_object_creation_options::open_existing) { // Local mutex. handle_ = new mutex_wrapper; initMutex(false, lockImmediately); } else { // Global mutex. if (oqpi_failed(isNameValid(name))) { oqpi_error("the name \"%s\" you provided is not valid for shared memory.", name_.c_str()); return; } // Mode applies only to future accesses of the newly created file. auto mode = S_IRUSR; auto flags = O_CREAT | O_EXCL | O_RDWR; auto fileDescriptor = shm_open(name_.c_str(), flags, mode); // Open existing mutex. if (fileDescriptor == -1 && creationOption != sync_object_creation_options::create_if_nonexistent) { // If O_EXCL and O_CREAT are specified, and a shared memory object with the given name already exists, // an error is returned. // Remove flags (O_EXCL, O_CREAT) and try to open shared memory that already exists. flags &= ~O_CREAT; flags &= ~O_EXCL; while (fileDescriptor == -1) { // Now since if the mode is still S_IRUSR, then shm_open with O_RDWR flags will fail until write permission given (after mutex was initialized). fileDescriptor = shm_open(name_.c_str(), flags, 0); if (fileDescriptor == -1) { if (errno == EACCES) { // If errno == EACCES, then caller does not have write permission on the object. Mutex is currently being initialized. Sleep 10 ms. const auto timeToSleep = timespec{ 0, (long)1e7 }; nanosleep(&timeToSleep, NULL); } else { oqpi_error("shm_open failed with error code %d", errno); oqpi_error("Was not able to properly get handle of global mutex."); return; } } } // Map the object into the caller's address space. handle_ = reinterpret_cast<mutex_wrapper *>(mmap(NULL, sizeof(*handle_), PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0)); if (lockImmediately) { oqpi_verify(lock()); } } // Create new mutex. else if(fileDescriptor != -1 && creationOption != sync_object_creation_options::open_existing) { // Allocate shared memory. if(ftruncate(fileDescriptor, sizeof(mutex_wrapper)) == -1) { oqpi_error("ftruncate() failed with error code %d", errno); } // Map the object into the caller's address space. handle_ = reinterpret_cast<mutex_wrapper *>(mmap(NULL, sizeof(*handle_), PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0)); initMutex(true, lockImmediately); // Now allow for read and write access. fchmod(fileDescriptor, S_IRUSR | S_IWUSR); } else { oqpi_error("Was not able to open or create a posix_mutex with the creation option specified."); } close(fileDescriptor); } } //------------------------------------------------------------------------------------------ ~posix_mutex() { if (handle_ != nullptr) { if (name_.empty()) { // Local mutex. delete handle_; } else { // Global mutex. // Removes any mappings for those entire pages containing any part of the address space of the process starting at handle_. const auto error = munmap(handle_, sizeof(*handle_)); if (error == -1) { oqpi_error("munmap failed with error code %d", errno); } } handle_ = nullptr; } if(!name_.empty()) { // Removes shared memory object name, and, once all processes have unmapped the object, de-allocates and destroys the contents // of the associated memory region. const auto error = shm_unlink(name_.c_str()); if (error == -1) { oqpi_error("munmap failed with error code %d", errno); } name_ = ""; } } //------------------------------------------------------------------------------------------ posix_mutex(posix_mutex &&other) : handle_(other.handle_), name_(other.name_) { other.handle_ = nullptr; other.name_ = ""; } //------------------------------------------------------------------------------------------ posix_mutex &operator=(posix_mutex &&rhs) { if (this != &rhs && !isValid()) { handle_ = rhs.handle_; name_ = rhs.name_; rhs.handle_ = nullptr; rhs.name_ = ""; } return (*this); } protected: //------------------------------------------------------------------------------------------ // User interface native_handle_type getNativeHandle() const { return handle_; } //------------------------------------------------------------------------------------------ bool isValid() const { return handle_ != nullptr; } //------------------------------------------------------------------------------------------ bool lock() { return pthread_mutex_lock(&handle_->mutex) == 0; } //------------------------------------------------------------------------------------------ bool tryLock() { return pthread_mutex_trylock(&handle_->mutex) == 0; } //------------------------------------------------------------------------------------------ template<typename _Rep, typename _Period> bool tryLockFor(const std::chrono::duration<_Rep, _Period> &relTime) { auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(relTime); const auto secs = std::chrono::duration_cast<std::chrono::seconds>(nanoseconds); nanoseconds -= secs; const auto timeout = timespec{secs.count(), nanoseconds.count()}; return pthread_mutex_timedlock(&handle_->mutex, &timeout) == 0; } //------------------------------------------------------------------------------------------ void unlock() { const auto error = pthread_mutex_unlock(&handle_->mutex); if(error != 0) { oqpi_error("pthread_mutex_unlock failed with error number %d", error); } } private: //------------------------------------------------------------------------------------------ void initMutex(bool processShared, bool lockImmediately) { auto attr = pthread_mutexattr_t{}; auto error = pthread_mutexattr_init(&attr); if (error != 0) { oqpi_error("pthread_mutexattr_init failed with error number %d", error); } pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); if (processShared) { pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); } error = pthread_mutex_init(&handle_->mutex, &attr); if (error != 0) { oqpi_error("pthread_mutex_init failed with error number %d", error); } pthread_mutexattr_destroy(&attr); if (lockImmediately) { oqpi_verify(lock()); } } //------------------------------------------------------------------------------------------ bool isNameValid(const std::string &name) const { // Note that name must be in the form of /somename; that is, a null-terminated string of up to NAME_MAX // characters consisting of an initial slash, followed by one or more characters, none of which are slashes. return (name.length() < NAME_MAX && name.length() > 1 && name[0] == '/' && std::find(name.begin() + 1, name.end(), '/') == name.end()); } private: //------------------------------------------------------------------------------------------ // Not copyable posix_mutex(const posix_mutex &) = delete; posix_mutex &operator=(const posix_mutex &) = delete; private: //------------------------------------------------------------------------------------------ native_handle_type handle_; std::string name_; }; } /*oqpi*/ <|endoftext|>
<commit_before>#include <config.h> #include "grid_creation.hh" #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/structuredgridfactory.hh> #include <dune/stuff/grid/information.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/multiscale/problems/selector.hh> #include <dune/common/parallel/mpihelper.hh> // Helper struct to make overlap for SPGrid possible // Declared in unnamed namespace to avoid naming conflicts namespace { template< class GridType > class MyGridFactory { typedef typename GridType::ctype ctype; static const int dimworld = GridType::dimensionworld; static const int dim = GridType::dimension; public: static std::shared_ptr<GridType> createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft, const Dune::FieldVector<ctype,dimworld>& upperRight, const Dune::array<unsigned int,dim>& elements, const Dune::array<unsigned int,dim>& /*overlap*/) { // structured grid factory allows overlap only for SPGrid at the moment, hence the following check BOOST_ASSERT_MSG((DSC_CONFIG_GET("msfem.oversampling_layers", 0)==0), "Oversampling may only be used in combination with SPGrid!"); return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements); } }; template< class ct, int dim, Dune::SPRefinementStrategy strategy, class Comm > class MyGridFactory< Dune::SPGrid< ct, dim, strategy, Comm > > { typedef Dune::SPGrid< ct, dim, strategy, Comm > GridType; typedef typename GridType::ctype ctype; static const int dimworld = GridType::dimensionworld; public: static std::shared_ptr<GridType> createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft, const Dune::FieldVector<ctype,dimworld>& upperRight, const Dune::array<unsigned int,dim>& elements, const Dune::array<unsigned int,dim>& overlap) { return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements, overlap); } }; } std::pair<std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>, std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>> Dune::Multiscale::make_grids() { BOOST_ASSERT_MSG(DSC_CONFIG.hasSub("grids"), "Parameter tree needs to have 'grids' subtree!"); const DSC::ExtendedParameterTree gridParameterTree(DSC_CONFIG.sub("grids")); const int dim_world = CommonTraits::GridType::dimensionworld; typedef FieldVector<typename CommonTraits::GridType::ctype, dim_world> CoordType; const auto& gridCorners = Problem::getModelData()->gridCorners(); CoordType lowerLeft = gridCorners.first; CoordType upperRight = gridCorners.second; const auto oversamplingLayers = DSC_CONFIG_GET("msfem.oversampling_layers", 0); std::vector<int> microPerMacro = gridParameterTree.getVector("micro_cells_per_macrocell_dim", 8, dim_world); const std::vector<int> coarse_cells = gridParameterTree.getVector("macro_cells_per_dim", 8, dim_world); array<unsigned int, dim_world> elements; array<unsigned int, dim_world> overCoarse; for (const auto i : DSC::valueRange(dim_world)) { elements[i] = coarse_cells[i]; overCoarse[i] = std::ceil(double(oversamplingLayers)/double(microPerMacro[i])); } auto coarse_gridptr = MyGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements, overCoarse); for (const auto i : DSC::valueRange(dim_world)) { elements[i] = coarse_cells[i] * microPerMacro[i]; } auto fine_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements); // check whether grids match (may not match after load balancing if different refinements in different // spatial directions are used) if (Dune::MPIHelper::getCollectiveCommunication().size()>1) { const auto coarse_dimensions = DSG::dimensions<CommonTraits::GridType>(*coarse_gridptr); const auto fine_dimensions = DSG::dimensions<CommonTraits::GridType>(*fine_gridptr); const auto eps = coarse_dimensions.entity_width.min(); for (const auto i : DSC::valueRange(dim_world)) { const bool match = (std::abs(coarse_dimensions.coord_limits[i].min()-fine_dimensions.coord_limits[i].min()) < eps) && (std::abs(coarse_dimensions.coord_limits[i].max()-fine_dimensions.coord_limits[i].max()) < eps); if (!match) DUNE_THROW(InvalidStateException, "Coarse and fine mesh do not match after load balancing, do \ you use different refinements in different spatial dimensions?"); } } return {coarse_gridptr, fine_gridptr}; } <commit_msg>Use grids without overlap to determine whether fine and coarse match Conflicts: dune/multiscale/common/grid_creation.cc<commit_after>#include <config.h> #include "grid_creation.hh" #include <dune/grid/common/gridenums.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/structuredgridfactory.hh> #include <dune/stuff/grid/information.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/multiscale/problems/selector.hh> #include <dune/common/parallel/mpihelper.hh> // Helper struct to make overlap for SPGrid possible // Declared in unnamed namespace to avoid naming conflicts namespace { template< class GridType > class MyGridFactory { typedef typename GridType::ctype ctype; static const int dimworld = GridType::dimensionworld; static const int dim = GridType::dimension; public: static std::shared_ptr<GridType> createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft, const Dune::FieldVector<ctype,dimworld>& upperRight, const Dune::array<unsigned int,dim>& elements, const Dune::array<unsigned int,dim>& /*overlap*/) { // structured grid factory allows overlap only for SPGrid at the moment, hence the following check BOOST_ASSERT_MSG((DSC_CONFIG_GET("msfem.oversampling_layers", 0)==0), "Oversampling may only be used in combination with SPGrid!"); return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements); } }; template< class ct, int dim, Dune::SPRefinementStrategy strategy, class Comm > class MyGridFactory< Dune::SPGrid< ct, dim, strategy, Comm > > { typedef Dune::SPGrid< ct, dim, strategy, Comm > GridType; typedef typename GridType::ctype ctype; static const int dimworld = GridType::dimensionworld; public: static std::shared_ptr<GridType> createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft, const Dune::FieldVector<ctype,dimworld>& upperRight, const Dune::array<unsigned int,dim>& elements, const Dune::array<unsigned int,dim>& overlap) { return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements, overlap); } }; } std::pair<std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>, std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>> Dune::Multiscale::make_grids() { BOOST_ASSERT_MSG(DSC_CONFIG.hasSub("grids"), "Parameter tree needs to have 'grids' subtree!"); const DSC::ExtendedParameterTree gridParameterTree(DSC_CONFIG.sub("grids")); const int dim_world = CommonTraits::GridType::dimensionworld; typedef FieldVector<typename CommonTraits::GridType::ctype, dim_world> CoordType; const auto& gridCorners = Problem::getModelData()->gridCorners(); CoordType lowerLeft = gridCorners.first; CoordType upperRight = gridCorners.second; const auto oversamplingLayers = DSC_CONFIG_GET("msfem.oversampling_layers", 0); std::vector<int> microPerMacro = gridParameterTree.getVector("micro_cells_per_macrocell_dim", 8, dim_world); const std::vector<int> coarse_cells = gridParameterTree.getVector("macro_cells_per_dim", 8, dim_world); array<unsigned int, dim_world> elements; array<unsigned int, dim_world> overCoarse; for (const auto i : DSC::valueRange(dim_world)) { elements[i] = coarse_cells[i]; overCoarse[i] = std::ceil(double(oversamplingLayers)/double(microPerMacro[i])); } auto coarse_gridptr = MyGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements, overCoarse); for (const auto i : DSC::valueRange(dim_world)) { elements[i] = coarse_cells[i] * microPerMacro[i]; } auto fine_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements); // check whether grids match (may not match after load balancing if different refinements in different // spatial directions are used) if (Dune::MPIHelper::getCollectiveCommunication().size()>1) { typedef CommonTraits::GridType::Partition<PartitionIteratorType::Interior_Partition>::LeafGridView InteriorLeafViewType; const auto coarse_dimensions = DSG::dimensions<InteriorLeafViewType>(coarse_gridptr->leafGridView<PartitionIteratorType::Interior_Partition>()); const auto fine_dimensions = DSG::dimensions<InteriorLeafViewType>(fine_gridptr->leafGridView<PartitionIteratorType::Interior_Partition>()); const auto eps = coarse_dimensions.entity_width.min(); for (const auto i : DSC::valueRange(dim_world)) { const bool match = (std::abs(coarse_dimensions.coord_limits[i].min()-fine_dimensions.coord_limits[i].min()) < eps) && (std::abs(coarse_dimensions.coord_limits[i].max()-fine_dimensions.coord_limits[i].max()) < eps); if (!match) DUNE_THROW(InvalidStateException, "Coarse and fine mesh do not match after load balancing, do \ you use different refinements in different spatial dimensions?"); } } return {coarse_gridptr, fine_gridptr}; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(OS_WIN) #include <windows.h> #endif #include "content/gpu/gpu_watchdog_thread.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/compiler_specific.h" #include "base/process_util.h" #include "base/process.h" #include "build/build_config.h" #include "content/public/common/result_codes.h" namespace { const int64 kCheckPeriodMs = 2000; } // namespace GpuWatchdogThread::GpuWatchdogThread(int timeout) : base::Thread("Watchdog"), watched_message_loop_(MessageLoop::current()), timeout_(base::TimeDelta::FromMilliseconds(timeout)), armed_(false), #if defined(OS_WIN) watched_thread_handle_(0), arm_cpu_time_(), #endif ALLOW_THIS_IN_INITIALIZER_LIST(task_observer_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) { DCHECK(timeout >= 0); #if defined(OS_WIN) // GetCurrentThread returns a pseudo-handle that cannot be used by one thread // to identify another. DuplicateHandle creates a "real" handle that can be // used for this purpose. BOOL result = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &watched_thread_handle_, THREAD_QUERY_INFORMATION, FALSE, 0); DCHECK(result); #endif watched_message_loop_->AddTaskObserver(&task_observer_); } void GpuWatchdogThread::PostAcknowledge() { // Called on the monitored thread. Responds with OnAcknowledge. Cannot use // the method factory. Rely on reference counting instead. message_loop()->PostTask( FROM_HERE, base::Bind(&GpuWatchdogThread::OnAcknowledge, this)); } void GpuWatchdogThread::CheckArmed() { // Acknowledge the watchdog if it has armed itself. The watchdog will not // change its armed state until it is acknowledged. if (armed()) { PostAcknowledge(); } } void GpuWatchdogThread::Init() { // Schedule the first check. OnCheck(); } void GpuWatchdogThread::CleanUp() { weak_factory_.InvalidateWeakPtrs(); } GpuWatchdogThread::GpuWatchdogTaskObserver::GpuWatchdogTaskObserver( GpuWatchdogThread* watchdog) : watchdog_(watchdog) { } GpuWatchdogThread::GpuWatchdogTaskObserver::~GpuWatchdogTaskObserver() { } void GpuWatchdogThread::GpuWatchdogTaskObserver::WillProcessTask( base::TimeTicks time_posted) { watchdog_->CheckArmed(); } void GpuWatchdogThread::GpuWatchdogTaskObserver::DidProcessTask( base::TimeTicks time_posted) { watchdog_->CheckArmed(); } GpuWatchdogThread::~GpuWatchdogThread() { // Verify that the thread was explicitly stopped. If the thread is stopped // implicitly by the destructor, CleanUp() will not be called. DCHECK(!weak_factory_.HasWeakPtrs()); #if defined(OS_WIN) CloseHandle(watched_thread_handle_); #endif watched_message_loop_->RemoveTaskObserver(&task_observer_); } void GpuWatchdogThread::OnAcknowledge() { // The check has already been acknowledged and another has already been // scheduled by a previous call to OnAcknowledge. It is normal for a // watched thread to see armed_ being true multiple times before // the OnAcknowledge task is run on the watchdog thread. if (!armed_) return; // Revoke any pending hang termination. weak_factory_.InvalidateWeakPtrs(); armed_ = false; // The monitored thread has responded. Post a task to check it again. message_loop()->PostDelayedTask( FROM_HERE, base::Bind(&GpuWatchdogThread::OnCheck, weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(kCheckPeriodMs)); } void GpuWatchdogThread::OnCheck() { if (armed_) return; // Must set armed before posting the task. This task might be the only task // that will activate the TaskObserver on the watched thread and it must not // miss the false -> true transition. armed_ = true; #if defined(OS_WIN) arm_cpu_time_ = GetWatchedThreadTime(); #endif arm_absolute_time_ = base::Time::Now(); // Post a task to the monitored thread that does nothing but wake up the // TaskObserver. Any other tasks that are pending on the watched thread will // also wake up the observer. This simply ensures there is at least one. watched_message_loop_->PostTask( FROM_HERE, base::Bind(&base::DoNothing)); // Post a task to the watchdog thread to exit if the monitored thread does // not respond in time. message_loop()->PostDelayedTask( FROM_HERE, base::Bind( &GpuWatchdogThread::DeliberatelyTerminateToRecoverFromHang, weak_factory_.GetWeakPtr()), timeout_); } // Use the --disable-gpu-watchdog command line switch to disable this. void GpuWatchdogThread::DeliberatelyTerminateToRecoverFromHang() { #if defined(OS_WIN) // Defer termination until a certain amount of CPU time has elapsed on the // watched thread. base::TimeDelta time_since_arm = GetWatchedThreadTime() - arm_cpu_time_; if (time_since_arm < timeout_) { message_loop()->PostDelayedTask( FROM_HERE, base::Bind( &GpuWatchdogThread::DeliberatelyTerminateToRecoverFromHang, weak_factory_.GetWeakPtr()), timeout_ - time_since_arm); return; } #endif // If the watchdog woke up significantly behind schedule, disarm and reset // the watchdog check. This is to prevent the watchdog thread from terminating // when a machine wakes up from sleep or hibernation, which would otherwise // appear to be a hang. if (base::Time::Now() - arm_absolute_time_ > timeout_ * 2) { armed_ = false; OnCheck(); return; } // For minimal developer annoyance, don't keep terminating. You need to skip // the call to base::Process::Terminate below in a debugger for this to be // useful. static bool terminated = false; if (terminated) return; #if defined(OS_WIN) if (IsDebuggerPresent()) return; #endif LOG(ERROR) << "The GPU process hung. Terminating after " << timeout_.InMilliseconds() << " ms."; // Deliberately crash the process to make a crash dump. *((volatile int*)0) = 0x1337; terminated = true; } #if defined(OS_WIN) base::TimeDelta GpuWatchdogThread::GetWatchedThreadTime() { FILETIME creation_time; FILETIME exit_time; FILETIME user_time; FILETIME kernel_time; BOOL result = GetThreadTimes(watched_thread_handle_, &creation_time, &exit_time, &kernel_time, &user_time); DCHECK(result); ULARGE_INTEGER user_time64; user_time64.HighPart = user_time.dwHighDateTime; user_time64.LowPart = user_time.dwLowDateTime; ULARGE_INTEGER kernel_time64; kernel_time64.HighPart = kernel_time.dwHighDateTime; kernel_time64.LowPart = kernel_time.dwLowDateTime; // Time is reported in units of 100 nanoseconds. Kernel and user time are // summed to deal with to kinds of hangs. One is where the GPU process is // stuck in user level, never calling into the kernel and kernel time is // not increasing. The other is where either the kernel hangs and never // returns to user level or where user level code // calls into kernel level repeatedly, giving up its quanta before it is // tracked, for example a loop that repeatedly Sleeps. return base::TimeDelta::FromMilliseconds(static_cast<int64>( (user_time64.QuadPart + kernel_time64.QuadPart) / 10000)); } #endif <commit_msg>Revert 160526 - Crash GPU process on watchdog timeout.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(OS_WIN) #include <windows.h> #endif #include "content/gpu/gpu_watchdog_thread.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/compiler_specific.h" #include "base/process_util.h" #include "base/process.h" #include "build/build_config.h" #include "content/public/common/result_codes.h" namespace { const int64 kCheckPeriodMs = 2000; } // namespace GpuWatchdogThread::GpuWatchdogThread(int timeout) : base::Thread("Watchdog"), watched_message_loop_(MessageLoop::current()), timeout_(base::TimeDelta::FromMilliseconds(timeout)), armed_(false), #if defined(OS_WIN) watched_thread_handle_(0), arm_cpu_time_(), #endif ALLOW_THIS_IN_INITIALIZER_LIST(task_observer_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) { DCHECK(timeout >= 0); #if defined(OS_WIN) // GetCurrentThread returns a pseudo-handle that cannot be used by one thread // to identify another. DuplicateHandle creates a "real" handle that can be // used for this purpose. BOOL result = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &watched_thread_handle_, THREAD_QUERY_INFORMATION, FALSE, 0); DCHECK(result); #endif watched_message_loop_->AddTaskObserver(&task_observer_); } void GpuWatchdogThread::PostAcknowledge() { // Called on the monitored thread. Responds with OnAcknowledge. Cannot use // the method factory. Rely on reference counting instead. message_loop()->PostTask( FROM_HERE, base::Bind(&GpuWatchdogThread::OnAcknowledge, this)); } void GpuWatchdogThread::CheckArmed() { // Acknowledge the watchdog if it has armed itself. The watchdog will not // change its armed state until it is acknowledged. if (armed()) { PostAcknowledge(); } } void GpuWatchdogThread::Init() { // Schedule the first check. OnCheck(); } void GpuWatchdogThread::CleanUp() { weak_factory_.InvalidateWeakPtrs(); } GpuWatchdogThread::GpuWatchdogTaskObserver::GpuWatchdogTaskObserver( GpuWatchdogThread* watchdog) : watchdog_(watchdog) { } GpuWatchdogThread::GpuWatchdogTaskObserver::~GpuWatchdogTaskObserver() { } void GpuWatchdogThread::GpuWatchdogTaskObserver::WillProcessTask( base::TimeTicks time_posted) { watchdog_->CheckArmed(); } void GpuWatchdogThread::GpuWatchdogTaskObserver::DidProcessTask( base::TimeTicks time_posted) { watchdog_->CheckArmed(); } GpuWatchdogThread::~GpuWatchdogThread() { // Verify that the thread was explicitly stopped. If the thread is stopped // implicitly by the destructor, CleanUp() will not be called. DCHECK(!weak_factory_.HasWeakPtrs()); #if defined(OS_WIN) CloseHandle(watched_thread_handle_); #endif watched_message_loop_->RemoveTaskObserver(&task_observer_); } void GpuWatchdogThread::OnAcknowledge() { // The check has already been acknowledged and another has already been // scheduled by a previous call to OnAcknowledge. It is normal for a // watched thread to see armed_ being true multiple times before // the OnAcknowledge task is run on the watchdog thread. if (!armed_) return; // Revoke any pending hang termination. weak_factory_.InvalidateWeakPtrs(); armed_ = false; // The monitored thread has responded. Post a task to check it again. message_loop()->PostDelayedTask( FROM_HERE, base::Bind(&GpuWatchdogThread::OnCheck, weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(kCheckPeriodMs)); } void GpuWatchdogThread::OnCheck() { if (armed_) return; // Must set armed before posting the task. This task might be the only task // that will activate the TaskObserver on the watched thread and it must not // miss the false -> true transition. armed_ = true; #if defined(OS_WIN) arm_cpu_time_ = GetWatchedThreadTime(); #endif arm_absolute_time_ = base::Time::Now(); // Post a task to the monitored thread that does nothing but wake up the // TaskObserver. Any other tasks that are pending on the watched thread will // also wake up the observer. This simply ensures there is at least one. watched_message_loop_->PostTask( FROM_HERE, base::Bind(&base::DoNothing)); // Post a task to the watchdog thread to exit if the monitored thread does // not respond in time. message_loop()->PostDelayedTask( FROM_HERE, base::Bind( &GpuWatchdogThread::DeliberatelyTerminateToRecoverFromHang, weak_factory_.GetWeakPtr()), timeout_); } // Use the --disable-gpu-watchdog command line switch to disable this. void GpuWatchdogThread::DeliberatelyTerminateToRecoverFromHang() { #if defined(OS_WIN) // Defer termination until a certain amount of CPU time has elapsed on the // watched thread. base::TimeDelta time_since_arm = GetWatchedThreadTime() - arm_cpu_time_; if (time_since_arm < timeout_) { message_loop()->PostDelayedTask( FROM_HERE, base::Bind( &GpuWatchdogThread::DeliberatelyTerminateToRecoverFromHang, weak_factory_.GetWeakPtr()), timeout_ - time_since_arm); return; } #endif // If the watchdog woke up significantly behind schedule, disarm and reset // the watchdog check. This is to prevent the watchdog thread from terminating // when a machine wakes up from sleep or hibernation, which would otherwise // appear to be a hang. if (base::Time::Now() - arm_absolute_time_ > timeout_ * 2) { armed_ = false; OnCheck(); return; } // For minimal developer annoyance, don't keep terminating. You need to skip // the call to base::Process::Terminate below in a debugger for this to be // useful. static bool terminated = false; if (terminated) return; #if defined(OS_WIN) if (IsDebuggerPresent()) return; #endif LOG(ERROR) << "The GPU process hung. Terminating after " << timeout_.InMilliseconds() << " ms."; base::Process current_process(base::GetCurrentProcessHandle()); current_process.Terminate(content::RESULT_CODE_HUNG); terminated = true; } #if defined(OS_WIN) base::TimeDelta GpuWatchdogThread::GetWatchedThreadTime() { FILETIME creation_time; FILETIME exit_time; FILETIME user_time; FILETIME kernel_time; BOOL result = GetThreadTimes(watched_thread_handle_, &creation_time, &exit_time, &kernel_time, &user_time); DCHECK(result); ULARGE_INTEGER user_time64; user_time64.HighPart = user_time.dwHighDateTime; user_time64.LowPart = user_time.dwLowDateTime; ULARGE_INTEGER kernel_time64; kernel_time64.HighPart = kernel_time.dwHighDateTime; kernel_time64.LowPart = kernel_time.dwLowDateTime; // Time is reported in units of 100 nanoseconds. Kernel and user time are // summed to deal with to kinds of hangs. One is where the GPU process is // stuck in user level, never calling into the kernel and kernel time is // not increasing. The other is where either the kernel hangs and never // returns to user level or where user level code // calls into kernel level repeatedly, giving up its quanta before it is // tracked, for example a loop that repeatedly Sleeps. return base::TimeDelta::FromMilliseconds(static_cast<int64>( (user_time64.QuadPart + kernel_time64.QuadPart) / 10000)); } #endif <|endoftext|>
<commit_before>/** * This file is part of Slideshow. * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com> * * Slideshow is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Slideshow is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "SwitchState.h" #include "TransitionState.h" #include "VideoState.h" #include "ViewState.h" #include "exception.h" #include "Log.h" #include <cstring> State* SwitchState::action(bool &flip){ if ( !browser() ){ return new ViewState(this); } /* get next slide */ slide_context_t slide = next_slide(); struct autofree_t { autofree_t(slide_context_t& s): s(s){} ~autofree_t(){ free(s.filename); free(s.assembler); } slide_context_t& s; }; autofree_t container(slide); if ( !(slide.filename && slide.assembler) ){ /* The current queue is empty, load a blank screen instead of keeping the * current slide. It makes more sense that the screen goes blank when removing * all the slides from the queue. */ Log::warning("Kernel: Queue is empty\n"); gfx()->load_image(NULL); /* blank screen */ return new TransitionState(this); } /* @todo make something factory-like */ if ( strcmp("image", slide.assembler) == 0 || strcmp("text", slide.assembler) == 0 ){ Log::debug("Kernel: Switching to image \"%s\"\n", slide.filename); try { gfx()->load_image( slide.filename ); } catch ( exception& e ) { Log::warning("Kernel: Failed to load image '%s': %s\n", slide.filename, e.what()); return new ViewState(this); } return new TransitionState(this); } else if ( strcmp("video", slide.assembler) == 0 ){ Log::debug("Kernel: Playing video \"%s\"\n", slide.filename); return new VideoState(this, slide.filename); } else { Log::warning("Unhandled assembler \"%s\" for \"%s\"\n", slide.assembler, slide.filename); return new ViewState(this); } } <commit_msg>this is useful enough, should be at verbose level<commit_after>/** * This file is part of Slideshow. * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com> * * Slideshow is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Slideshow is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "SwitchState.h" #include "TransitionState.h" #include "VideoState.h" #include "ViewState.h" #include "exception.h" #include "Log.h" #include <cstring> State* SwitchState::action(bool &flip){ if ( !browser() ){ return new ViewState(this); } /* get next slide */ slide_context_t slide = next_slide(); struct autofree_t { autofree_t(slide_context_t& s): s(s){} ~autofree_t(){ free(s.filename); free(s.assembler); } slide_context_t& s; }; autofree_t container(slide); if ( !(slide.filename && slide.assembler) ){ /* The current queue is empty, load a blank screen instead of keeping the * current slide. It makes more sense that the screen goes blank when removing * all the slides from the queue. */ Log::warning("Kernel: Queue is empty\n"); gfx()->load_image(NULL); /* blank screen */ return new TransitionState(this); } /* @todo make something factory-like */ if ( strcmp("image", slide.assembler) == 0 || strcmp("text", slide.assembler) == 0 ){ Log::verbose("Kernel: Switching to image \"%s\"\n", slide.filename); try { gfx()->load_image( slide.filename ); } catch ( exception& e ) { Log::warning("Kernel: Failed to load image '%s': %s\n", slide.filename, e.what()); return new ViewState(this); } return new TransitionState(this); } else if ( strcmp("video", slide.assembler) == 0 ){ Log::debug("Kernel: Playing video \"%s\"\n", slide.filename); return new VideoState(this, slide.filename); } else { Log::warning("Unhandled assembler \"%s\" for \"%s\"\n", slide.assembler, slide.filename); return new ViewState(this); } } <|endoftext|>
<commit_before>#include <QtWidgets/QApplication> #include <canrawloggermodel.h> #include <datamodeltypes/canrawdata.h> #define CATCH_CONFIG_RUNNER #include "log.h" #include <QSignalSpy> #include <catch.hpp> #include <fakeit.hpp> std::shared_ptr<spdlog::logger> kDefaultLogger; // needed for QSignalSpy cause according to qtbug 49623 comments // automatic detection of types is "flawed" in moc Q_DECLARE_METATYPE(QCanBusFrame); TEST_CASE("Test basic functionality", "[canrawloggerModel]") { using namespace fakeit; CanRawLoggerModel canrawloggerModel; CHECK(canrawloggerModel.caption() == "CanRawLogger"); CHECK(canrawloggerModel.name() == "CanRawLogger"); CHECK(canrawloggerModel.resizable() == false); CHECK(canrawloggerModel.hasSeparateThread() == false); CHECK(dynamic_cast<CanRawLoggerModel*>(canrawloggerModel.clone().get()) != nullptr); CHECK(dynamic_cast<QLabel*>(canrawloggerModel.embeddedWidget()) != nullptr); } TEST_CASE("painterDelegate", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; CHECK(canrawloggerModel.painterDelegate() != nullptr); } TEST_CASE("nPorts", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; CHECK(canrawloggerModel.nPorts(QtNodes::PortType::Out) == 0); CHECK(canrawloggerModel.nPorts(QtNodes::PortType::In) == 1); } TEST_CASE("dataType", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; NodeDataType ndt; ndt = canrawloggerModel.dataType(QtNodes::PortType::Out, 0); CHECK(ndt.id == ""); CHECK(ndt.name == ""); ndt = canrawloggerModel.dataType(QtNodes::PortType::In, 0); CHECK(ndt.id == "rawframe"); CHECK(ndt.name == "RAW"); ndt = canrawloggerModel.dataType(QtNodes::PortType::In, 1); CHECK(ndt.id == ""); CHECK(ndt.name == ""); } TEST_CASE("outData", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; auto nd = canrawloggerModel.outData(0); CHECK(!nd); } TEST_CASE("setInData", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; QCanBusFrame frame; QSignalSpy rxSpy(&canrawloggerModel, &CanRawLoggerModel::frameReceived); QSignalSpy txSpy(&canrawloggerModel, &CanRawLoggerModel::frameSent); auto&& rxData = std::make_shared<CanRawData>(frame, Direction::RX, true); auto&& txData = std::make_shared<CanRawData>(frame, Direction::TX, true); auto&& errData = std::make_shared<CanRawData>(frame, static_cast<Direction>(11), true); canrawloggerModel.setInData(rxData, 1); canrawloggerModel.setInData(txData, 1); canrawloggerModel.setInData(errData, 1); canrawloggerModel.setInData({}, 1); CHECK(txSpy.count() == 1); CHECK(rxSpy.count() == 1); } int main(int argc, char* argv[]) { bool haveDebug = std::getenv("CDS_DEBUG") != nullptr; kDefaultLogger = spdlog::stdout_color_mt("cds"); if (haveDebug) { kDefaultLogger->set_level(spdlog::level::debug); } cds_debug("Staring unit tests"); qRegisterMetaType<QCanBusFrame>(); // required by QSignalSpy QApplication a(argc, argv); // QApplication must exist when contructing QWidgets TODO check QTest return Catch::Session().run(argc, argv); } <commit_msg>Fix typos<commit_after>#include <QtWidgets/QApplication> #include <canrawloggermodel.h> #include <datamodeltypes/canrawdata.h> #define CATCH_CONFIG_RUNNER #include "log.h" #include <QSignalSpy> #include <catch.hpp> #include <fakeit.hpp> std::shared_ptr<spdlog::logger> kDefaultLogger; // needed for QSignalSpy cause according to qtbug 49623 comments // automatic detection of types is "flawed" in moc Q_DECLARE_METATYPE(QCanBusFrame); TEST_CASE("Test basic functionality", "[canrawloggerModel]") { using namespace fakeit; CanRawLoggerModel canrawloggerModel; CHECK(canrawloggerModel.caption() == "CanRawLogger"); CHECK(canrawloggerModel.name() == "CanRawLogger"); CHECK(canrawloggerModel.resizable() == false); CHECK(canrawloggerModel.hasSeparateThread() == false); CHECK(dynamic_cast<CanRawLoggerModel*>(canrawloggerModel.clone().get()) != nullptr); CHECK(dynamic_cast<QLabel*>(canrawloggerModel.embeddedWidget()) != nullptr); } TEST_CASE("painterDelegate", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; CHECK(canrawloggerModel.painterDelegate() != nullptr); } TEST_CASE("nPorts", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; CHECK(canrawloggerModel.nPorts(QtNodes::PortType::Out) == 0); CHECK(canrawloggerModel.nPorts(QtNodes::PortType::In) == 1); } TEST_CASE("dataType", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; NodeDataType ndt; ndt = canrawloggerModel.dataType(QtNodes::PortType::Out, 0); CHECK(ndt.id == ""); CHECK(ndt.name == ""); ndt = canrawloggerModel.dataType(QtNodes::PortType::In, 0); CHECK(ndt.id == "rawframe"); CHECK(ndt.name == "RAW"); ndt = canrawloggerModel.dataType(QtNodes::PortType::In, 1); CHECK(ndt.id == ""); CHECK(ndt.name == ""); } TEST_CASE("outData", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; auto nd = canrawloggerModel.outData(0); CHECK(!nd); } TEST_CASE("setInData", "[canrawloggerModel]") { CanRawLoggerModel canrawloggerModel; QCanBusFrame frame; QSignalSpy rxSpy(&canrawloggerModel, &CanRawLoggerModel::frameReceived); QSignalSpy txSpy(&canrawloggerModel, &CanRawLoggerModel::frameSent); auto&& rxData = std::make_shared<CanRawData>(frame, Direction::RX, true); auto&& txData = std::make_shared<CanRawData>(frame, Direction::TX, true); auto&& errData = std::make_shared<CanRawData>(frame, static_cast<Direction>(11), true); canrawloggerModel.setInData(rxData, 1); canrawloggerModel.setInData(txData, 1); canrawloggerModel.setInData(errData, 1); canrawloggerModel.setInData({}, 1); CHECK(txSpy.count() == 1); CHECK(rxSpy.count() == 1); } int main(int argc, char* argv[]) { bool haveDebug = std::getenv("CDS_DEBUG") != nullptr; kDefaultLogger = spdlog::stdout_color_mt("cds"); if (haveDebug) { kDefaultLogger->set_level(spdlog::level::debug); } cds_debug("Starting unit tests"); qRegisterMetaType<QCanBusFrame>(); // required by QSignalSpy QApplication a(argc, argv); // QApplication must exist when constructing QWidgets TODO check QTest return Catch::Session().run(argc, argv); } <|endoftext|>
<commit_before>#include <boost/foreach.hpp> #include <sstream> #include "Hypothesis.h" #include "Manager.h" #include "ActiveChart.h" #include "TargetPhraseImpl.h" #include "../System.h" #include "../Scores.h" #include "../InputPathBase.h" #include "../FF/StatefulFeatureFunction.h" using namespace std; namespace Moses2 { namespace SCFG { Hypothesis *Hypothesis::Create(MemPool &pool, Manager &mgr) { // ++g_numHypos; Hypothesis *ret; //ret = new (pool.Allocate<Hypothesis>()) Hypothesis(pool, mgr.system); Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle(); ret = static_cast<Hypothesis*>(recycler.Get()); if (ret) { // got new hypo from recycler. Do nothing } else { ret = new (pool.Allocate<Hypothesis>()) Hypothesis(pool, mgr.system); //cerr << "Hypothesis=" << sizeof(Hypothesis) << " " << ret << endl; recycler.Keep(ret); } return ret; } Hypothesis::Hypothesis(MemPool &pool, const System &system) :HypothesisBase(pool, system) ,m_prevHypos(pool) { } void Hypothesis::Init(SCFG::Manager &mgr, const SCFG::InputPath &path, const SCFG::SymbolBind &symbolBind, const SCFG::TargetPhraseImpl &tp, const Vector<size_t> &prevHyposIndices) { m_mgr = &mgr; m_targetPhrase = &tp; m_path = &path; m_symbolBind = &symbolBind; m_scores->Reset(mgr.system); m_scores->PlusEquals(mgr.system, GetTargetPhrase().GetScores()); //cerr << "tp=" << tp << endl; //cerr << "symbolBind=" << symbolBind << endl; //cerr << endl; m_prevHypos.resize(symbolBind.numNT); size_t currInd = 0; for (size_t i = 0; i < symbolBind.coll.size(); ++i) { const SymbolBindElement &ele = symbolBind.coll[i]; //cerr << "ele=" << ele.word->isNonTerminal << " " << ele.hypos << endl; if (ele.hypos) { const Hypotheses &sortedHypos = *ele.hypos; size_t prevHyposInd = prevHyposIndices[currInd]; assert(prevHyposInd < sortedHypos.size()); const Hypothesis *prevHypo = static_cast<const SCFG::Hypothesis*>(sortedHypos[prevHyposInd]); m_prevHypos[currInd] = prevHypo; m_scores->PlusEquals(mgr.system, prevHypo->GetScores()); ++currInd; } } } SCORE Hypothesis::GetFutureScore() const { return GetScores().GetTotalScore(); } void Hypothesis::EvaluateWhenApplied() { const std::vector<const StatefulFeatureFunction*> &sfffs = GetManager().system.featureFunctions.GetStatefulFeatureFunctions(); BOOST_FOREACH(const StatefulFeatureFunction *sfff, sfffs){ EvaluateWhenApplied(*sfff); } //cerr << *this << endl; } void Hypothesis::EvaluateWhenApplied(const StatefulFeatureFunction &sfff) { const SCFG::Manager &mgr = static_cast<const SCFG::Manager&>(GetManager()); size_t statefulInd = sfff.GetStatefulInd(); FFState *thisState = m_ffStates[statefulInd]; sfff.EvaluateWhenApplied(mgr, *this, statefulInd, GetScores(), *thisState); } void Hypothesis::OutputToStream(std::ostream &out) const { const SCFG::TargetPhraseImpl &tp = GetTargetPhrase(); //cerr << "tp=" << tp.Debug(m_mgr->system) << endl; for (size_t pos = 0; pos < tp.GetSize(); ++pos) { const SCFG::Word &word = tp[pos]; //cerr << "word " << pos << "=" << word << endl; if (word.isNonTerminal) { //cerr << "is nt" << endl; // non-term. fill out with prev hypo size_t nonTermInd = tp.GetAlignNonTerm().GetNonTermIndexMap()[pos]; const Hypothesis *prevHypo = m_prevHypos[nonTermInd]; prevHypo->OutputToStream(out); } else { //cerr << "not nt" << endl; word.OutputToStream(out); out << " "; } } } std::string Hypothesis::Debug(const System &system) const { stringstream out; out << this << flush; out << " RANGE:"; out << m_path->range << " "; out << m_symbolBind->Debug(system) << " "; // score out << " SCORE:" << GetScores().Debug(GetManager().system) << flush; out << m_targetPhrase->Debug(GetManager().system); out << "PREV:"; for (size_t i = 0; i < m_prevHypos.size(); ++i) { const Hypothesis *prevHypo = m_prevHypos[i]; out << prevHypo << prevHypo->GetInputPath().range << "(" << prevHypo->GetFutureScore() << ") "; } out << endl; /* // recursive for (size_t i = 0; i < m_prevHypos.size(); ++i) { const Hypothesis *prevHypo = m_prevHypos[i]; out << prevHypo->Debug(GetManager().system) << " "; } */ return out.str(); } void Hypothesis::OutputTransOpt(std::ostream &out) const { out << GetInputPath().range << " " << "score=" << GetScores().GetTotalScore() << " " << GetTargetPhrase().Debug(m_mgr->system) << endl; BOOST_FOREACH(const Hypothesis *prevHypo, m_prevHypos) { prevHypo->OutputTransOpt(out); } } } // namespaces } <commit_msg>get ready for placeholders in scfg<commit_after>#include <boost/foreach.hpp> #include <sstream> #include "Hypothesis.h" #include "Manager.h" #include "ActiveChart.h" #include "TargetPhraseImpl.h" #include "../System.h" #include "../Scores.h" #include "../InputPathBase.h" #include "../FF/StatefulFeatureFunction.h" using namespace std; namespace Moses2 { namespace SCFG { Hypothesis *Hypothesis::Create(MemPool &pool, Manager &mgr) { // ++g_numHypos; Hypothesis *ret; //ret = new (pool.Allocate<Hypothesis>()) Hypothesis(pool, mgr.system); Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle(); ret = static_cast<Hypothesis*>(recycler.Get()); if (ret) { // got new hypo from recycler. Do nothing } else { ret = new (pool.Allocate<Hypothesis>()) Hypothesis(pool, mgr.system); //cerr << "Hypothesis=" << sizeof(Hypothesis) << " " << ret << endl; recycler.Keep(ret); } return ret; } Hypothesis::Hypothesis(MemPool &pool, const System &system) :HypothesisBase(pool, system) ,m_prevHypos(pool) { } void Hypothesis::Init(SCFG::Manager &mgr, const SCFG::InputPath &path, const SCFG::SymbolBind &symbolBind, const SCFG::TargetPhraseImpl &tp, const Vector<size_t> &prevHyposIndices) { m_mgr = &mgr; m_targetPhrase = &tp; m_path = &path; m_symbolBind = &symbolBind; m_scores->Reset(mgr.system); m_scores->PlusEquals(mgr.system, GetTargetPhrase().GetScores()); //cerr << "tp=" << tp << endl; //cerr << "symbolBind=" << symbolBind << endl; //cerr << endl; m_prevHypos.resize(symbolBind.numNT); size_t currInd = 0; for (size_t i = 0; i < symbolBind.coll.size(); ++i) { const SymbolBindElement &ele = symbolBind.coll[i]; //cerr << "ele=" << ele.word->isNonTerminal << " " << ele.hypos << endl; if (ele.hypos) { const Hypotheses &sortedHypos = *ele.hypos; size_t prevHyposInd = prevHyposIndices[currInd]; assert(prevHyposInd < sortedHypos.size()); const Hypothesis *prevHypo = static_cast<const SCFG::Hypothesis*>(sortedHypos[prevHyposInd]); m_prevHypos[currInd] = prevHypo; m_scores->PlusEquals(mgr.system, prevHypo->GetScores()); ++currInd; } } } SCORE Hypothesis::GetFutureScore() const { return GetScores().GetTotalScore(); } void Hypothesis::EvaluateWhenApplied() { const std::vector<const StatefulFeatureFunction*> &sfffs = GetManager().system.featureFunctions.GetStatefulFeatureFunctions(); BOOST_FOREACH(const StatefulFeatureFunction *sfff, sfffs){ EvaluateWhenApplied(*sfff); } //cerr << *this << endl; } void Hypothesis::EvaluateWhenApplied(const StatefulFeatureFunction &sfff) { const SCFG::Manager &mgr = static_cast<const SCFG::Manager&>(GetManager()); size_t statefulInd = sfff.GetStatefulInd(); FFState *thisState = m_ffStates[statefulInd]; sfff.EvaluateWhenApplied(mgr, *this, statefulInd, GetScores(), *thisState); } void Hypothesis::OutputToStream(std::ostream &out) const { const SCFG::TargetPhraseImpl &tp = GetTargetPhrase(); //cerr << "tp=" << tp.Debug(m_mgr->system) << endl; for (size_t targetPos = 0; targetPos < tp.GetSize(); ++targetPos) { const SCFG::Word &word = tp[targetPos]; //cerr << "word " << targetPos << "=" << word << endl; if (word.isNonTerminal) { //cerr << "is nt" << endl; // non-term. fill out with prev hypo size_t nonTermInd = tp.GetAlignNonTerm().GetNonTermIndexMap()[targetPos]; const Hypothesis *prevHypo = m_prevHypos[nonTermInd]; prevHypo->OutputToStream(out); } else { //cerr << "not nt" << endl; word.OutputToStream(out); out << " "; } } } std::string Hypothesis::Debug(const System &system) const { stringstream out; out << this << flush; out << " RANGE:"; out << m_path->range << " "; out << m_symbolBind->Debug(system) << " "; // score out << " SCORE:" << GetScores().Debug(GetManager().system) << flush; out << m_targetPhrase->Debug(GetManager().system); out << "PREV:"; for (size_t i = 0; i < m_prevHypos.size(); ++i) { const Hypothesis *prevHypo = m_prevHypos[i]; out << prevHypo << prevHypo->GetInputPath().range << "(" << prevHypo->GetFutureScore() << ") "; } out << endl; /* // recursive for (size_t i = 0; i < m_prevHypos.size(); ++i) { const Hypothesis *prevHypo = m_prevHypos[i]; out << prevHypo->Debug(GetManager().system) << " "; } */ return out.str(); } void Hypothesis::OutputTransOpt(std::ostream &out) const { out << GetInputPath().range << " " << "score=" << GetScores().GetTotalScore() << " " << GetTargetPhrase().Debug(m_mgr->system) << endl; BOOST_FOREACH(const Hypothesis *prevHypo, m_prevHypos) { prevHypo->OutputTransOpt(out); } } } // namespaces } <|endoftext|>
<commit_before>/** * Class CCopasiContainer * * This class is the is used to group CCopasiObjects logically. It inself is * an object. Contained objects are still globally accessible. * * Copyright Stefan Hoops 2002 */ #include "copasi.h" #include "CCopasiObjectName.h" #include "CCopasiContainer.h" #include "utilities/CCopasiVector.h" CCopasiContainer * CCopasiContainer::Root = NULL; void CCopasiContainer::init() {CCopasiContainer::Root = new CCopasiContainer();} CCopasiContainer::CCopasiContainer() {} CCopasiContainer::CCopasiContainer(const std::string & name, const CCopasiContainer * pParent, const std::string & type, const unsigned C_INT32 & flag): CCopasiObject(name, pParent, type, flag | CCopasiObject::Container) {} CCopasiContainer::CCopasiContainer(const CCopasiContainer & src, const CCopasiContainer * pParent): CCopasiObject(src, pParent), mObjects() {} CCopasiContainer::~CCopasiContainer() { std::map< const std::string, CCopasiObject * >::iterator it = mObjects.begin(); std::map< const std::string, CCopasiObject * >::iterator end = mObjects.end(); for (; it != end; it++) if (it->second->getObjectParent() == this) { it->second->setObjectParent(NULL); pdelete(it->second); } } const std::string CCopasiContainer::getObjectUniqueName() const { // return getObjectName(); return CCopasiObject::getObjectUniqueName(); } const CCopasiObject * CCopasiContainer::getObject(const CCopasiObjectName & cn) const { if (cn == "") return this; std::string Name = cn.getObjectName(); std::string Type = cn.getObjectType(); if (getObjectName() == Name && getObjectType() == Type) return getObject(cn.getRemainder()); std::map< const std::string, CCopasiObject * >::const_iterator it = mObjects.find(Name); if (it == mObjects.end()) return NULL; if (it->second->getObjectType() != Type) return NULL; const CCopasiObject * pObject = NULL; if (it->second->isNameVector() || it->second->isVector()) { pObject = it->second->getObject("[" + cn.getName() + "]"); if (it->second->getObjectType() == "Reference" || !pObject) return pObject; else return pObject->getObject(cn.getRemainder()); } if (it->second->isContainer()) return it->second->getObject(cn.getRemainder()); if (it->second->isMatrix()) { pObject = it->second->getObject("[" + cn.getName() + "]" + "[" + cn.getName(1) + "]"); if (it->second->getObjectType() == "Reference" || !pObject) return pObject; else return pObject->getObject(cn.getRemainder()); } if (it->second->isReference()) return it->second; return it->second->getObject(cn.getRemainder()); } const std::map< const std::string, CCopasiObject * > & CCopasiContainer::getObjects() const { return mObjects; } void CCopasiContainer::initObjects() {} bool CCopasiContainer::add(CCopasiObject * pObject) { if (mObjects.find(pObject->getObjectName()) != mObjects.end()) return false; mObjects[pObject->getObjectName()] = pObject; return true; } bool CCopasiContainer::remove(CCopasiObject * pObject) { std::map< const std::string, CCopasiObject * >::iterator it = mObjects.find(pObject->getObjectName()); if (it == mObjects.end()) return false; mObjects.erase(it); return false; } #ifdef XXXX CCopasiContainer CRootContainer::mRoot("Root"); CRootContainer::CRootContainer() {} CRootContainer::~CRootContainer() {} CCopasiContainer & CRootContainer::ref() {return mRoot;} #endif // XXXX <commit_msg>Fix the problem of failure to create a new copasi model,<commit_after>/** * Class CCopasiContainer * * This class is the is used to group CCopasiObjects logically. It inself is * an object. Contained objects are still globally accessible. * * Copyright Stefan Hoops 2002 */ #include "copasi.h" #include "CCopasiObjectName.h" #include "CCopasiContainer.h" #include "utilities/CCopasiVector.h" CCopasiContainer * CCopasiContainer::Root = NULL; void CCopasiContainer::init() {CCopasiContainer::Root = new CCopasiContainer();} CCopasiContainer::CCopasiContainer() : CCopasiObject("Root", NULL, "CN", CCopasiObject::Container) {} CCopasiContainer::CCopasiContainer(const std::string & name, const CCopasiContainer * pParent, const std::string & type, const unsigned C_INT32 & flag): CCopasiObject(name, pParent, type, flag | CCopasiObject::Container) {} CCopasiContainer::CCopasiContainer(const CCopasiContainer & src, const CCopasiContainer * pParent): CCopasiObject(src, pParent), mObjects() {} CCopasiContainer::~CCopasiContainer() { std::map< const std::string, CCopasiObject * >::iterator it = mObjects.begin(); std::map< const std::string, CCopasiObject * >::iterator end = mObjects.end(); for (; it != end; it++) if (it->second->getObjectParent() == this) { it->second->setObjectParent(NULL); pdelete(it->second); } } const std::string CCopasiContainer::getObjectUniqueName() const { // return getObjectName(); return CCopasiObject::getObjectUniqueName(); } const CCopasiObject * CCopasiContainer::getObject(const CCopasiObjectName & cn) const { if (cn == "") return this; std::string Name = cn.getObjectName(); std::string Type = cn.getObjectType(); if (getObjectName() == Name && getObjectType() == Type) return getObject(cn.getRemainder()); std::map< const std::string, CCopasiObject * >::const_iterator it = mObjects.find(Name); if (it == mObjects.end()) return NULL; if (it->second->getObjectType() != Type) return NULL; const CCopasiObject * pObject = NULL; if (it->second->isNameVector() || it->second->isVector()) { pObject = it->second->getObject("[" + cn.getName() + "]"); if (it->second->getObjectType() == "Reference" || !pObject) return pObject; else return pObject->getObject(cn.getRemainder()); } if (it->second->isContainer()) return it->second->getObject(cn.getRemainder()); if (it->second->isMatrix()) { pObject = it->second->getObject("[" + cn.getName() + "]" + "[" + cn.getName(1) + "]"); if (it->second->getObjectType() == "Reference" || !pObject) return pObject; else return pObject->getObject(cn.getRemainder()); } if (it->second->isReference()) return it->second; return it->second->getObject(cn.getRemainder()); } const std::map< const std::string, CCopasiObject * > & CCopasiContainer::getObjects() const { return mObjects; } void CCopasiContainer::initObjects() {} bool CCopasiContainer::add(CCopasiObject * pObject) { if (mObjects.find(pObject->getObjectName()) != mObjects.end()) return false; mObjects[pObject->getObjectName()] = pObject; return true; } bool CCopasiContainer::remove(CCopasiObject * pObject) { std::map< const std::string, CCopasiObject * >::iterator it = mObjects.find(pObject->getObjectName()); if (it == mObjects.end()) return false; mObjects.erase(it); return false; } #ifdef XXXX CCopasiContainer CRootContainer::mRoot("Root"); CRootContainer::CRootContainer() {} CRootContainer::~CRootContainer() {} CCopasiContainer & CRootContainer::ref() {return mRoot;} #endif // XXXX <|endoftext|>
<commit_before>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2002 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /*! \file CCopasiContainer.cpp \brief Implementation file of class CCopasiContainer */ /** * Class CCopasiContainer * * This class is the is used to group CCopasiObjects logically. It inself is * an object. Contained objects are still globally accessible. * * Copyright Stefan Hoops 2002 */ #include "copasi/copasi.h" #include "copasi/report/CCopasiObjectName.h" #include "copasi/report/CCopasiContainer.h" #include "copasi/report/CCopasiObjectReference.h" #include "copasi/report/CCopasiStaticString.h" #include "copasi/report/CCopasiTimer.h" #include "copasi/utilities/CCopasiVector.h" #include "copasi/utilities/CUnit.h" #include "copasi/report/CCopasiRootContainer.h" CCopasiContainer::CObjectMap::iterator::iterator(): mpMap(NULL), mNameEnd(true), mName(), mObjectEnd(true), mObject() {} CCopasiContainer::CObjectMap::iterator::iterator(const CObjectMap & map, const bool & begin): mpMap(&map), mNameEnd(true), mName(), mObjectEnd(true), mObject() { if (mpMap != NULL && mpMap->begin() != mpMap->end()) { if (begin) { mNameEnd = false; mName = const_cast< std::map< std::string, std::set< CCopasiObject * > > * >(mpMap)->begin(); if (!mName->second.empty()) { mObjectEnd = false; mObject = mName->second.begin(); } } } } CCopasiContainer::CObjectMap::iterator::iterator(const CCopasiContainer::CObjectMap::iterator & src): mpMap(src.mpMap), mNameEnd(src.mNameEnd), mName(src.mName), mObjectEnd(src.mObjectEnd), mObject(src.mObject) {} CCopasiContainer::CObjectMap::iterator::~iterator() {} CCopasiObject * CCopasiContainer::CObjectMap::iterator::operator*() const { if (!mObjectEnd) return *mObject; return NULL; } CCopasiObject * CCopasiContainer::CObjectMap::iterator::operator->() const { if (!mObjectEnd) return *mObject; return NULL; } CCopasiContainer::CObjectMap::iterator & CCopasiContainer::CObjectMap::iterator::operator++() { mObject++; if (mObject == mName->second.end() || mObjectEnd) { if (mName != mpMap->end() && !mNameEnd) { mName++; } if (mName != mpMap->end() && !mNameEnd) { mObjectEnd = false; mObject = mName->second.begin(); } else { mNameEnd = true; mObjectEnd = true; } } return *this; } CCopasiContainer::CObjectMap::iterator CCopasiContainer::CObjectMap::iterator::operator++(int) { iterator Current(*this); operator++(); return Current; } bool CCopasiContainer::CObjectMap::iterator::operator != (const iterator & rhs) const { return (mpMap != rhs.mpMap || mNameEnd != rhs.mNameEnd || mObjectEnd != rhs.mObjectEnd || (!mNameEnd && mName != rhs.mName) || (!mObjectEnd && mObject != rhs.mObject)); } CCopasiContainer::CObjectMap::const_iterator::const_iterator(): mpMap(NULL), mNameEnd(true), mName(), mObjectEnd(true), mObject() {} CCopasiContainer::CObjectMap::const_iterator::const_iterator(const CObjectMap & map, const bool & begin): mpMap(&map), mNameEnd(true), mName(), mObjectEnd(true), mObject() { if (mpMap != NULL && mpMap->begin() != mpMap->end()) { if (begin) { mNameEnd = false; mName = const_cast< std::map< std::string, std::set< CCopasiObject * > > * >(mpMap)->begin(); if (!mName->second.empty()) { mObjectEnd = false; mObject = mName->second.begin(); } } } } CCopasiContainer::CObjectMap::const_iterator::const_iterator(const CCopasiContainer::CObjectMap::const_iterator & src): mpMap(src.mpMap), mNameEnd(src.mNameEnd), mName(src.mName), mObjectEnd(src.mObjectEnd), mObject(src.mObject) {} CCopasiContainer::CObjectMap::const_iterator::~const_iterator() {} CCopasiObject * CCopasiContainer::CObjectMap::const_iterator::operator*() const { return *mObject; } CCopasiObject * CCopasiContainer::CObjectMap::const_iterator::operator->() const { return *mObject; } CCopasiContainer::CObjectMap::const_iterator & CCopasiContainer::CObjectMap::const_iterator::operator++() { mObject++; if (mObject == mName->second.end() || mObjectEnd) { if (mName != mpMap->end() && !mNameEnd) { mName++; } if (mName != mpMap->end() && !mNameEnd) { mObjectEnd = false; mObject = mName->second.begin(); } else { mNameEnd = true; mObjectEnd = true; } } return *this; } CCopasiContainer::CObjectMap::const_iterator CCopasiContainer::CObjectMap::const_iterator::operator++(int) { const_iterator Current(*this); operator++(); return Current; } bool CCopasiContainer::CObjectMap::const_iterator::operator != (const const_iterator & rhs) const { return (mpMap != rhs.mpMap || mNameEnd != rhs.mNameEnd || mObjectEnd != rhs.mObjectEnd || (!mNameEnd && mName != rhs.mName) || (!mObjectEnd && mObject != rhs.mObject)); } CCopasiContainer::CObjectMap::CObjectMap(): CCopasiContainer::CObjectMap::data() {} CCopasiContainer::CObjectMap::CObjectMap(const CCopasiContainer::CObjectMap & src): CCopasiContainer::CObjectMap::data(src) {} CCopasiContainer::CObjectMap::~CObjectMap() {} std::pair< std::set< CCopasiObject * >::iterator, bool > CCopasiContainer::CObjectMap::insert(CCopasiObject * pObject) { if (pObject == NULL) { return std::make_pair(std::set< CCopasiObject * >::iterator(), false); } std::map< std::string, std::set< CCopasiObject * > >::iterator itMap = data::find(pObject->getObjectName()); if (itMap == data::end()) { itMap = data::insert(std::make_pair(pObject->getObjectName(), std::set< CCopasiObject * >())).first; } return itMap->second.insert(pObject); } bool CCopasiContainer::CObjectMap::erase(CCopasiObject * pObject) { if (pObject == NULL) return false; std::map< std::string, std::set< CCopasiObject * > >::iterator itMap = data::find(pObject->getObjectName()); if (itMap != data::end()) { bool success = (itMap->second.erase(pObject) > 0); if (itMap->second.empty()) { data::erase(itMap); } return success; } return false; } void CCopasiContainer::CObjectMap::clear() { data::clear(); } bool CCopasiContainer::CObjectMap::contains(CCopasiObject * pObject) const { if (pObject == NULL) return false; std::map< std::string, std::set< CCopasiObject * > >::const_iterator itMap = data::find(pObject->getObjectName()); if (itMap != data::end()) { return (itMap->second.find(pObject) != itMap->second.end()); } return false; } std::pair< std::set< CCopasiObject * >::const_iterator, std::set< CCopasiObject * >::const_iterator > CCopasiContainer::CObjectMap::equal_range(const std::string & name) const { std::map< std::string, std::set< CCopasiObject * > >::const_iterator itMap = data::find(name); if (itMap != data::end()) { return std::make_pair(itMap->second.begin(), itMap->second.end()); } return std::make_pair(std::set< CCopasiObject * >::iterator(), std::set< CCopasiObject * >::iterator()); } CCopasiContainer::CObjectMap::iterator CCopasiContainer::CObjectMap::begin() { return iterator(*this, true); } CCopasiContainer::CObjectMap::iterator CCopasiContainer::CObjectMap::end() { return iterator(*this, false); } CCopasiContainer::CObjectMap::const_iterator CCopasiContainer::CObjectMap::begin() const { return const_iterator(*this, true); } CCopasiContainer::CObjectMap::const_iterator CCopasiContainer::CObjectMap::end() const { return const_iterator(*this, false); } const CObjectInterface::ContainerList CCopasiContainer::EmptyList; CCopasiContainer::CCopasiContainer() : CCopasiObject(), mObjects() {addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));} CCopasiContainer::CCopasiContainer(const std::string & name, const CCopasiContainer * pParent, const std::string & type, const unsigned C_INT32 & flag): CCopasiObject(name, pParent, type, flag | CCopasiObject::Container), mObjects() {addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));} CCopasiContainer::CCopasiContainer(const CCopasiContainer & src, const CCopasiContainer * pParent): CCopasiObject(src, pParent), mObjects() {addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));} CCopasiContainer::~CCopasiContainer() { objectMap::iterator it = mObjects.begin(); objectMap::iterator end = mObjects.end(); for (; it != end; ++it) if (*it != NULL && (*it)->getObjectParent() == this) { (*it)->setObjectParent(NULL); if (*it != NULL) delete(*it); } } const CObjectInterface * CCopasiContainer::getObject(const CCopasiObjectName & cn) const { if (cn == "") { if (isRoot()) return NULL; else return this; } if (cn == "Property=DisplayName") { return CCopasiObject::getObject(cn); } std::string Name = cn.getObjectName(); std::string Type = cn.getObjectType(); if (getObjectName() == Name && getObjectType() == Type) return getObject(cn.getRemainder()); //check if the first part of the cn matches one of the children (by name and type) objectMap::range range = mObjects.equal_range(Name); while (range.first != range.second && (*range.first)->getObjectType() != Type) ++range.first; if (range.first == range.second) //not found in the list of children { if (Type == "String") return new CCopasiStaticString(Name, this); else if (Type == "Separator") return new CCopasiReportSeparator(Name, this); else return NULL; } const CObjectInterface * pObject = NULL; if ((*range.first)->isNameVector() || (*range.first)->isVector()) { if (cn.getElementName(0, false) == "") return *range.first; pObject = (*range.first)->getObject("[" + cn.getElementName(0, false) + "]"); if ((*range.first)->getObjectType() == "Reference" || !pObject || cn.getRemainder() == "") return pObject; else return pObject->getObject(cn.getRemainder()); } //handle objects where the array flag is set. Currently this applies to the //CArrayAnnotation object. Since this is also a container, we have to do this //before handling general containers. if ((*range.first)->isArray()) { //we need to call the getObject() method of the child array with the //remainder of the cn, with the indices in square brackets, or with an empty string //if there are no indices there could still be a remainder (since the array can also be //a container) if (cn.getElementName(0, false) == "") //no indices return (*range.first)->getObject(cn.getRemainder()); return (*range.first)->getObject(cn); } //handle generic containers. if ((*range.first)->isContainer()) return (*range.first)->getObject(cn.getRemainder()); if ((*range.first)->isMatrix()) { if (cn.getElementName(0, false) == "") return *range.first; pObject = (*range.first)->getObject("[" + cn.getElementName(0, false) + "]" + //TODO really? "[" + cn.getElementName(1, false) + "]"); if ((*range.first)->getObjectType() == "Reference" || !pObject) return pObject; else return pObject->getObject(cn.getRemainder()); } return (*range.first)->getObject(cn.getRemainder()); } const CCopasiContainer::objectMap & CCopasiContainer::getObjects() const {return mObjects;} const CCopasiObject * CCopasiContainer::getValueObject() const { void * ptr = getValuePointer(); if (ptr == NULL) return NULL; objectMap::const_iterator it = mObjects.begin(); objectMap::const_iterator end = mObjects.end(); for (; it != end; ++it) if (ptr == (*it)->getValuePointer()) return *it; return NULL; } void CCopasiContainer::initObjects() {} bool CCopasiContainer::add(CCopasiObject * pObject, const bool & adopt) { if (pObject == NULL) { return false; } /* We check whether we are already containing that object. */ if (mObjects.contains(pObject)) return false; /* This object is not contained, so we can add it. */ mObjects.insert(pObject); if (adopt) pObject->setObjectParent(this); return true; } bool CCopasiContainer::remove(CCopasiObject * pObject) { return mObjects.erase(pObject); } // virtual const std::string CCopasiContainer::getUnits() const {return "?";} // virtual std::string CCopasiContainer::getChildObjectUnits(const CCopasiObject * /* pObject */) const {return "?";} <commit_msg>Fixed Bug 2291. Assured that equal_range always returns a pair of iterators which can be properly compared.<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2002 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /*! \file CCopasiContainer.cpp \brief Implementation file of class CCopasiContainer */ /** * Class CCopasiContainer * * This class is the is used to group CCopasiObjects logically. It inself is * an object. Contained objects are still globally accessible. * * Copyright Stefan Hoops 2002 */ #include "copasi/copasi.h" #include "copasi/report/CCopasiObjectName.h" #include "copasi/report/CCopasiContainer.h" #include "copasi/report/CCopasiObjectReference.h" #include "copasi/report/CCopasiStaticString.h" #include "copasi/report/CCopasiTimer.h" #include "copasi/utilities/CCopasiVector.h" #include "copasi/utilities/CUnit.h" #include "copasi/report/CCopasiRootContainer.h" CCopasiContainer::CObjectMap::iterator::iterator(): mpMap(NULL), mNameEnd(true), mName(), mObjectEnd(true), mObject() {} CCopasiContainer::CObjectMap::iterator::iterator(const CObjectMap & map, const bool & begin): mpMap(&map), mNameEnd(true), mName(), mObjectEnd(true), mObject() { if (mpMap != NULL && mpMap->begin() != mpMap->end()) { if (begin) { mNameEnd = false; mName = const_cast< std::map< std::string, std::set< CCopasiObject * > > * >(mpMap)->begin(); if (!mName->second.empty()) { mObjectEnd = false; mObject = mName->second.begin(); } } } } CCopasiContainer::CObjectMap::iterator::iterator(const CCopasiContainer::CObjectMap::iterator & src): mpMap(src.mpMap), mNameEnd(src.mNameEnd), mName(src.mName), mObjectEnd(src.mObjectEnd), mObject(src.mObject) {} CCopasiContainer::CObjectMap::iterator::~iterator() {} CCopasiObject * CCopasiContainer::CObjectMap::iterator::operator*() const { if (!mObjectEnd) return *mObject; return NULL; } CCopasiObject * CCopasiContainer::CObjectMap::iterator::operator->() const { if (!mObjectEnd) return *mObject; return NULL; } CCopasiContainer::CObjectMap::iterator & CCopasiContainer::CObjectMap::iterator::operator++() { mObject++; if (mObject == mName->second.end() || mObjectEnd) { if (mName != mpMap->end() && !mNameEnd) { mName++; } if (mName != mpMap->end() && !mNameEnd) { mObjectEnd = false; mObject = mName->second.begin(); } else { mNameEnd = true; mObjectEnd = true; } } return *this; } CCopasiContainer::CObjectMap::iterator CCopasiContainer::CObjectMap::iterator::operator++(int) { iterator Current(*this); operator++(); return Current; } bool CCopasiContainer::CObjectMap::iterator::operator != (const iterator & rhs) const { return (mpMap != rhs.mpMap || mNameEnd != rhs.mNameEnd || mObjectEnd != rhs.mObjectEnd || (!mNameEnd && mName != rhs.mName) || (!mObjectEnd && mObject != rhs.mObject)); } CCopasiContainer::CObjectMap::const_iterator::const_iterator(): mpMap(NULL), mNameEnd(true), mName(), mObjectEnd(true), mObject() {} CCopasiContainer::CObjectMap::const_iterator::const_iterator(const CObjectMap & map, const bool & begin): mpMap(&map), mNameEnd(true), mName(), mObjectEnd(true), mObject() { if (mpMap != NULL && mpMap->begin() != mpMap->end()) { if (begin) { mNameEnd = false; mName = const_cast< std::map< std::string, std::set< CCopasiObject * > > * >(mpMap)->begin(); if (!mName->second.empty()) { mObjectEnd = false; mObject = mName->second.begin(); } } } } CCopasiContainer::CObjectMap::const_iterator::const_iterator(const CCopasiContainer::CObjectMap::const_iterator & src): mpMap(src.mpMap), mNameEnd(src.mNameEnd), mName(src.mName), mObjectEnd(src.mObjectEnd), mObject(src.mObject) {} CCopasiContainer::CObjectMap::const_iterator::~const_iterator() {} CCopasiObject * CCopasiContainer::CObjectMap::const_iterator::operator*() const { return *mObject; } CCopasiObject * CCopasiContainer::CObjectMap::const_iterator::operator->() const { return *mObject; } CCopasiContainer::CObjectMap::const_iterator & CCopasiContainer::CObjectMap::const_iterator::operator++() { mObject++; if (mObject == mName->second.end() || mObjectEnd) { if (mName != mpMap->end() && !mNameEnd) { mName++; } if (mName != mpMap->end() && !mNameEnd) { mObjectEnd = false; mObject = mName->second.begin(); } else { mNameEnd = true; mObjectEnd = true; } } return *this; } CCopasiContainer::CObjectMap::const_iterator CCopasiContainer::CObjectMap::const_iterator::operator++(int) { const_iterator Current(*this); operator++(); return Current; } bool CCopasiContainer::CObjectMap::const_iterator::operator != (const const_iterator & rhs) const { return (mpMap != rhs.mpMap || mNameEnd != rhs.mNameEnd || mObjectEnd != rhs.mObjectEnd || (!mNameEnd && mName != rhs.mName) || (!mObjectEnd && mObject != rhs.mObject)); } CCopasiContainer::CObjectMap::CObjectMap(): CCopasiContainer::CObjectMap::data() {} CCopasiContainer::CObjectMap::CObjectMap(const CCopasiContainer::CObjectMap & src): CCopasiContainer::CObjectMap::data(src) {} CCopasiContainer::CObjectMap::~CObjectMap() {} std::pair< std::set< CCopasiObject * >::iterator, bool > CCopasiContainer::CObjectMap::insert(CCopasiObject * pObject) { if (pObject == NULL) { return std::make_pair(std::set< CCopasiObject * >::iterator(), false); } std::map< std::string, std::set< CCopasiObject * > >::iterator itMap = data::find(pObject->getObjectName()); if (itMap == data::end()) { itMap = data::insert(std::make_pair(pObject->getObjectName(), std::set< CCopasiObject * >())).first; } return itMap->second.insert(pObject); } bool CCopasiContainer::CObjectMap::erase(CCopasiObject * pObject) { if (pObject == NULL) return false; std::map< std::string, std::set< CCopasiObject * > >::iterator itMap = data::find(pObject->getObjectName()); if (itMap != data::end()) { bool success = (itMap->second.erase(pObject) > 0); if (itMap->second.empty()) { data::erase(itMap); } return success; } return false; } void CCopasiContainer::CObjectMap::clear() { data::clear(); } bool CCopasiContainer::CObjectMap::contains(CCopasiObject * pObject) const { if (pObject == NULL) return false; std::map< std::string, std::set< CCopasiObject * > >::const_iterator itMap = data::find(pObject->getObjectName()); if (itMap != data::end()) { return (itMap->second.find(pObject) != itMap->second.end()); } return false; } std::pair< std::set< CCopasiObject * >::const_iterator, std::set< CCopasiObject * >::const_iterator > CCopasiContainer::CObjectMap::equal_range(const std::string & name) const { std::map< std::string, std::set< CCopasiObject * > >::const_iterator itMap = data::find(name); if (itMap != data::end()) { return std::make_pair(itMap->second.begin(), itMap->second.end()); } static std::set< CCopasiObject * > Set; return std::make_pair(Set.begin(), Set.end()); } CCopasiContainer::CObjectMap::iterator CCopasiContainer::CObjectMap::begin() { return iterator(*this, true); } CCopasiContainer::CObjectMap::iterator CCopasiContainer::CObjectMap::end() { return iterator(*this, false); } CCopasiContainer::CObjectMap::const_iterator CCopasiContainer::CObjectMap::begin() const { return const_iterator(*this, true); } CCopasiContainer::CObjectMap::const_iterator CCopasiContainer::CObjectMap::end() const { return const_iterator(*this, false); } const CObjectInterface::ContainerList CCopasiContainer::EmptyList; CCopasiContainer::CCopasiContainer() : CCopasiObject(), mObjects() {addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));} CCopasiContainer::CCopasiContainer(const std::string & name, const CCopasiContainer * pParent, const std::string & type, const unsigned C_INT32 & flag): CCopasiObject(name, pParent, type, flag | CCopasiObject::Container), mObjects() {addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));} CCopasiContainer::CCopasiContainer(const CCopasiContainer & src, const CCopasiContainer * pParent): CCopasiObject(src, pParent), mObjects() {addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));} CCopasiContainer::~CCopasiContainer() { objectMap::iterator it = mObjects.begin(); objectMap::iterator end = mObjects.end(); for (; it != end; ++it) if (*it != NULL && (*it)->getObjectParent() == this) { (*it)->setObjectParent(NULL); if (*it != NULL) delete(*it); } } const CObjectInterface * CCopasiContainer::getObject(const CCopasiObjectName & cn) const { if (cn == "") { if (isRoot()) return NULL; else return this; } if (cn == "Property=DisplayName") { return CCopasiObject::getObject(cn); } std::string Name = cn.getObjectName(); std::string Type = cn.getObjectType(); if (getObjectName() == Name && getObjectType() == Type) return getObject(cn.getRemainder()); //check if the first part of the cn matches one of the children (by name and type) objectMap::range range = mObjects.equal_range(Name); while (range.first != range.second && (*range.first)->getObjectType() != Type) ++range.first; if (range.first == range.second) //not found in the list of children { if (Type == "String") return new CCopasiStaticString(Name, this); else if (Type == "Separator") return new CCopasiReportSeparator(Name, this); else return NULL; } const CObjectInterface * pObject = NULL; if ((*range.first)->isNameVector() || (*range.first)->isVector()) { if (cn.getElementName(0, false) == "") return *range.first; pObject = (*range.first)->getObject("[" + cn.getElementName(0, false) + "]"); if ((*range.first)->getObjectType() == "Reference" || !pObject || cn.getRemainder() == "") return pObject; else return pObject->getObject(cn.getRemainder()); } //handle objects where the array flag is set. Currently this applies to the //CArrayAnnotation object. Since this is also a container, we have to do this //before handling general containers. if ((*range.first)->isArray()) { //we need to call the getObject() method of the child array with the //remainder of the cn, with the indices in square brackets, or with an empty string //if there are no indices there could still be a remainder (since the array can also be //a container) if (cn.getElementName(0, false) == "") //no indices return (*range.first)->getObject(cn.getRemainder()); return (*range.first)->getObject(cn); } //handle generic containers. if ((*range.first)->isContainer()) return (*range.first)->getObject(cn.getRemainder()); if ((*range.first)->isMatrix()) { if (cn.getElementName(0, false) == "") return *range.first; pObject = (*range.first)->getObject("[" + cn.getElementName(0, false) + "]" + //TODO really? "[" + cn.getElementName(1, false) + "]"); if ((*range.first)->getObjectType() == "Reference" || !pObject) return pObject; else return pObject->getObject(cn.getRemainder()); } return (*range.first)->getObject(cn.getRemainder()); } const CCopasiContainer::objectMap & CCopasiContainer::getObjects() const {return mObjects;} const CCopasiObject * CCopasiContainer::getValueObject() const { void * ptr = getValuePointer(); if (ptr == NULL) return NULL; objectMap::const_iterator it = mObjects.begin(); objectMap::const_iterator end = mObjects.end(); for (; it != end; ++it) if (ptr == (*it)->getValuePointer()) return *it; return NULL; } void CCopasiContainer::initObjects() {} bool CCopasiContainer::add(CCopasiObject * pObject, const bool & adopt) { if (pObject == NULL) { return false; } /* We check whether we are already containing that object. */ if (mObjects.contains(pObject)) return false; /* This object is not contained, so we can add it. */ mObjects.insert(pObject); if (adopt) pObject->setObjectParent(this); return true; } bool CCopasiContainer::remove(CCopasiObject * pObject) { return mObjects.erase(pObject); } // virtual const std::string CCopasiContainer::getUnits() const {return "?";} // virtual std::string CCopasiContainer::getChildObjectUnits(const CCopasiObject * /* pObject */) const {return "?";} <|endoftext|>
<commit_before>// Compile with // g++ perfanalysis.cpp -o perfanalyis -std=c++14 -Wall -O3 #include <algorithm> #include <cstring> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <vector> using namespace std; struct StrTok { string& s; size_t pos; bool done; void advance() { while (pos < s.size() && s[pos] == ' ') { ++pos; } done = pos >= s.size(); } StrTok(string& t) : s(t), pos(0), done(false) { advance(); } const char* get() { if (done) { return nullptr; } auto p = s.find(' ', pos); if (p == string::npos) { done = true; return s.c_str() + pos; } s[p] = 0; auto ret = s.c_str() + pos; pos = p + 1; advance(); return ret; } }; struct Event { string threadName; int tid; string cpu; double startTime; double duration; string name; string inbrackets; bool isRet; Event(string& line) : isRet(false) { StrTok tok(line); const char* p = tok.get(); const char* q; if (p != nullptr) { threadName = p; p = tok.get(); tid = strtol(p, nullptr, 10); p = tok.get(); cpu = p; p = tok.get(); startTime = strtod(p, nullptr); p = tok.get(); name = p; name.pop_back(); q = tok.get(); if (strcmp(q, "cs:") == 0) { return; } if (name.compare(0, 14, "probe_arangod:") == 0) { name = name.substr(14); } auto l = name.size(); if (l >= 3 && name[l-1] == 't' && name[l-2] == 'e' && name[l-3] == 'R') { isRet = true; name.pop_back(); name.pop_back(); name.pop_back(); } inbrackets = q; } } bool empty() { return name.empty(); } string id() { return to_string(tid) + name; } string pretty() { return to_string(duration) + " " + name + " " + to_string(startTime); } bool operator<(Event const& other) { if (name < other.name) { return true; } else if (name > other.name) { return false; } else { return duration < other.duration; } } }; int main(int /*argc*/, char* /*argv*/ []) { unordered_map<string, unique_ptr<Event>> table; vector<unique_ptr<Event>> list; string line; while (getline(cin, line)) { auto event = make_unique<Event>(line); if (!event->empty()) { string id = event->id(); // insert to table if it is not a function return if (!event->isRet) { auto it = table.find(id); if (it != table.end()) { //cout << "Alarm, double event found:\n" << line << endl; } else { table.insert(make_pair(id, move(event))); } // update duration in table } else { auto it = table.find(id); if (it == table.end()) { cout << "Return for unknown event found:\n" << line << endl; } else { unique_ptr<Event> ev = move(it->second); table.erase(it); ev->duration = event->startTime - ev->startTime; list.push_back(move(ev)); } } } } //cout << "Unreturned events:\n"; //for (auto& p : table) { // cout << p.second->pretty() << "\n"; //} sort(list.begin(), list.end(), [](unique_ptr<Event>const& a, unique_ptr<Event>const& b) -> bool { return *a < *b; }); cout << "Events sorted by name and time:\n"; string current; size_t startPos = 0; bool bootstrap = true; auto printStats = [&](size_t i) -> void { cout << "Statistics in microseconds for " << current << ":\n" << " Number of calls: " << i - startPos << "\n" << " Minimal time : " << static_cast<uint64_t>(list[startPos]->duration * 1000000.0) << "\n"; size_t pos = (i - startPos) / 2 + startPos; cout << " 50%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; pos = ((i - startPos) * 90) / 100 + startPos; cout << " 90%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; pos = ((i - startPos) * 99) / 100 + startPos; cout << " 99%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; pos = ((i - startPos) * 999) / 1000 + startPos; cout << " 99.9%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; cout << " Maximal time : " << static_cast<uint64_t>(list[i-1]->duration * 1000000.0) << "\n"; size_t j = (i-startPos > 30) ? i-30 : startPos; cout << " Top " << i-j << " times :"; while (j < i) { cout << " " << static_cast<uint64_t>(list[j++]->duration * 1000000.0); } cout << "\n" << endl; }; for (size_t i = 0; i < list.size(); ++i) { unique_ptr<Event>& e = list[i]; if (e->name != current) { if (!bootstrap) { printStats(i); } bootstrap = false; startPos = i; current = e->name; } cout << e->pretty() << "\n"; } printStats(list.size()); return 0; } <commit_msg>Fix compilation instructions.<commit_after>// Compile with // g++ perfanalysis.cpp -o perfanalysis -std=c++14 -Wall -O3 #include <algorithm> #include <cstring> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <vector> using namespace std; struct StrTok { string& s; size_t pos; bool done; void advance() { while (pos < s.size() && s[pos] == ' ') { ++pos; } done = pos >= s.size(); } StrTok(string& t) : s(t), pos(0), done(false) { advance(); } const char* get() { if (done) { return nullptr; } auto p = s.find(' ', pos); if (p == string::npos) { done = true; return s.c_str() + pos; } s[p] = 0; auto ret = s.c_str() + pos; pos = p + 1; advance(); return ret; } }; struct Event { string threadName; int tid; string cpu; double startTime; double duration; string name; string inbrackets; bool isRet; Event(string& line) : isRet(false) { StrTok tok(line); const char* p = tok.get(); const char* q; if (p != nullptr) { threadName = p; p = tok.get(); tid = strtol(p, nullptr, 10); p = tok.get(); cpu = p; p = tok.get(); startTime = strtod(p, nullptr); p = tok.get(); name = p; name.pop_back(); q = tok.get(); if (strcmp(q, "cs:") == 0) { return; } if (name.compare(0, 14, "probe_arangod:") == 0) { name = name.substr(14); } auto l = name.size(); if (l >= 3 && name[l-1] == 't' && name[l-2] == 'e' && name[l-3] == 'R') { isRet = true; name.pop_back(); name.pop_back(); name.pop_back(); } inbrackets = q; } } bool empty() { return name.empty(); } string id() { return to_string(tid) + name; } string pretty() { return to_string(duration) + " " + name + " " + to_string(startTime); } bool operator<(Event const& other) { if (name < other.name) { return true; } else if (name > other.name) { return false; } else { return duration < other.duration; } } }; int main(int /*argc*/, char* /*argv*/ []) { unordered_map<string, unique_ptr<Event>> table; vector<unique_ptr<Event>> list; string line; while (getline(cin, line)) { auto event = make_unique<Event>(line); if (!event->empty()) { string id = event->id(); // insert to table if it is not a function return if (!event->isRet) { auto it = table.find(id); if (it != table.end()) { //cout << "Alarm, double event found:\n" << line << endl; } else { table.insert(make_pair(id, move(event))); } // update duration in table } else { auto it = table.find(id); if (it == table.end()) { cout << "Return for unknown event found:\n" << line << endl; } else { unique_ptr<Event> ev = move(it->second); table.erase(it); ev->duration = event->startTime - ev->startTime; list.push_back(move(ev)); } } } } //cout << "Unreturned events:\n"; //for (auto& p : table) { // cout << p.second->pretty() << "\n"; //} sort(list.begin(), list.end(), [](unique_ptr<Event>const& a, unique_ptr<Event>const& b) -> bool { return *a < *b; }); cout << "Events sorted by name and time:\n"; string current; size_t startPos = 0; bool bootstrap = true; auto printStats = [&](size_t i) -> void { cout << "Statistics in microseconds for " << current << ":\n" << " Number of calls: " << i - startPos << "\n" << " Minimal time : " << static_cast<uint64_t>(list[startPos]->duration * 1000000.0) << "\n"; size_t pos = (i - startPos) / 2 + startPos; cout << " 50%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; pos = ((i - startPos) * 90) / 100 + startPos; cout << " 90%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; pos = ((i - startPos) * 99) / 100 + startPos; cout << " 99%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; pos = ((i - startPos) * 999) / 1000 + startPos; cout << " 99.9%ile : " << static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n"; cout << " Maximal time : " << static_cast<uint64_t>(list[i-1]->duration * 1000000.0) << "\n"; size_t j = (i-startPos > 30) ? i-30 : startPos; cout << " Top " << i-j << " times :"; while (j < i) { cout << " " << static_cast<uint64_t>(list[j++]->duration * 1000000.0); } cout << "\n" << endl; }; for (size_t i = 0; i < list.size(); ++i) { unique_ptr<Event>& e = list[i]; if (e->name != current) { if (!bootstrap) { printStats(i); } bootstrap = false; startPos = i; current = e->name; } cout << e->pretty() << "\n"; } printStats(list.size()); return 0; } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*- * vi: set shiftwidth=4 tabstop=8: * :indentSize=4:tabSize=8: */ #include "regex_index.h" #include <iostream> void convert(const std::string& flags, std::regex_constants::syntax_option_type& fl, bool& positiveMatch) { bool positive_match = true; std::regex_constants::syntax_option_type flg = std::regex::ECMAScript | std::regex::optimize; for(auto f : flags) { switch(f) { case 'i': flg |= std::regex::icase; break; case '!': positive_match = false; break; default: throw std::runtime_error(std::string("invalid regular expression flags character: ") + f); } } // set output parameters positiveMatch = positive_match; fl = flg; } regex_index::regex_index(std::shared_ptr<file_index> f_idx, const std::string& rgx, const std::string& flags, ProgressFunctor *func) { bool positive_match = true; std::regex_constants::syntax_option_type fl; convert(flags, fl, positive_match); const uint64_t total_lines = f_idx->size(); uint64_t cnt = 0; std::regex r(rgx, fl); for(auto line : *f_idx) { //std::clog << line.num_ << ":" << line.to_string(); bool res = std::regex_search(line.beg_, line.end_, r); if (( positive_match && res) || (!positive_match && !res)) { lineNum_set_.insert(line.num_); //std::clog << " !match!"; } //std::clog << std::endl; if (func && ((++cnt) % 10000) == 0) { func->progress(cnt, cnt * 100 / total_lines); } } } lineNum_set_t intersect(const lineNum_set_t& l, const lineNum_set_t& r) { lineNum_set_t s; if (! l.empty()) { for(auto i : r) { if (l.count(i)) { s.insert(i); } } } return s; } lineNum_set_t ILineNumSetProvider::intersect(const lineNum_set_t& s) { return ::intersect(lineNum_set(), s); } const lineNum_set_t& regex_index::lineNum_set() { return lineNum_set_; } <commit_msg>optimize intersect()<commit_after>/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*- * vi: set shiftwidth=4 tabstop=8: * :indentSize=4:tabSize=8: */ #include "regex_index.h" #include <iostream> void convert(const std::string& flags, std::regex_constants::syntax_option_type& fl, bool& positiveMatch) { bool positive_match = true; std::regex_constants::syntax_option_type flg = std::regex::ECMAScript | std::regex::optimize; for(auto f : flags) { switch(f) { case 'i': flg |= std::regex::icase; break; case '!': positive_match = false; break; default: throw std::runtime_error(std::string("invalid regular expression flags character: ") + f); } } // set output parameters positiveMatch = positive_match; fl = flg; } regex_index::regex_index(std::shared_ptr<file_index> f_idx, const std::string& rgx, const std::string& flags, ProgressFunctor *func) { bool positive_match = true; std::regex_constants::syntax_option_type fl; convert(flags, fl, positive_match); const uint64_t total_lines = f_idx->size(); uint64_t cnt = 0; std::regex r(rgx, fl); for(auto line : *f_idx) { //std::clog << line.num_ << ":" << line.to_string(); bool res = std::regex_search(line.beg_, line.end_, r); if (( positive_match && res) || (!positive_match && !res)) { lineNum_set_.insert(line.num_); //std::clog << " !match!"; } //std::clog << std::endl; if (func && ((++cnt) % 10000) == 0) { func->progress(cnt, cnt * 100 / total_lines); } } } lineNum_set_t intersect(const lineNum_set_t& L, const lineNum_set_t& R) { // make l the smaller set const bool L_smaller_R = L.size() < R.size(); const lineNum_set_t &l = L_smaller_R ? L : R; const lineNum_set_t &r = L_smaller_R ? R : L; lineNum_set_t s; for(auto i : l) { if (r.count(i)) { s.insert(i); } } return s; } lineNum_set_t ILineNumSetProvider::intersect(const lineNum_set_t& s) { return ::intersect(lineNum_set(), s); } const lineNum_set_t& regex_index::lineNum_set() { return lineNum_set_; } <|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/inference/analysis/dfg_graphviz_draw_pass.h" namespace paddle { namespace inference { namespace analysis { int DFG_GraphvizDrawPass::counter_{0}; void DFG_GraphvizDrawPass::Run(DataFlowGraph *graph) { auto content = Draw(graph); auto dot_path = GenDotPath(); std::ofstream file(dot_path); file.write(content.c_str(), content.size()); file.close(); auto png_path = dot_path.substr(0, dot_path.size() - 4) + ".png"; std::string message; LOG(INFO) << "draw to " << png_path; ExecShellCommand("dot -Tpng " + dot_path + " -o " + png_path, &message); } std::string DFG_GraphvizDrawPass::Draw(DataFlowGraph *graph) { Dot dot; // Add nodes for (size_t i = 0; i < graph->nodes.size(); i++) { const Node &node = graph->nodes.Get(i); if (config_.display_deleted_node || !node.deleted()) { dot.AddNode(node.repr(), node.dot_attrs()); } } // Add edges for (size_t i = 0; i < graph->nodes.size(); i++) { const Node &node = graph->nodes.Get(i); if (!config_.display_deleted_node && node.deleted()) continue; for (auto &in : node.inlinks) { if (!config_.display_deleted_node && in->deleted()) continue; dot.AddEdge(in->repr(), node.repr(), {}); } } return dot.Build(); } } // namespace analysis } // namespace inference } // namespace paddle <commit_msg>refine graph draw<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/inference/analysis/dfg_graphviz_draw_pass.h" namespace paddle { namespace inference { namespace analysis { int DFG_GraphvizDrawPass::counter_{0}; void DFG_GraphvizDrawPass::Run(DataFlowGraph *graph) { auto content = Draw(graph); auto dot_path = GenDotPath(); std::ofstream file(dot_path); file.write(content.c_str(), content.size()); file.close(); auto png_path = dot_path.substr(0, dot_path.size() - 4) + ".png"; std::string message; LOG(INFO) << "draw to " << png_path; ExecShellCommand("dot -Tpng " + dot_path + " -o " + png_path, &message); } std::string DFG_GraphvizDrawPass::Draw(DataFlowGraph *graph) { Dot dot; // Add nodes for (size_t i = 0; i < graph->nodes.size(); i++) { const Node &node = graph->nodes.Get(i); if (config_.display_deleted_node || !node.deleted()) { dot.AddNode(node.repr(), node.dot_attrs()); } } // Add edges for (size_t i = 0; i < graph->nodes.size(); i++) { const Node &node = graph->nodes.Get(i); if (!config_.display_deleted_node && node.deleted()) continue; for (auto &out : node.outlinks) { if (!config_.display_deleted_node && out->deleted()) continue; dot.AddEdge(node.repr(), out->repr(), {}); } } return dot.Build(); } } // namespace analysis } // namespace inference } // namespace paddle <|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <gtest/gtest.h> #include <fstream> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/inference/tensorrt/convert/ut_helper.h" namespace paddle { namespace inference { namespace tensorrt { TEST(Pool2dOpConverter, main) { framework::Scope scope; std::unordered_set<std::string> parameters; TRTConvertValidation validator(5, parameters, scope, 1 << 15); // The ITensor's Dims should not contain the batch size. // So, the ITensor's Dims of input and output should be C * H * W. validator.DeclInputVar("pool2d-X", nvinfer1::Dims3(3, 4, 4)); validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 2, 2)); // Prepare Op description framework::OpDesc desc; desc.SetType("pool2d"); desc.SetInput("X", {"pool2d-X"}); desc.SetOutput("Out", {"pool2d-Out"}); std::vector<int> ksize({2, 2}); std::vector<int> strides({2, 2}); std::vector<int> paddings({0, 0}); std::string pooling_t = "max"; bool global_pooling = false; desc.SetAttr("pooling_type", pooling_t); desc.SetAttr("ksize", ksize); desc.SetAttr("strides", strides); desc.SetAttr("paddings", paddings); desc.SetAttr("global_pooling", global_pooling); LOG(INFO) << "set OP"; validator.SetOp(*desc.Proto()); LOG(INFO) << "execute"; validator.Execute(3); } TEST(Pool2dOpConverter, test_global_pooling) { framework::Scope scope; std::unordered_set<std::string> parameters; TRTConvertValidation validator(5, parameters, scope, 1 << 15); // The ITensor's Dims should not contain the batch size. // So, the ITensor's Dims of input and output should be C * H * W. validator.DeclInputVar("pool2d-X", nvinfer1::Dims3(3, 4, 4)); validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 1, 1)); // Prepare Op description framework::OpDesc desc; desc.SetType("pool2d"); desc.SetInput("X", {"pool2d-X"}); desc.SetOutput("Out", {"pool2d-Out"}); std::vector<int> ksize({2, 2}); std::vector<int> strides({2, 2}); std::vector<int> paddings({0, 0}); std::string pooling_t = "max"; bool global_pooling = true; desc.SetAttr("pooling_type", pooling_t); desc.SetAttr("ksize", ksize); desc.SetAttr("strides", strides); desc.SetAttr("paddings", paddings); desc.SetAttr("global_pooling", global_pooling); LOG(INFO) << "set OP"; validator.SetOp(*desc.Proto()); LOG(INFO) << "execute"; validator.Execute(3); } } // namespace tensorrt } // namespace inference } // namespace paddle USE_OP(pool2d); <commit_msg>fix comments<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <gtest/gtest.h> #include <fstream> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/inference/tensorrt/convert/ut_helper.h" namespace paddle { namespace inference { namespace tensorrt { void test_pool2d(bool global_pooling) { framework::Scope scope; std::unordered_set<std::string> parameters; TRTConvertValidation validator(5, parameters, scope, 1 << 15); // The ITensor's Dims should not contain the batch size. // So, the ITensor's Dims of input and output should be C * H * W. validator.DeclInputVar("pool2d-X", nvinfer1::Dims3(3, 4, 4)); if (global_pooling) validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 1, 1)); else validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 2, 2)); // Prepare Op description framework::OpDesc desc; desc.SetType("pool2d"); desc.SetInput("X", {"pool2d-X"}); desc.SetOutput("Out", {"pool2d-Out"}); std::vector<int> ksize({2, 2}); std::vector<int> strides({2, 2}); std::vector<int> paddings({0, 0}); std::string pooling_t = "max"; desc.SetAttr("pooling_type", pooling_t); desc.SetAttr("ksize", ksize); desc.SetAttr("strides", strides); desc.SetAttr("paddings", paddings); desc.SetAttr("global_pooling", global_pooling); LOG(INFO) << "set OP"; validator.SetOp(*desc.Proto()); LOG(INFO) << "execute"; validator.Execute(3); } TEST(Pool2dOpConverter, normal) { test_pool2d(false); } TEST(Pool2dOpConverter, test_global_pooling) { test_pool2d(true); } } // namespace tensorrt } // namespace inference } // namespace paddle USE_OP(pool2d); <|endoftext|>
<commit_before>#include "lambda_man.hpp" namespace shiranui{ namespace syntax{ void LambdaMarkerScanner::visit(ast::Identifier&){} void LambdaMarkerScanner::visit(ast::Variable&){} void LambdaMarkerScanner::visit(ast::Number&){} void LambdaMarkerScanner::visit(ast::String&){} void LambdaMarkerScanner::visit(ast::Boolean&){} void LambdaMarkerScanner::visit(ast::Enum& node){ for(auto e : node.expressions){ e->accept(*this); } } void LambdaMarkerScanner::visit(ast::Interval& node){ if(node.start != nullptr){ node.start->accept(*this); } if(node.end != nullptr){ node.end->accept(*this); } if(node.next != nullptr){ node.next->accept(*this); } } void LambdaMarkerScanner::visit(ast::Block& node){ for(auto s : node.statements){ s->accept(*this); } for(auto s : node.flymarks){ s->accept(*this); } } void LambdaMarkerScanner::visit(ast::Function& node){ // FIXME: copy is safe,BUT should not.(runtime_infomation is not shared) auto copy = std::make_shared<ast::Function>(node); where_are_you_from[node.body] = copy; if(node.lambda_id.name != ""){ marker_to_lambda[node.lambda_id] = copy; } node.body->accept(*this); } void LambdaMarkerScanner::visit(ast::FunctionCall& node){ node.function->accept(*this); for(auto a : node.arguments){ a->accept(*this); } } void LambdaMarkerScanner::visit(ast::BinaryOperator& node){ node.left->accept(*this); node.right->accept(*this); } void LambdaMarkerScanner::visit(ast::UnaryOperator& node){ node.exp->accept(*this); } void LambdaMarkerScanner::visit(ast::IfElseExpression& node){ node.pred->accept(*this); node.ife->accept(*this); node.elsee->accept(*this); } void LambdaMarkerScanner::visit(ast::Definement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::ExpressionStatement& node){ node.exp->accept(*this); } void LambdaMarkerScanner::visit(ast::ReturnStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::ProbeStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::AssertStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::IfElseStatement& node){ node.pred->accept(*this); node.ifblock->accept(*this); node.elseblock->accept(*this); } // should return forstatement? void LambdaMarkerScanner::visit(ast::ForStatement& node){ node.loop_exp->accept(*this); node.block->accept(*this); } void LambdaMarkerScanner::visit(ast::Assignment& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::TestFlyLine&){} void LambdaMarkerScanner::visit(ast::IdleFlyLine&){} void LambdaMarkerScanner::visit(ast::FlyMark&){} void LambdaMarkerScanner::visit(ast::SourceCode& node){ for(auto s : node.statements){ s->accept(*this); } } void LambdaMarkerScanner::visit(ast::DSL::DataDSL&){} std::pair< std::map<sp<ast::Block>,sp<ast::Function> >, std::map<ast::Identifier,sp<ast::Function> > > scan_lambda_marker(ast::SourceCode& source){ LambdaMarkerScanner h; h.visit(source); return std::make_pair(h.where_are_you_from, h.marker_to_lambda); } // --------------------------------------------------------------------- LambdaFreeVariableScanner::LambdaFreeVariableScanner(){} void LambdaFreeVariableScanner::visit(ast::Identifier&){} void LambdaFreeVariableScanner::visit(ast::Variable& v){ if(is_free(v.value)){ free.insert(v.value); }else{ } } void LambdaFreeVariableScanner::visit(ast::Number&){} void LambdaFreeVariableScanner::visit(ast::String&){} void LambdaFreeVariableScanner::visit(ast::Boolean&){} void LambdaFreeVariableScanner::visit(ast::Enum& node){ for(auto e : node.expressions){ e->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::Interval& node){ if(node.start != nullptr){ node.start->accept(*this); } if(node.end != nullptr){ node.end->accept(*this); } if(node.next != nullptr){ node.next->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::Block& node){ bound.emplace(); for(auto s : node.statements){ s->accept(*this); } for(auto s : node.flymarks){ s->accept(*this); } bound.pop(); } void LambdaFreeVariableScanner::visit(ast::Function& node){ bound.emplace(); for(auto i : node.parameters){ bound.top().insert(i); } node.body->accept(*this); bound.pop(); } void LambdaFreeVariableScanner::visit(ast::FunctionCall& node){ node.function->accept(*this); for(auto a : node.arguments){ a->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::BinaryOperator& node){ node.left->accept(*this); node.right->accept(*this); } void LambdaFreeVariableScanner::visit(ast::UnaryOperator& node){ node.exp->accept(*this); } void LambdaFreeVariableScanner::visit(ast::IfElseExpression& node){ node.pred->accept(*this); node.ife->accept(*this); node.elsee->accept(*this); } void LambdaFreeVariableScanner::visit(ast::Definement& node){ // for recursive function, add here. bound.top().insert(node.id); node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ExpressionStatement& node){ node.exp->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ReturnStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ProbeStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::AssertStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::IfElseStatement& node){ node.pred->accept(*this); node.ifblock->accept(*this); node.elseblock->accept(*this); } // should return forstatement? void LambdaFreeVariableScanner::visit(ast::ForStatement& node){ node.loop_exp->accept(*this); node.block->accept(*this); } void LambdaFreeVariableScanner::visit(ast::Assignment& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::TestFlyLine&){} void LambdaFreeVariableScanner::visit(ast::IdleFlyLine&){} void LambdaFreeVariableScanner::visit(ast::FlyMark&){} void LambdaFreeVariableScanner::visit(ast::SourceCode& node){ for(auto s : node.statements){ s->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::DSL::DataDSL&){} bool LambdaFreeVariableScanner::is_free(ast::Identifier i){ auto copy = bound; while(not copy.empty()){ auto t = copy.top(); if(t.find(i) != t.end()){ return false; } copy.pop(); } return true; } std::set<ast::Identifier> scan_free_variable(ast::Function& f){ LambdaFreeVariableScanner sc; f.accept(sc); return sc.free; } std::set<ast::Identifier> scan_free_variable(sp<ast::Function> fp){ return scan_free_variable(*fp); } } } <commit_msg>Add check for assginment when collecting freevar.<commit_after>#include "lambda_man.hpp" namespace shiranui{ namespace syntax{ void LambdaMarkerScanner::visit(ast::Identifier&){} void LambdaMarkerScanner::visit(ast::Variable&){} void LambdaMarkerScanner::visit(ast::Number&){} void LambdaMarkerScanner::visit(ast::String&){} void LambdaMarkerScanner::visit(ast::Boolean&){} void LambdaMarkerScanner::visit(ast::Enum& node){ for(auto e : node.expressions){ e->accept(*this); } } void LambdaMarkerScanner::visit(ast::Interval& node){ if(node.start != nullptr){ node.start->accept(*this); } if(node.end != nullptr){ node.end->accept(*this); } if(node.next != nullptr){ node.next->accept(*this); } } void LambdaMarkerScanner::visit(ast::Block& node){ for(auto s : node.statements){ s->accept(*this); } for(auto s : node.flymarks){ s->accept(*this); } } void LambdaMarkerScanner::visit(ast::Function& node){ // FIXME: copy is safe,BUT should not.(runtime_infomation is not shared) auto copy = std::make_shared<ast::Function>(node); where_are_you_from[node.body] = copy; if(node.lambda_id.name != ""){ marker_to_lambda[node.lambda_id] = copy; } node.body->accept(*this); } void LambdaMarkerScanner::visit(ast::FunctionCall& node){ node.function->accept(*this); for(auto a : node.arguments){ a->accept(*this); } } void LambdaMarkerScanner::visit(ast::BinaryOperator& node){ node.left->accept(*this); node.right->accept(*this); } void LambdaMarkerScanner::visit(ast::UnaryOperator& node){ node.exp->accept(*this); } void LambdaMarkerScanner::visit(ast::IfElseExpression& node){ node.pred->accept(*this); node.ife->accept(*this); node.elsee->accept(*this); } void LambdaMarkerScanner::visit(ast::Definement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::ExpressionStatement& node){ node.exp->accept(*this); } void LambdaMarkerScanner::visit(ast::ReturnStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::ProbeStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::AssertStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::IfElseStatement& node){ node.pred->accept(*this); node.ifblock->accept(*this); node.elseblock->accept(*this); } // should return forstatement? void LambdaMarkerScanner::visit(ast::ForStatement& node){ node.loop_exp->accept(*this); node.block->accept(*this); } void LambdaMarkerScanner::visit(ast::Assignment& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::TestFlyLine&){} void LambdaMarkerScanner::visit(ast::IdleFlyLine&){} void LambdaMarkerScanner::visit(ast::FlyMark&){} void LambdaMarkerScanner::visit(ast::SourceCode& node){ for(auto s : node.statements){ s->accept(*this); } } void LambdaMarkerScanner::visit(ast::DSL::DataDSL&){} std::pair< std::map<sp<ast::Block>,sp<ast::Function> >, std::map<ast::Identifier,sp<ast::Function> > > scan_lambda_marker(ast::SourceCode& source){ LambdaMarkerScanner h; h.visit(source); return std::make_pair(h.where_are_you_from, h.marker_to_lambda); } // --------------------------------------------------------------------- LambdaFreeVariableScanner::LambdaFreeVariableScanner(){} void LambdaFreeVariableScanner::visit(ast::Identifier&){} void LambdaFreeVariableScanner::visit(ast::Variable& v){ if(is_free(v.value)){ free.insert(v.value); }else{ } } void LambdaFreeVariableScanner::visit(ast::Number&){} void LambdaFreeVariableScanner::visit(ast::String&){} void LambdaFreeVariableScanner::visit(ast::Boolean&){} void LambdaFreeVariableScanner::visit(ast::Enum& node){ for(auto e : node.expressions){ e->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::Interval& node){ if(node.start != nullptr){ node.start->accept(*this); } if(node.end != nullptr){ node.end->accept(*this); } if(node.next != nullptr){ node.next->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::Block& node){ bound.emplace(); for(auto s : node.statements){ s->accept(*this); } for(auto s : node.flymarks){ s->accept(*this); } bound.pop(); } void LambdaFreeVariableScanner::visit(ast::Function& node){ bound.emplace(); for(auto i : node.parameters){ bound.top().insert(i); } node.body->accept(*this); bound.pop(); } void LambdaFreeVariableScanner::visit(ast::FunctionCall& node){ node.function->accept(*this); for(auto a : node.arguments){ a->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::BinaryOperator& node){ node.left->accept(*this); node.right->accept(*this); } void LambdaFreeVariableScanner::visit(ast::UnaryOperator& node){ node.exp->accept(*this); } void LambdaFreeVariableScanner::visit(ast::IfElseExpression& node){ node.pred->accept(*this); node.ife->accept(*this); node.elsee->accept(*this); } void LambdaFreeVariableScanner::visit(ast::Definement& node){ // for recursive function, add here. bound.top().insert(node.id); node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ExpressionStatement& node){ node.exp->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ReturnStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ProbeStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::AssertStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::IfElseStatement& node){ node.pred->accept(*this); node.ifblock->accept(*this); node.elseblock->accept(*this); } // should return forstatement? void LambdaFreeVariableScanner::visit(ast::ForStatement& node){ node.loop_exp->accept(*this); node.block->accept(*this); } void LambdaFreeVariableScanner::visit(ast::Assignment& node){ if(is_free(node.id)){ free.insert(node.id); }else{ } node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::TestFlyLine&){} void LambdaFreeVariableScanner::visit(ast::IdleFlyLine&){} void LambdaFreeVariableScanner::visit(ast::FlyMark&){} void LambdaFreeVariableScanner::visit(ast::SourceCode& node){ for(auto s : node.statements){ s->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::DSL::DataDSL&){} bool LambdaFreeVariableScanner::is_free(ast::Identifier i){ auto copy = bound; while(not copy.empty()){ auto t = copy.top(); if(t.find(i) != t.end()){ return false; } copy.pop(); } return true; } std::set<ast::Identifier> scan_free_variable(ast::Function& f){ LambdaFreeVariableScanner sc; f.accept(sc); return sc.free; } std::set<ast::Identifier> scan_free_variable(sp<ast::Function> fp){ return scan_free_variable(*fp); } } } <|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2022 Vaclav Slavik * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ #include "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); // Leading whitespace: for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } // Trailing whitespace: for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { // Some special whitespace characters should always be highlighted: if (*i == 0x00A0 /*non-breakable space*/) { int pos = int(i - s.begin()); highlight(pos, pos + 1, LeadingWhitespace); } // Duplicate whitespace (2+ spaces etc.): else if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } // Escape sequences: if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: /// Ctor. Notice that @a re is a reference and must outlive the highlighter! RegexSyntaxHighlighter(std::wregex& re, TextKind kind) : m_re(re), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { try { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } catch (std::regex_error& e) { switch (e.code()) { case std::regex_constants::error_complexity: case std::regex_constants::error_stack: // MSVC version of std::regex in particular can fail to match // e.g. HTML regex with backreferences on insanely large strings; // in that case, don't highlight instead of failing outright. return; default: throw; } } } private: std::wregex& m_re; TextKind m_kind; }; std::wregex RE_HTML_MARKUP(LR"((<\/?[a-zA-Z0-9:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", std::regex_constants::ECMAScript | std::regex_constants::optimize); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals std::wregex RE_PHP_FORMAT(LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html std::wregex RE_C_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // python-format old style https://docs.python.org/2/library/stdtypes.html#string-formatting // new style https://docs.python.org/3/library/string.html#format-string-syntax std::wregex RE_PYTHON_FORMAT(LR"((%(\(\w+\))?[-+ #0]?(\d+|\*)?(\.(\d+|\*))?[hlL]?[diouxXeEfFgGcrs%]))" // old style "|" LR"((\{([^{}])*\}))", // new style, being permissive std::regex_constants::ECMAScript | std::regex_constants::optimize); // ruby-format per https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-sprintf std::wregex RE_RUBY_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // variables expansion for various template languages std::wregex RE_COMMON_PLACEHOLDERS( // // | | LR"(%[\w.-]+%|%?\{[\w.-]+\}|\{\{[\w.-]+\}\})", // | | | | | // | | | // | | +----------------------- {{var}} // | | // | +--------------------------------------- %{var} (Ruby) and {var} // | // +--------------------------------------------------- %var% (Twig) // std::regex_constants::ECMAScript | std::regex_constants::optimize); } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item, int kindsMask) { auto formatFlag = item.GetFormatFlag(); bool needsHTML = (kindsMask & Markup); if (needsHTML) { needsHTML = std::regex_search(str::to_wstring(item.GetString()), RE_HTML_MARKUP) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), RE_HTML_MARKUP)); } bool needsGenericPlaceholders = (kindsMask & Placeholder); if (needsGenericPlaceholders) { needsGenericPlaceholders = std::regex_search(str::to_wstring(item.GetString()), RE_COMMON_PLACEHOLDERS) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), RE_COMMON_PLACEHOLDERS)); } static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsGenericPlaceholders && formatFlag.empty()) { if (kindsMask & (LeadingWhitespace | Escape)) return basic; else return nullptr; } auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(RE_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsGenericPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(RE_COMMON_PLACEHOLDERS, TextKind::Placeholder); all->Add(placeholders); } if (kindsMask & Placeholder) { // TODO: more/all languages if (formatFlag == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Placeholder); all->Add(php_format); } else if (formatFlag == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Placeholder); all->Add(c_format); } else if (formatFlag == "python") { static auto python_format = std::make_shared<RegexSyntaxHighlighter>(RE_PYTHON_FORMAT, TextKind::Placeholder); all->Add(python_format); } else if (formatFlag == "ruby") { static auto ruby_format = std::make_shared<RegexSyntaxHighlighter>(RE_RUBY_FORMAT, TextKind::Placeholder); all->Add(ruby_format); } } // basic highlighting has highest priority, so should come last in the order: if (kindsMask & (LeadingWhitespace | Escape)) all->Add(basic); return all; } <commit_msg>Simplify RegexSyntaxHighlighter creation code<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2022 Vaclav Slavik * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ #include "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); // Leading whitespace: for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } // Trailing whitespace: for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { // Some special whitespace characters should always be highlighted: if (*i == 0x00A0 /*non-breakable space*/) { int pos = int(i - s.begin()); highlight(pos, pos + 1, LeadingWhitespace); } // Duplicate whitespace (2+ spaces etc.): else if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } // Escape sequences: if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: static const std::wregex::flag_type flags = std::regex_constants::ECMAScript | std::regex_constants::optimize; RegexSyntaxHighlighter(const wchar_t *regex, TextKind kind) : m_re(regex, flags), m_kind(kind) {} RegexSyntaxHighlighter(const std::wregex& regex, TextKind kind) : m_re(regex), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { try { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } catch (std::regex_error& e) { switch (e.code()) { case std::regex_constants::error_complexity: case std::regex_constants::error_stack: // MSVC version of std::regex in particular can fail to match // e.g. HTML regex with backreferences on insanely large strings; // in that case, don't highlight instead of failing outright. return; default: throw; } } } private: std::wregex m_re; TextKind m_kind; }; std::wregex REOBJ_HTML_MARKUP(LR"((<\/?[a-zA-Z0-9:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", RegexSyntaxHighlighter::flags); // variables expansion for various template languages std::wregex REOBJ_COMMON_PLACEHOLDERS( // // | | LR"(%[\w.-]+%|%?\{[\w.-]+\}|\{\{[\w.-]+\}\})", // | | | | | // | | | // | | +----------------------- {{var}} // | | // | +--------------------------------------- %{var} (Ruby) and {var} // | // +--------------------------------------------------- %var% (Twig) // RegexSyntaxHighlighter::flags); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals const wchar_t* RE_PHP_FORMAT = LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])"; // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html const wchar_t* RE_C_FORMAT = LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])"; // python-format old style https://docs.python.org/2/library/stdtypes.html#string-formatting // new style https://docs.python.org/3/library/string.html#format-string-syntax const wchar_t* RE_PYTHON_FORMAT = LR"((%(\(\w+\))?[-+ #0]?(\d+|\*)?(\.(\d+|\*))?[hlL]?[diouxXeEfFgGcrs%]))" // old style "|" LR"((\{([^{}])*\}))"; // new style, being permissive // ruby-format per https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-sprintf const wchar_t* RE_RUBY_FORMAT = LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])"; } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item, int kindsMask) { auto fmt = item.GetFormatFlag(); bool needsHTML = (kindsMask & Markup); if (needsHTML) { needsHTML = std::regex_search(str::to_wstring(item.GetString()), REOBJ_HTML_MARKUP) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), REOBJ_HTML_MARKUP)); } bool needsGenericPlaceholders = (kindsMask & Placeholder); if (needsGenericPlaceholders) { needsGenericPlaceholders = std::regex_search(str::to_wstring(item.GetString()), REOBJ_COMMON_PLACEHOLDERS) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), REOBJ_COMMON_PLACEHOLDERS)); } static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsGenericPlaceholders && fmt.empty()) { if (kindsMask & (LeadingWhitespace | Escape)) return basic; else return nullptr; } auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(REOBJ_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsGenericPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(REOBJ_COMMON_PLACEHOLDERS, TextKind::Placeholder); all->Add(placeholders); } if (kindsMask & Placeholder) { if (fmt == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Placeholder); all->Add(php_format); } else if (fmt == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Placeholder); all->Add(c_format); } else if (fmt == "python") { static auto python_format = std::make_shared<RegexSyntaxHighlighter>(RE_PYTHON_FORMAT, TextKind::Placeholder); all->Add(python_format); } else if (fmt == "ruby") { static auto ruby_format = std::make_shared<RegexSyntaxHighlighter>(RE_RUBY_FORMAT, TextKind::Placeholder); all->Add(ruby_format); } } // basic highlighting has highest priority, so should come last in the order: if (kindsMask & (LeadingWhitespace | Escape)) all->Add(basic); return all; } <|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2019 Vaclav Slavik * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ #include "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'n': case 'r': case 't': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: /// Ctor. Notice that @a re is a reference and must outlive the highlighter! RegexSyntaxHighlighter(std::wregex& re, TextKind kind) : m_re(re), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } private: std::wregex& m_re; TextKind m_kind; }; std::wregex RE_HTML_MARKUP(LR"((<\/?[a-zA-Z:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", std::regex_constants::ECMAScript | std::regex_constants::optimize); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals std::wregex RE_PHP_FORMAT(LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html std::wregex RE_C_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // variables expansion for %foo% (Twig), {foo} and {{foo}} std::wregex RE_COMMON_PLACEHOLDERS(LR"((%[0-9a-zA-Z_.-]+%)|(\{[0-9a-zA-Z_.-]+\})|(\{\{[0-9a-zA-Z_.-]+\}\}))", std::regex_constants::ECMAScript | std::regex_constants::optimize); } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item) { auto formatFlag = item.GetFormatFlag(); bool needsHTML = std::regex_search(str::to_wstring(item.GetString()), RE_HTML_MARKUP); bool needsPlaceholders = std::regex_search(str::to_wstring(item.GetString()), RE_COMMON_PLACEHOLDERS); static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsPlaceholders && formatFlag.empty()) return basic; auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(RE_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(RE_COMMON_PLACEHOLDERS, TextKind::Format); all->Add(placeholders); } // TODO: more/all languages if (formatFlag == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Format); all->Add(php_format); } else if (formatFlag == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Format); all->Add(c_format); } // basic higlighting has highest priority, so should come last in the order: all->Add(basic); return all; } <commit_msg>Allow editing even if highlighter regex fails<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2019 Vaclav Slavik * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ #include "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'n': case 'r': case 't': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: /// Ctor. Notice that @a re is a reference and must outlive the highlighter! RegexSyntaxHighlighter(std::wregex& re, TextKind kind) : m_re(re), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { try { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } catch (std::regex_error& e) { switch (e.code()) { case std::regex_constants::error_complexity: case std::regex_constants::error_stack: // MSVC version of std::regex in particular can fail to match // e.g. HTML regex with backreferences on insanely large strings; // in that case, don't highlight instead of failing outright. return; default: throw; } } } private: std::wregex& m_re; TextKind m_kind; }; std::wregex RE_HTML_MARKUP(LR"((<\/?[a-zA-Z:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", std::regex_constants::ECMAScript | std::regex_constants::optimize); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals std::wregex RE_PHP_FORMAT(LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html std::wregex RE_C_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // variables expansion for %foo% (Twig), {foo} and {{foo}} std::wregex RE_COMMON_PLACEHOLDERS(LR"((%[0-9a-zA-Z_.-]+%)|(\{[0-9a-zA-Z_.-]+\})|(\{\{[0-9a-zA-Z_.-]+\}\}))", std::regex_constants::ECMAScript | std::regex_constants::optimize); } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item) { auto formatFlag = item.GetFormatFlag(); bool needsHTML = std::regex_search(str::to_wstring(item.GetString()), RE_HTML_MARKUP); bool needsPlaceholders = std::regex_search(str::to_wstring(item.GetString()), RE_COMMON_PLACEHOLDERS); static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsPlaceholders && formatFlag.empty()) return basic; auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(RE_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(RE_COMMON_PLACEHOLDERS, TextKind::Format); all->Add(placeholders); } // TODO: more/all languages if (formatFlag == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Format); all->Add(php_format); } else if (formatFlag == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Format); all->Add(c_format); } // basic higlighting has highest priority, so should come last in the order: all->Add(basic); return all; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/centaur/procedures/hwp/perv/cen_pll_setup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file cen_pll_setup.C /// @brief Centaur PLL setup (FAPI2) /// /// @author Peng Fei GOU <shgoupf@cn.ibm.com> /// // // *HWP HWP Owner: Peng Fei GOU <shgoupf@cn.ibm.com> // *HWP FW Owner: Thi Tran <thi@us.ibm.com> // *HWP Team: Perv // *HWP Level: 2 // *HWP Consumed by: HB // //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <cen_pll_setup.H> #include <centaur_misc_scom_addresses.H> #include <centaur_misc_constants.H> //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode cen_pll_setup(const fapi2::Target<fapi2::TARGET_TYPE_MEMBUF_CHIP>& i_target) { FAPI_DBG("Start"); fapi2::buffer<uint32_t> l_cfam_status_data = 0; fapi2::buffer<uint32_t> l_fsi_gp3_data = 0; fapi2::buffer<uint32_t> l_fsi_gp4_data = 0; fapi2::buffer<uint32_t> l_perv_gp3_data = 0; fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; bool l_poll_succeed = false; // SBE Address Base Register Setups FAPI_DBG("Reset PLL test enable"); FAPI_TRY(fapi2::getCfamRegister(i_target, CFAM_FSI_GP4, l_fsi_gp4_data), "Error from getCfamRegister (CFAM_FSI_GP4)"); l_fsi_gp4_data.clearBit<24>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CFAM_FSI_GP4, l_fsi_gp4_data), "Error from putCfamRegister (CFAM_FSI_GP4)"); FAPI_DBG( "PLL Leave Reset State" ); FAPI_TRY(fapi2::getCfamRegister(i_target, CFAM_FSI_GP3, l_fsi_gp3_data), "Error from getCfamRegister (CFAM_FSI_GP3)"); l_fsi_gp3_data.clearBit<28>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CFAM_FSI_GP3, l_fsi_gp3_data), "Error from putCfamRegister (CFAM_FSI_GP3)"); FAPI_DBG( "Centaur only: Nest PLL Leave Reset State" ); FAPI_TRY(fapi2::getCfamRegister(i_target, CFAM_FSI_GP4, l_fsi_gp4_data), "Error from getCfamRegister (CFAM_FSI_GP4)"); l_fsi_gp4_data.clearBit<16>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CFAM_FSI_GP4, l_fsi_gp4_data), "Error from putCfamRegister (CFAM_FSI_GP4)"); FAPI_DBG( "Drop Nest PLL bypass GP3MIR(5)=0 tp_pllbyp_dc" ); FAPI_TRY(fapi2::getCfamRegister(i_target, PERV_GP3, l_perv_gp3_data), "Error from getCfamRegister (PERV_GP3)"); l_perv_gp3_data.clearBit<5>(); FAPI_TRY(fapi2::putCfamRegister(i_target, PERV_GP3, l_perv_gp3_data), "Error from putCfamRegister (PERV_GP3)"); FAPI_DBG( "Poll FSI2PIB-Status(24) for (nest) pll lock bits." ); for (uint32_t i = 0; i < MAX_FLUSH_LOOPS; i++) { FAPI_TRY(fapi2::getCfamRegister(i_target, FSI2PIB_STATUS, l_cfam_status_data), "Error from getCfamRegister (FSI2PIB_STATUS)"); FAPI_DBG( "Polling... FSI2PIB-Status(24)." ); if (l_cfam_status_data.getBit<24>()) { l_poll_succeed = true; break; } FAPI_TRY(fapi2::delay(NANO_FLUSH_DELAY, SIM_FLUSH_DELAY)); } FAPI_ASSERT(l_poll_succeed, fapi2::CEN_PLL_SETUP_POLL_NEST_PLL_LOCK_TIMEOUT(). set_TARGET(i_target), "NEST PLL LOCK TIMEOUT!"); // Chiplet Init bring-up MEM PLL FAPI_DBG( "bring-up the MEM PLL for ARRAYINIT closure" ); FAPI_DBG( "Drop bypass mode before LOCK (tp_pllmem_bypass_en_dc)." ); FAPI_TRY(fapi2::getCfamRegister(i_target, PERV_GP3, l_perv_gp3_data), "Error from getCfamRegister (PERV_GP3)"); l_perv_gp3_data.clearBit<17>(); FAPI_TRY(fapi2::putCfamRegister(i_target, PERV_GP3, l_perv_gp3_data), "Error from putCfamRegister (PERV_GP3)"); FAPI_DBG( "Poll FSI2PIB-Status(25) for (mem) pll lock bits." ); l_poll_succeed = false; for (uint32_t i = 0; i < MAX_FLUSH_LOOPS; i++) { FAPI_TRY(fapi2::getCfamRegister(i_target, FSI2PIB_STATUS, l_cfam_status_data), "Error from getCfamRegister (FSI2PIB_STATUS)"); FAPI_DBG( "Polling... FSI2PIB-Status(25)." ); if (l_cfam_status_data.getBit<25>()) { l_poll_succeed = true; break; } FAPI_TRY(fapi2::delay(NANO_FLUSH_DELAY, SIM_FLUSH_DELAY)); } FAPI_ASSERT(l_poll_succeed, fapi2::CEN_PLL_SETUP_POLL_MEM_PLL_LOCK_TIMEOUT(). set_TARGET(i_target), "MEM PLL LOCK TIMEOUT!"); fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } <commit_msg>Edit ECID+Perv code to use new gen'd centaur scom headers<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/centaur/procedures/hwp/perv/cen_pll_setup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file cen_pll_setup.C /// @brief Centaur PLL setup (FAPI2) /// /// @author Peng Fei GOU <shgoupf@cn.ibm.com> /// // // *HWP HWP Owner: Peng Fei GOU <shgoupf@cn.ibm.com> // *HWP FW Owner: Thi Tran <thi@us.ibm.com> // *HWP Team: Perv // *HWP Level: 2 // *HWP Consumed by: HB // //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <cen_pll_setup.H> #include <cen_gen_scom_addresses.H> #include <centaur_misc_constants.H> //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode cen_pll_setup(const fapi2::Target<fapi2::TARGET_TYPE_MEMBUF_CHIP>& i_target) { FAPI_DBG("Start"); fapi2::buffer<uint32_t> l_cfam_status_data = 0; fapi2::buffer<uint32_t> l_fsi_gp3_data = 0; fapi2::buffer<uint32_t> l_fsi_gp4_data = 0; fapi2::buffer<uint32_t> l_perv_gp3_data = 0; fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; bool l_poll_succeed = false; // SBE Address Base Register Setups FAPI_DBG("Reset PLL test enable"); FAPI_TRY(fapi2::getCfamRegister(i_target, CEN_FSIGP4, l_fsi_gp4_data), "Error from getCfamRegister (CEN_FSIGP4)"); l_fsi_gp4_data.clearBit<24>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CEN_FSIGP4, l_fsi_gp4_data), "Error from putCfamRegister (CEN_FSIGP4)"); FAPI_DBG( "PLL Leave Reset State" ); FAPI_TRY(fapi2::getCfamRegister(i_target, CEN_FSIGP3, l_fsi_gp3_data), "Error from getCfamRegister (CEN_FSIGP3)"); l_fsi_gp3_data.clearBit<28>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CEN_FSIGP3, l_fsi_gp3_data), "Error from putCfamRegister (CEN_FSIGP3)"); FAPI_DBG( "Centaur only: Nest PLL Leave Reset State" ); FAPI_TRY(fapi2::getCfamRegister(i_target, CEN_FSIGP4, l_fsi_gp4_data), "Error from getCfamRegister (CEN_FSIGP4)"); l_fsi_gp4_data.clearBit<16>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CEN_FSIGP4, l_fsi_gp4_data), "Error from putCfamRegister (CEN_FSIGP4)"); FAPI_DBG( "Drop Nest PLL bypass GP3MIR(5)=0 tp_pllbyp_dc" ); FAPI_TRY(fapi2::getCfamRegister(i_target, CEN_PERV_GP3, l_perv_gp3_data), "Error from getCfamRegister (CEN_PERV_GP3)"); l_perv_gp3_data.clearBit<5>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CEN_PERV_GP3, l_perv_gp3_data), "Error from putCfamRegister (CEN_PERV_GP3)"); FAPI_DBG( "Poll FSI2PIB-Status(24) for (nest) pll lock bits." ); for (uint32_t i = 0; i < MAX_FLUSH_LOOPS; i++) { FAPI_TRY(fapi2::getCfamRegister(i_target, CEN_STATUS_ROX, l_cfam_status_data), "Error from getCfamRegister (CEN_STATUS_ROX)"); FAPI_DBG( "Polling... FSI2PIB-Status(24)." ); if (l_cfam_status_data.getBit<24>()) { l_poll_succeed = true; break; } FAPI_TRY(fapi2::delay(NANO_FLUSH_DELAY, SIM_FLUSH_DELAY)); } FAPI_ASSERT(l_poll_succeed, fapi2::CEN_PLL_SETUP_POLL_NEST_PLL_LOCK_TIMEOUT(). set_TARGET(i_target), "NEST PLL LOCK TIMEOUT!"); // Chiplet Init bring-up MEM PLL FAPI_DBG( "bring-up the MEM PLL for ARRAYINIT closure" ); FAPI_DBG( "Drop bypass mode before LOCK (tp_pllmem_bypass_en_dc)." ); FAPI_TRY(fapi2::getCfamRegister(i_target, CEN_PERV_GP3, l_perv_gp3_data), "Error from getCfamRegister (CEN_PERV_GP3)"); l_perv_gp3_data.clearBit<17>(); FAPI_TRY(fapi2::putCfamRegister(i_target, CEN_PERV_GP3, l_perv_gp3_data), "Error from putCfamRegister (CEN_PERV_GP3)"); FAPI_DBG( "Poll FSI2PIB-Status(25) for (mem) pll lock bits." ); l_poll_succeed = false; for (uint32_t i = 0; i < MAX_FLUSH_LOOPS; i++) { FAPI_TRY(fapi2::getCfamRegister(i_target, CEN_STATUS_ROX, l_cfam_status_data), "Error from getCfamRegister (CEN_STATUS_ROX)"); FAPI_DBG( "Polling... FSI2PIB-Status(25)." ); if (l_cfam_status_data.getBit<25>()) { l_poll_succeed = true; break; } FAPI_TRY(fapi2::delay(NANO_FLUSH_DELAY, SIM_FLUSH_DELAY)); } FAPI_ASSERT(l_poll_succeed, fapi2::CEN_PLL_SETUP_POLL_MEM_PLL_LOCK_TIMEOUT(). set_TARGET(i_target), "MEM PLL LOCK TIMEOUT!"); fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } <|endoftext|>
<commit_before>/* Copyright 2014 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "threading.h" #include "scriptEngineWorker.h" #include "src/utils.h" #include "src/scriptThread.h" #include <QsLog.h> using namespace trikScriptRunner; Threading::Threading(ScriptEngineWorker *scriptWorker, ScriptExecutionControl &scriptControl) : QObject(scriptWorker) , mResetStarted(false) , mScriptWorker(scriptWorker) , mScriptControl(scriptControl) { } Threading::~Threading() { reset(); } void Threading::startMainThread(const QString &script) { mScript = script; mErrorMessage.clear(); mFinishedThreads.clear(); mPreventFromStart.clear(); QRegExp const mainRegexp("(.*var main\\s*=\\s*\\w*\\s*function\\(.*\\).*)|(.*function\\s+%1\\s*\\(.*\\).*)"); bool needCallMain = mainRegexp.exactMatch(script) && !script.trimmed().endsWith("main();"); startThread("main", mScriptWorker->createScriptEngine(), needCallMain ? script + "\nmain();" : script); } void Threading::startThread(const QScriptValue &threadId, const QScriptValue &function) { startThread(threadId.toString(), cloneEngine(function.engine()), mScript + "\n" + function.toString() + "();"); } void Threading::startThread(const QString &threadId, QScriptEngine *engine, const QString &script) { mResetMutex.lock(); if (mResetStarted) { QLOG_INFO() << "Threading: can't start new thread" << threadId << "with engine" << engine << "due to reset"; delete engine; mResetMutex.unlock(); return; } mThreadsMutex.lock(); if (mThreads.contains(threadId)) { QLOG_ERROR() << "Threading: attempt to create a thread with an already occupied id" << threadId; mErrorMessage = tr("Attempt to create a thread with an already occupied id %1").arg(threadId); mThreads[threadId]->abort(); mThreadsMutex.unlock(); mResetMutex.unlock(); return; } if (mPreventFromStart.contains(threadId)) { QLOG_INFO() << "Threading: attempt to create a thread which must be killed" << threadId; mPreventFromStart.remove(threadId); mFinishedThreads.insert(threadId); mThreadsMutex.unlock(); mResetMutex.unlock(); return; } QLOG_INFO() << "Starting new thread" << threadId << "with engine" << engine; ScriptThread *thread = new ScriptThread(*this, threadId, engine, script); connect(&mScriptControl, SIGNAL(quitSignal()), thread, SIGNAL(stopRunning()), Qt::DirectConnection); mThreads[threadId] = thread; mFinishedThreads.remove(threadId); mThreadsMutex.unlock(); engine->moveToThread(thread); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); while (!thread->isEvaluating()) { QThread::yieldCurrentThread(); } // wait until script actually start to avoid problems with multiple starts and resets // TODO: efficient AND safe solution for (int i = 0; i < 500; ++i) { QThread::yieldCurrentThread(); } QLOG_INFO() << "Threading: started thread" << threadId << "with engine" << engine << ", thread object" << thread; mResetMutex.unlock(); } void Threading::waitForAll() { while (!mThreads.isEmpty()) { QThread::yieldCurrentThread(); } } void Threading::joinThread(const QString &threadId) { mThreadsMutex.lock(); while ((!mThreads.contains(threadId) || !mThreads[threadId]->isRunning()) && !mFinishedThreads.contains(threadId)) { mThreadsMutex.unlock(); if (mResetStarted) { return; } QThread::yieldCurrentThread(); mThreadsMutex.lock(); } if (mFinishedThreads.contains(threadId)) { mThreadsMutex.unlock(); return; } ScriptThread *thread = mThreads[threadId]; mThreadsMutex.unlock(); thread->wait(); } QScriptEngine * Threading::cloneEngine(QScriptEngine *engine) { QScriptEngine *result = mScriptWorker->copyScriptEngine(engine); result->evaluate(mScript); return result; } void Threading::reset() { if (!tryLockReset()) { return; } mResetStarted = true; mResetMutex.unlock(); QLOG_INFO() << "Threading: reset started"; mMessageMutex.lock(); for (QWaitCondition * const condition : mMessageQueueConditions.values()) { condition->wakeAll(); } mMessageMutex.unlock(); mThreadsMutex.lock(); for (ScriptThread *thread : mThreads.values()) { mScriptControl.reset(); // TODO: find more sophisticated solution to prevent waiting after abortion thread->abort(); } mFinishedThreads.clear(); mThreadsMutex.unlock(); mScriptControl.reset(); waitForAll(); qDeleteAll(mMessageQueueMutexes); qDeleteAll(mMessageQueueConditions); mMessageQueueMutexes.clear(); mMessageQueueConditions.clear(); mMessageQueues.clear(); QLOG_INFO() << "Threading: reset ended"; mResetStarted = false; } void Threading::threadFinished(const QString &id) { QLOG_INFO() << "Finishing thread" << id; mResetMutex.lock(); mThreadsMutex.lock(); if (!mThreads[id]->error().isEmpty() && mErrorMessage.isEmpty()) { mErrorMessage = mThreads[id]->error(); } QLOG_INFO() << "Thread" << id << "has finished, thread object" << mThreads[id]; mThreads.remove(id); mFinishedThreads.insert(id); mThreadsMutex.unlock(); mResetMutex.unlock(); if (!mErrorMessage.isEmpty()) { reset(); } } void Threading::sendMessage(const QString &threadId, const QScriptValue &message) { if (!tryLockReset()) { return; } mMessageMutex.lock(); if (!mMessageQueueConditions.contains(threadId)) { mMessageQueueMutexes[threadId] = new QMutex(); mMessageQueueConditions[threadId] = new QWaitCondition(); } mMessageQueues[threadId].enqueue(message); mMessageQueueConditions[threadId]->wakeOne(); mMessageMutex.unlock(); mResetMutex.unlock(); } QScriptValue Threading::receiveMessage(bool waitForMessage) { if (!tryLockReset()) { return QScriptValue(); } QString threadId = static_cast<ScriptThread *>(QThread::currentThread())->id(); mMessageMutex.lock(); if (!mMessageQueueConditions.contains(threadId)) { mMessageQueueMutexes[threadId] = new QMutex(); mMessageQueueConditions[threadId] = new QWaitCondition(); } QMutex *mutex = mMessageQueueMutexes[threadId]; QWaitCondition *condition = mMessageQueueConditions[threadId]; QQueue<QScriptValue> &queue = mMessageQueues[threadId]; mMessageMutex.unlock(); mutex->lock(); if (queue.isEmpty()) { mResetMutex.unlock(); if (!waitForMessage) { mutex->unlock(); return QScriptValue(""); } condition->wait(mutex); if (!tryLockReset()) { mutex->unlock(); return QScriptValue(); } } mutex->unlock(); QScriptValue result = queue.dequeue(); mResetMutex.unlock(); return result; } void Threading::killThread(const QString &threadId) { if (!tryLockReset()) { return; } mThreadsMutex.lock(); if (!mThreads.contains(threadId)) { if (!mFinishedThreads.contains(threadId)) { QLOG_INFO() << "Threading: killing thread that is not started yet," << threadId << "will be prevented from running"; mPreventFromStart.insert(threadId); } else { QLOG_INFO() << "Threading: killing already finished thread, ignoring"; } } else { QLOG_INFO() << "Threading: killing thread" << threadId; mThreads[threadId]->abort(); } mThreadsMutex.unlock(); mResetMutex.unlock(); } QString Threading::errorMessage() const { return mErrorMessage; } bool Threading::tryLockReset() { mResetMutex.lock(); if (mResetStarted) { mResetMutex.unlock(); } return !mResetStarted; } bool Threading::inEventDrivenMode() const { return mScriptControl.isInEventDrivenMode(); } <commit_msg>Fixed deadlock when starting script that ends too quickly (with syntax error, for example)<commit_after>/* Copyright 2014 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "threading.h" #include "scriptEngineWorker.h" #include "src/utils.h" #include "src/scriptThread.h" #include <QsLog.h> using namespace trikScriptRunner; Threading::Threading(ScriptEngineWorker *scriptWorker, ScriptExecutionControl &scriptControl) : QObject(scriptWorker) , mResetStarted(false) , mScriptWorker(scriptWorker) , mScriptControl(scriptControl) { } Threading::~Threading() { reset(); } void Threading::startMainThread(const QString &script) { mScript = script; mErrorMessage.clear(); mFinishedThreads.clear(); mPreventFromStart.clear(); QRegExp const mainRegexp("(.*var main\\s*=\\s*\\w*\\s*function\\(.*\\).*)|(.*function\\s+%1\\s*\\(.*\\).*)"); bool needCallMain = mainRegexp.exactMatch(script) && !script.trimmed().endsWith("main();"); startThread("main", mScriptWorker->createScriptEngine(), needCallMain ? script + "\nmain();" : script); } void Threading::startThread(const QScriptValue &threadId, const QScriptValue &function) { startThread(threadId.toString(), cloneEngine(function.engine()), mScript + "\n" + function.toString() + "();"); } void Threading::startThread(const QString &threadId, QScriptEngine *engine, const QString &script) { mResetMutex.lock(); if (mResetStarted) { QLOG_INFO() << "Threading: can't start new thread" << threadId << "with engine" << engine << "due to reset"; delete engine; mResetMutex.unlock(); return; } mThreadsMutex.lock(); if (mThreads.contains(threadId)) { QLOG_ERROR() << "Threading: attempt to create a thread with an already occupied id" << threadId; mErrorMessage = tr("Attempt to create a thread with an already occupied id %1").arg(threadId); mThreads[threadId]->abort(); mThreadsMutex.unlock(); mResetMutex.unlock(); return; } if (mPreventFromStart.contains(threadId)) { QLOG_INFO() << "Threading: attempt to create a thread which must be killed" << threadId; mPreventFromStart.remove(threadId); mFinishedThreads.insert(threadId); mThreadsMutex.unlock(); mResetMutex.unlock(); return; } QLOG_INFO() << "Starting new thread" << threadId << "with engine" << engine; ScriptThread *thread = new ScriptThread(*this, threadId, engine, script); connect(&mScriptControl, SIGNAL(quitSignal()), thread, SIGNAL(stopRunning()), Qt::DirectConnection); mThreads[threadId] = thread; mFinishedThreads.remove(threadId); mThreadsMutex.unlock(); engine->moveToThread(thread); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); // wait until script actually start to avoid problems with multiple starts and resets // TODO: efficient AND safe solution for (int i = 0; i < 500; ++i) { QThread::yieldCurrentThread(); } QLOG_INFO() << "Threading: started thread" << threadId << "with engine" << engine << ", thread object" << thread; mResetMutex.unlock(); } void Threading::waitForAll() { while (!mThreads.isEmpty()) { QThread::yieldCurrentThread(); } } void Threading::joinThread(const QString &threadId) { mThreadsMutex.lock(); while ((!mThreads.contains(threadId) || !mThreads[threadId]->isRunning()) && !mFinishedThreads.contains(threadId)) { mThreadsMutex.unlock(); if (mResetStarted) { return; } QThread::yieldCurrentThread(); mThreadsMutex.lock(); } if (mFinishedThreads.contains(threadId)) { mThreadsMutex.unlock(); return; } ScriptThread *thread = mThreads[threadId]; mThreadsMutex.unlock(); thread->wait(); } QScriptEngine * Threading::cloneEngine(QScriptEngine *engine) { QScriptEngine *result = mScriptWorker->copyScriptEngine(engine); result->evaluate(mScript); return result; } void Threading::reset() { if (!tryLockReset()) { return; } mResetStarted = true; mResetMutex.unlock(); QLOG_INFO() << "Threading: reset started"; mMessageMutex.lock(); for (QWaitCondition * const condition : mMessageQueueConditions.values()) { condition->wakeAll(); } mMessageMutex.unlock(); mThreadsMutex.lock(); for (ScriptThread *thread : mThreads.values()) { mScriptControl.reset(); // TODO: find more sophisticated solution to prevent waiting after abortion thread->abort(); } mFinishedThreads.clear(); mThreadsMutex.unlock(); mScriptControl.reset(); waitForAll(); qDeleteAll(mMessageQueueMutexes); qDeleteAll(mMessageQueueConditions); mMessageQueueMutexes.clear(); mMessageQueueConditions.clear(); mMessageQueues.clear(); QLOG_INFO() << "Threading: reset ended"; mResetStarted = false; } void Threading::threadFinished(const QString &id) { QLOG_INFO() << "Finishing thread" << id; mResetMutex.lock(); mThreadsMutex.lock(); if (!mThreads[id]->error().isEmpty() && mErrorMessage.isEmpty()) { mErrorMessage = mThreads[id]->error(); } QLOG_INFO() << "Thread" << id << "has finished, thread object" << mThreads[id]; mThreads.remove(id); mFinishedThreads.insert(id); mThreadsMutex.unlock(); mResetMutex.unlock(); if (!mErrorMessage.isEmpty()) { reset(); } } void Threading::sendMessage(const QString &threadId, const QScriptValue &message) { if (!tryLockReset()) { return; } mMessageMutex.lock(); if (!mMessageQueueConditions.contains(threadId)) { mMessageQueueMutexes[threadId] = new QMutex(); mMessageQueueConditions[threadId] = new QWaitCondition(); } mMessageQueues[threadId].enqueue(message); mMessageQueueConditions[threadId]->wakeOne(); mMessageMutex.unlock(); mResetMutex.unlock(); } QScriptValue Threading::receiveMessage(bool waitForMessage) { if (!tryLockReset()) { return QScriptValue(); } QString threadId = static_cast<ScriptThread *>(QThread::currentThread())->id(); mMessageMutex.lock(); if (!mMessageQueueConditions.contains(threadId)) { mMessageQueueMutexes[threadId] = new QMutex(); mMessageQueueConditions[threadId] = new QWaitCondition(); } QMutex *mutex = mMessageQueueMutexes[threadId]; QWaitCondition *condition = mMessageQueueConditions[threadId]; QQueue<QScriptValue> &queue = mMessageQueues[threadId]; mMessageMutex.unlock(); mutex->lock(); if (queue.isEmpty()) { mResetMutex.unlock(); if (!waitForMessage) { mutex->unlock(); return QScriptValue(""); } condition->wait(mutex); if (!tryLockReset()) { mutex->unlock(); return QScriptValue(); } } mutex->unlock(); QScriptValue result = queue.dequeue(); mResetMutex.unlock(); return result; } void Threading::killThread(const QString &threadId) { if (!tryLockReset()) { return; } mThreadsMutex.lock(); if (!mThreads.contains(threadId)) { if (!mFinishedThreads.contains(threadId)) { QLOG_INFO() << "Threading: killing thread that is not started yet," << threadId << "will be prevented from running"; mPreventFromStart.insert(threadId); } else { QLOG_INFO() << "Threading: killing already finished thread, ignoring"; } } else { QLOG_INFO() << "Threading: killing thread" << threadId; mThreads[threadId]->abort(); } mThreadsMutex.unlock(); mResetMutex.unlock(); } QString Threading::errorMessage() const { return mErrorMessage; } bool Threading::tryLockReset() { mResetMutex.lock(); if (mResetStarted) { mResetMutex.unlock(); } return !mResetStarted; } bool Threading::inEventDrivenMode() const { return mScriptControl.isInEventDrivenMode(); } <|endoftext|>
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/platform_view_android.h" #include <memory> #include <utility> #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/shell/common/shell_io_manager.h" #include "flutter/shell/gpu/gpu_surface_gl_delegate.h" #include "flutter/shell/platform/android/android_context_gl_impeller.h" #include "flutter/shell/platform/android/android_context_gl_skia.h" #include "flutter/shell/platform/android/android_external_texture_gl.h" #include "flutter/shell/platform/android/android_surface_gl_impeller.h" #include "flutter/shell/platform/android/android_surface_gl_skia.h" #include "flutter/shell/platform/android/android_surface_software.h" #include "flutter/shell/platform/android/context/android_context.h" #include "flutter/shell/platform/android/external_view_embedder/external_view_embedder.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" #include "flutter/shell/platform/android/platform_message_response_android.h" #include "flutter/shell/platform/android/surface/android_surface.h" #include "flutter/shell/platform/android/surface/snapshot_surface_producer.h" #include "flutter/shell/platform/android/vsync_waiter_android.h" namespace flutter { AndroidSurfaceFactoryImpl::AndroidSurfaceFactoryImpl( const std::shared_ptr<AndroidContext>& context, std::shared_ptr<PlatformViewAndroidJNI> jni_facade, bool enable_impeller) : android_context_(context), jni_facade_(jni_facade), enable_impeller_(enable_impeller) {} AndroidSurfaceFactoryImpl::~AndroidSurfaceFactoryImpl() = default; std::unique_ptr<AndroidSurface> AndroidSurfaceFactoryImpl::CreateSurface() { switch (android_context_->RenderingApi()) { case AndroidRenderingAPI::kSoftware: return std::make_unique<AndroidSurfaceSoftware>(android_context_, jni_facade_); case AndroidRenderingAPI::kOpenGLES: if (enable_impeller_) { return std::make_unique<AndroidSurfaceGLImpeller>(android_context_, jni_facade_); } else { return std::make_unique<AndroidSurfaceGLSkia>(android_context_, jni_facade_); } default: FML_DCHECK(false); return nullptr; } } static std::shared_ptr<flutter::AndroidContext> CreateAndroidContext( bool use_software_rendering, const flutter::TaskRunners task_runners, uint8_t msaa_samples, bool enable_impeller) { if (use_software_rendering) { return std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); } if (enable_impeller) { return std::make_unique<AndroidContextGLImpeller>(); } return std::make_unique<AndroidContextGLSkia>( AndroidRenderingAPI::kOpenGLES, // fml::MakeRefCounted<AndroidEnvironmentGL>(), // task_runners, // msaa_samples // ); } PlatformViewAndroid::PlatformViewAndroid( PlatformView::Delegate& delegate, flutter::TaskRunners task_runners, std::shared_ptr<PlatformViewAndroidJNI> jni_facade, bool use_software_rendering, uint8_t msaa_samples) : PlatformViewAndroid( delegate, std::move(task_runners), std::move(jni_facade), CreateAndroidContext( use_software_rendering, task_runners, msaa_samples, delegate.OnPlatformViewGetSettings().enable_impeller)) {} PlatformViewAndroid::PlatformViewAndroid( PlatformView::Delegate& delegate, flutter::TaskRunners task_runners, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade, const std::shared_ptr<flutter::AndroidContext>& android_context) : PlatformView(delegate, std::move(task_runners)), jni_facade_(jni_facade), android_context_(std::move(android_context)), platform_view_android_delegate_(jni_facade), platform_message_handler_(new PlatformMessageHandlerAndroid(jni_facade)) { if (android_context_) { FML_CHECK(android_context_->IsValid()) << "Could not create surface from invalid Android context."; surface_factory_ = std::make_shared<AndroidSurfaceFactoryImpl>( android_context_, jni_facade_, delegate.OnPlatformViewGetSettings().enable_impeller); android_surface_ = surface_factory_->CreateSurface(); FML_CHECK(android_surface_ && android_surface_->IsValid()) << "Could not create an OpenGL, Vulkan or Software surface to set up " "rendering."; } } PlatformViewAndroid::~PlatformViewAndroid() = default; void PlatformViewAndroid::NotifyCreated( fml::RefPtr<AndroidNativeWindow> native_window) { if (android_surface_) { InstallFirstFrameCallback(); fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get(), native_window = std::move(native_window)]() { surface->SetNativeWindow(native_window); latch.Signal(); }); latch.Wait(); } PlatformView::NotifyCreated(); } void PlatformViewAndroid::NotifySurfaceWindowChanged( fml::RefPtr<AndroidNativeWindow> native_window) { if (android_surface_) { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get(), native_window = std::move(native_window)]() { surface->TeardownOnScreenContext(); surface->SetNativeWindow(native_window); latch.Signal(); }); latch.Wait(); } } void PlatformViewAndroid::NotifyDestroyed() { PlatformView::NotifyDestroyed(); if (android_surface_) { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get()]() { surface->TeardownOnScreenContext(); latch.Signal(); }); latch.Wait(); } } void PlatformViewAndroid::NotifyChanged(const SkISize& size) { if (!android_surface_) { return; } fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), // [&latch, surface = android_surface_.get(), size]() { surface->OnScreenSurfaceResize(size); latch.Signal(); }); latch.Wait(); } void PlatformViewAndroid::DispatchPlatformMessage(JNIEnv* env, std::string name, jobject java_message_data, jint java_message_position, jint response_id) { uint8_t* message_data = static_cast<uint8_t*>(env->GetDirectBufferAddress(java_message_data)); fml::MallocMapping message = fml::MallocMapping::Copy(message_data, java_message_position); fml::RefPtr<flutter::PlatformMessageResponse> response; if (response_id) { response = fml::MakeRefCounted<PlatformMessageResponseAndroid>( response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); } PlatformView::DispatchPlatformMessage( std::make_unique<flutter::PlatformMessage>( std::move(name), std::move(message), std::move(response))); } void PlatformViewAndroid::DispatchEmptyPlatformMessage(JNIEnv* env, std::string name, jint response_id) { fml::RefPtr<flutter::PlatformMessageResponse> response; if (response_id) { response = fml::MakeRefCounted<PlatformMessageResponseAndroid>( response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); } PlatformView::DispatchPlatformMessage( std::make_unique<flutter::PlatformMessage>(std::move(name), std::move(response))); } // |PlatformView| void PlatformViewAndroid::HandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { // Called from the ui thread. platform_message_handler_->HandlePlatformMessage(std::move(message)); } // |PlatformView| void PlatformViewAndroid::OnPreEngineRestart() const { jni_facade_->FlutterViewOnPreEngineRestart(); } void PlatformViewAndroid::DispatchSemanticsAction(JNIEnv* env, jint id, jint action, jobject args, jint args_position) { if (env->IsSameObject(args, NULL)) { PlatformView::DispatchSemanticsAction( id, static_cast<flutter::SemanticsAction>(action), fml::MallocMapping()); return; } uint8_t* args_data = static_cast<uint8_t*>(env->GetDirectBufferAddress(args)); auto args_vector = fml::MallocMapping::Copy(args_data, args_position); PlatformView::DispatchSemanticsAction( id, static_cast<flutter::SemanticsAction>(action), std::move(args_vector)); } // |PlatformView| void PlatformViewAndroid::UpdateSemantics( flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) { platform_view_android_delegate_.UpdateSemantics(update, actions); } void PlatformViewAndroid::RegisterExternalTexture( int64_t texture_id, const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture) { if (android_context_->RenderingApi() == AndroidRenderingAPI::kOpenGLES) { RegisterTexture(std::make_shared<AndroidExternalTextureGL>( texture_id, surface_texture, std::move(jni_facade_))); } else { FML_LOG(INFO) << "Attempted to use a GL texture in a non GL context."; } } // |PlatformView| std::unique_ptr<VsyncWaiter> PlatformViewAndroid::CreateVSyncWaiter() { return std::make_unique<VsyncWaiterAndroid>(task_runners_); } // |PlatformView| std::unique_ptr<Surface> PlatformViewAndroid::CreateRenderingSurface() { if (!android_surface_) { return nullptr; } return android_surface_->CreateGPUSurface( android_context_->GetMainSkiaContext().get()); } // |PlatformView| std::shared_ptr<ExternalViewEmbedder> PlatformViewAndroid::CreateExternalViewEmbedder() { return std::make_shared<AndroidExternalViewEmbedder>( *android_context_, jni_facade_, surface_factory_, task_runners_); } // |PlatformView| std::unique_ptr<SnapshotSurfaceProducer> PlatformViewAndroid::CreateSnapshotSurfaceProducer() { if (!android_surface_) { return nullptr; } return std::make_unique<AndroidSnapshotSurfaceProducer>(*android_surface_); } // |PlatformView| sk_sp<GrDirectContext> PlatformViewAndroid::CreateResourceContext() const { if (!android_surface_) { return nullptr; } sk_sp<GrDirectContext> resource_context; if (android_surface_->ResourceContextMakeCurrent()) { // TODO(chinmaygarde): Currently, this code depends on the fact that only // the OpenGL surface will be able to make a resource context current. If // this changes, this assumption breaks. Handle the same. resource_context = ShellIOManager::CreateCompatibleResourceLoadingContext( GrBackend::kOpenGL_GrBackend, GPUSurfaceGLDelegate::GetDefaultPlatformGLInterface()); } else { FML_DLOG(ERROR) << "Could not make the resource context current."; } return resource_context; } // |PlatformView| void PlatformViewAndroid::ReleaseResourceContext() const { if (android_surface_) { android_surface_->ResourceContextClearCurrent(); } } // |PlatformView| std::unique_ptr<std::vector<std::string>> PlatformViewAndroid::ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data) { return jni_facade_->FlutterViewComputePlatformResolvedLocale( supported_locale_data); } // |PlatformView| void PlatformViewAndroid::RequestDartDeferredLibrary(intptr_t loading_unit_id) { if (jni_facade_->RequestDartDeferredLibrary(loading_unit_id)) { return; } return; // TODO(garyq): Call LoadDartDeferredLibraryFailure() } // |PlatformView| void PlatformViewAndroid::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions) { delegate_.LoadDartDeferredLibrary(loading_unit_id, std::move(snapshot_data), std::move(snapshot_instructions)); } // |PlatformView| void PlatformViewAndroid::LoadDartDeferredLibraryError( intptr_t loading_unit_id, const std::string error_message, bool transient) { delegate_.LoadDartDeferredLibraryError(loading_unit_id, error_message, transient); } // |PlatformView| void PlatformViewAndroid::UpdateAssetResolverByType( std::unique_ptr<AssetResolver> updated_asset_resolver, AssetResolver::AssetResolverType type) { delegate_.UpdateAssetResolverByType(std::move(updated_asset_resolver), type); } void PlatformViewAndroid::InstallFirstFrameCallback() { // On Platform Task Runner. SetNextFrameCallback( [platform_view = GetWeakPtr(), platform_task_runner = task_runners_.GetPlatformTaskRunner()]() { // On GPU Task Runner. platform_task_runner->PostTask([platform_view]() { // Back on Platform Task Runner. if (platform_view) { reinterpret_cast<PlatformViewAndroid*>(platform_view.get()) ->FireFirstFrameCallback(); } }); }); } void PlatformViewAndroid::FireFirstFrameCallback() { jni_facade_->FlutterViewOnFirstFrame(); } } // namespace flutter <commit_msg>Guard impeller references in platform_view_android.cc for google build (#33487)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/platform_view_android.h" #include <memory> #include <utility> #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/shell/common/shell_io_manager.h" #include "flutter/shell/gpu/gpu_surface_gl_delegate.h" #if IMPELLER_SUPPORTS_PLATFORM #include "flutter/shell/platform/android/android_context_gl_impeller.h" #endif #include "flutter/shell/platform/android/android_context_gl_skia.h" #include "flutter/shell/platform/android/android_external_texture_gl.h" #if IMPELLER_SUPPORTS_PLATFORM #include "flutter/shell/platform/android/android_surface_gl_impeller.h" #endif #include "flutter/shell/platform/android/android_surface_gl_skia.h" #include "flutter/shell/platform/android/android_surface_software.h" #include "flutter/shell/platform/android/context/android_context.h" #include "flutter/shell/platform/android/external_view_embedder/external_view_embedder.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" #include "flutter/shell/platform/android/platform_message_response_android.h" #include "flutter/shell/platform/android/surface/android_surface.h" #include "flutter/shell/platform/android/surface/snapshot_surface_producer.h" #include "flutter/shell/platform/android/vsync_waiter_android.h" namespace flutter { AndroidSurfaceFactoryImpl::AndroidSurfaceFactoryImpl( const std::shared_ptr<AndroidContext>& context, std::shared_ptr<PlatformViewAndroidJNI> jni_facade, bool enable_impeller) : android_context_(context), jni_facade_(jni_facade), enable_impeller_(enable_impeller) {} AndroidSurfaceFactoryImpl::~AndroidSurfaceFactoryImpl() = default; std::unique_ptr<AndroidSurface> AndroidSurfaceFactoryImpl::CreateSurface() { switch (android_context_->RenderingApi()) { case AndroidRenderingAPI::kSoftware: return std::make_unique<AndroidSurfaceSoftware>(android_context_, jni_facade_); case AndroidRenderingAPI::kOpenGLES: #if IMPELLER_SUPPORTS_PLATFORM if (enable_impeller_) { return std::make_unique<AndroidSurfaceGLImpeller>(android_context_, jni_facade_); } else { #endif return std::make_unique<AndroidSurfaceGLSkia>(android_context_, jni_facade_); #if IMPELLER_SUPPORTS_PLATFORM } #endif default: FML_DCHECK(false); return nullptr; } } static std::shared_ptr<flutter::AndroidContext> CreateAndroidContext( bool use_software_rendering, const flutter::TaskRunners task_runners, uint8_t msaa_samples, bool enable_impeller) { if (use_software_rendering) { return std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); } #if IMPELLER_SUPPORTS_PLATFORM if (enable_impeller) { return std::make_unique<AndroidContextGLImpeller>(); } #endif return std::make_unique<AndroidContextGLSkia>( AndroidRenderingAPI::kOpenGLES, // fml::MakeRefCounted<AndroidEnvironmentGL>(), // task_runners, // msaa_samples // ); } PlatformViewAndroid::PlatformViewAndroid( PlatformView::Delegate& delegate, flutter::TaskRunners task_runners, std::shared_ptr<PlatformViewAndroidJNI> jni_facade, bool use_software_rendering, uint8_t msaa_samples) : PlatformViewAndroid( delegate, std::move(task_runners), std::move(jni_facade), CreateAndroidContext( use_software_rendering, task_runners, msaa_samples, delegate.OnPlatformViewGetSettings().enable_impeller)) {} PlatformViewAndroid::PlatformViewAndroid( PlatformView::Delegate& delegate, flutter::TaskRunners task_runners, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade, const std::shared_ptr<flutter::AndroidContext>& android_context) : PlatformView(delegate, std::move(task_runners)), jni_facade_(jni_facade), android_context_(std::move(android_context)), platform_view_android_delegate_(jni_facade), platform_message_handler_(new PlatformMessageHandlerAndroid(jni_facade)) { if (android_context_) { FML_CHECK(android_context_->IsValid()) << "Could not create surface from invalid Android context."; surface_factory_ = std::make_shared<AndroidSurfaceFactoryImpl>( android_context_, jni_facade_, delegate.OnPlatformViewGetSettings().enable_impeller); android_surface_ = surface_factory_->CreateSurface(); FML_CHECK(android_surface_ && android_surface_->IsValid()) << "Could not create an OpenGL, Vulkan or Software surface to set up " "rendering."; } } PlatformViewAndroid::~PlatformViewAndroid() = default; void PlatformViewAndroid::NotifyCreated( fml::RefPtr<AndroidNativeWindow> native_window) { if (android_surface_) { InstallFirstFrameCallback(); fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get(), native_window = std::move(native_window)]() { surface->SetNativeWindow(native_window); latch.Signal(); }); latch.Wait(); } PlatformView::NotifyCreated(); } void PlatformViewAndroid::NotifySurfaceWindowChanged( fml::RefPtr<AndroidNativeWindow> native_window) { if (android_surface_) { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get(), native_window = std::move(native_window)]() { surface->TeardownOnScreenContext(); surface->SetNativeWindow(native_window); latch.Signal(); }); latch.Wait(); } } void PlatformViewAndroid::NotifyDestroyed() { PlatformView::NotifyDestroyed(); if (android_surface_) { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get()]() { surface->TeardownOnScreenContext(); latch.Signal(); }); latch.Wait(); } } void PlatformViewAndroid::NotifyChanged(const SkISize& size) { if (!android_surface_) { return; } fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), // [&latch, surface = android_surface_.get(), size]() { surface->OnScreenSurfaceResize(size); latch.Signal(); }); latch.Wait(); } void PlatformViewAndroid::DispatchPlatformMessage(JNIEnv* env, std::string name, jobject java_message_data, jint java_message_position, jint response_id) { uint8_t* message_data = static_cast<uint8_t*>(env->GetDirectBufferAddress(java_message_data)); fml::MallocMapping message = fml::MallocMapping::Copy(message_data, java_message_position); fml::RefPtr<flutter::PlatformMessageResponse> response; if (response_id) { response = fml::MakeRefCounted<PlatformMessageResponseAndroid>( response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); } PlatformView::DispatchPlatformMessage( std::make_unique<flutter::PlatformMessage>( std::move(name), std::move(message), std::move(response))); } void PlatformViewAndroid::DispatchEmptyPlatformMessage(JNIEnv* env, std::string name, jint response_id) { fml::RefPtr<flutter::PlatformMessageResponse> response; if (response_id) { response = fml::MakeRefCounted<PlatformMessageResponseAndroid>( response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); } PlatformView::DispatchPlatformMessage( std::make_unique<flutter::PlatformMessage>(std::move(name), std::move(response))); } // |PlatformView| void PlatformViewAndroid::HandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { // Called from the ui thread. platform_message_handler_->HandlePlatformMessage(std::move(message)); } // |PlatformView| void PlatformViewAndroid::OnPreEngineRestart() const { jni_facade_->FlutterViewOnPreEngineRestart(); } void PlatformViewAndroid::DispatchSemanticsAction(JNIEnv* env, jint id, jint action, jobject args, jint args_position) { if (env->IsSameObject(args, NULL)) { PlatformView::DispatchSemanticsAction( id, static_cast<flutter::SemanticsAction>(action), fml::MallocMapping()); return; } uint8_t* args_data = static_cast<uint8_t*>(env->GetDirectBufferAddress(args)); auto args_vector = fml::MallocMapping::Copy(args_data, args_position); PlatformView::DispatchSemanticsAction( id, static_cast<flutter::SemanticsAction>(action), std::move(args_vector)); } // |PlatformView| void PlatformViewAndroid::UpdateSemantics( flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) { platform_view_android_delegate_.UpdateSemantics(update, actions); } void PlatformViewAndroid::RegisterExternalTexture( int64_t texture_id, const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture) { if (android_context_->RenderingApi() == AndroidRenderingAPI::kOpenGLES) { RegisterTexture(std::make_shared<AndroidExternalTextureGL>( texture_id, surface_texture, std::move(jni_facade_))); } else { FML_LOG(INFO) << "Attempted to use a GL texture in a non GL context."; } } // |PlatformView| std::unique_ptr<VsyncWaiter> PlatformViewAndroid::CreateVSyncWaiter() { return std::make_unique<VsyncWaiterAndroid>(task_runners_); } // |PlatformView| std::unique_ptr<Surface> PlatformViewAndroid::CreateRenderingSurface() { if (!android_surface_) { return nullptr; } return android_surface_->CreateGPUSurface( android_context_->GetMainSkiaContext().get()); } // |PlatformView| std::shared_ptr<ExternalViewEmbedder> PlatformViewAndroid::CreateExternalViewEmbedder() { return std::make_shared<AndroidExternalViewEmbedder>( *android_context_, jni_facade_, surface_factory_, task_runners_); } // |PlatformView| std::unique_ptr<SnapshotSurfaceProducer> PlatformViewAndroid::CreateSnapshotSurfaceProducer() { if (!android_surface_) { return nullptr; } return std::make_unique<AndroidSnapshotSurfaceProducer>(*android_surface_); } // |PlatformView| sk_sp<GrDirectContext> PlatformViewAndroid::CreateResourceContext() const { if (!android_surface_) { return nullptr; } sk_sp<GrDirectContext> resource_context; if (android_surface_->ResourceContextMakeCurrent()) { // TODO(chinmaygarde): Currently, this code depends on the fact that only // the OpenGL surface will be able to make a resource context current. If // this changes, this assumption breaks. Handle the same. resource_context = ShellIOManager::CreateCompatibleResourceLoadingContext( GrBackend::kOpenGL_GrBackend, GPUSurfaceGLDelegate::GetDefaultPlatformGLInterface()); } else { FML_DLOG(ERROR) << "Could not make the resource context current."; } return resource_context; } // |PlatformView| void PlatformViewAndroid::ReleaseResourceContext() const { if (android_surface_) { android_surface_->ResourceContextClearCurrent(); } } // |PlatformView| std::unique_ptr<std::vector<std::string>> PlatformViewAndroid::ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data) { return jni_facade_->FlutterViewComputePlatformResolvedLocale( supported_locale_data); } // |PlatformView| void PlatformViewAndroid::RequestDartDeferredLibrary(intptr_t loading_unit_id) { if (jni_facade_->RequestDartDeferredLibrary(loading_unit_id)) { return; } return; // TODO(garyq): Call LoadDartDeferredLibraryFailure() } // |PlatformView| void PlatformViewAndroid::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions) { delegate_.LoadDartDeferredLibrary(loading_unit_id, std::move(snapshot_data), std::move(snapshot_instructions)); } // |PlatformView| void PlatformViewAndroid::LoadDartDeferredLibraryError( intptr_t loading_unit_id, const std::string error_message, bool transient) { delegate_.LoadDartDeferredLibraryError(loading_unit_id, error_message, transient); } // |PlatformView| void PlatformViewAndroid::UpdateAssetResolverByType( std::unique_ptr<AssetResolver> updated_asset_resolver, AssetResolver::AssetResolverType type) { delegate_.UpdateAssetResolverByType(std::move(updated_asset_resolver), type); } void PlatformViewAndroid::InstallFirstFrameCallback() { // On Platform Task Runner. SetNextFrameCallback( [platform_view = GetWeakPtr(), platform_task_runner = task_runners_.GetPlatformTaskRunner()]() { // On GPU Task Runner. platform_task_runner->PostTask([platform_view]() { // Back on Platform Task Runner. if (platform_view) { reinterpret_cast<PlatformViewAndroid*>(platform_view.get()) ->FireFirstFrameCallback(); } }); }); } void PlatformViewAndroid::FireFirstFrameCallback() { jni_facade_->FlutterViewOnFirstFrame(); } } // namespace flutter <|endoftext|>
<commit_before>#include "ExternalInput.h" #include "../WebRtcConnection.h" #include "../RTPSink.h" #include <cstdio> #include <boost/cstdint.hpp> #include <sys/time.h> #include <arpa/inet.h> namespace erizo { ExternalInput::ExternalInput(const std::string& inputUrl){ sourcefbSink_=NULL; context_ = NULL; sendVideoBuffer_=NULL; running_ = false; url_ = inputUrl; } ExternalInput::~ExternalInput(){ printf("Destructor EI\n"); this->closeSource(); } int ExternalInput::init(){ context_ = avformat_alloc_context(); av_register_all(); avcodec_register_all(); avformat_network_init(); //open rtsp printf("trying to open input\n"); int res = avformat_open_input(&context_, url_.c_str(),NULL,NULL); char errbuff[500]; printf ("RES %d\n", res); if(res != 0){ av_strerror(res, (char*)(&errbuff), 500); printf("fail when opening input %s\n", errbuff); return false; } res = avformat_find_stream_info(context_,NULL); if(res!=0){ av_strerror(res, (char*)(&errbuff), 500); printf("fail when finding stream info %s\n", errbuff); return false; } VideoCodecInfo info; int streamNo = av_find_best_stream(context_, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); if (streamNo < 0){ printf("No video stream?\n"); return false; } sendVideoBuffer_ = (char*) malloc(2000); video_stream_index_ = streamNo; AVStream* st = context_->streams[streamNo]; inCodec_.initDecoder(st->codec); bufflen_ = st->codec->width*st->codec->height*3/2; decodedBuffer_ = (unsigned char*) malloc(bufflen_); MediaInfo om; om.proccessorType = RTP_ONLY; om.videoCodec.codec = VIDEO_CODEC_VP8; om.videoCodec.bitRate = 1000000; om.videoCodec.width = 640; om.videoCodec.height = 480; om.videoCodec.frameRate = 20; om.hasVideo = true; om.hasAudio = false; if (om.hasAudio) { om.audioCodec.sampleRate = 8000; om.audioCodec.bitRate = 64000; } op_ = new OutputProcessor(); op_->init(om, this); printf("Success initializing external input for codec %s\n", st->codec->codec_name); av_init_packet(&avpacket_); AVStream* stream=NULL; int cnt = 0; thread_ = boost::thread(&ExternalInput::receiveLoop, this); running_ = true; encodeThread_ = boost::thread(&ExternalInput::encodeLoop, this); return true; } void ExternalInput::closeSource() { running_ = false; encodeThread_.join(); thread_.join(); av_free_packet(&avpacket_); if (context_!=NULL) avformat_free_context(context_); if (sendVideoBuffer_!=NULL) free(sendVideoBuffer_); if(decodedBuffer_!=NULL) free(decodedBuffer_); } int ExternalInput::sendFirPacket() { return 0; } void ExternalInput::receiveRtpData(unsigned char*rtpdata, int len) { if (videoSink_!=NULL){ memcpy(sendVideoBuffer_, rtpdata, len); videoSink_->deliverVideoData(sendVideoBuffer_, len); } } void ExternalInput::receiveLoop(){ av_read_play(context_);//play RTSP int gotDecodedFrame = 0; while(av_read_frame(context_,&avpacket_)>=0&& running_==true){//read 100 frames if(avpacket_.stream_index == video_stream_index_){//packet is video // packet.stream_index = stream->id; inCodec_.decodeVideo(avpacket_.data, avpacket_.size, decodedBuffer_, bufflen_, &gotDecodedFrame); RawDataPacket packetR; if (gotDecodedFrame){ packetR.data = decodedBuffer_; packetR.length = bufflen_; packetR.type = VIDEO; queueMutex_.lock(); packetQueue_.push(packetR); queueMutex_.unlock(); gotDecodedFrame=0; } } av_free_packet(&avpacket_); av_init_packet(&avpacket_); } running_=false; av_read_pause(context_); } void ExternalInput::encodeLoop() { while (running_ == true) { queueMutex_.lock(); if (packetQueue_.size() > 0) { op_->receiveRawData(packetQueue_.front()); packetQueue_.pop(); // printf("Queue Size! %d\n", packetQueue_.size()); queueMutex_.unlock(); } else { queueMutex_.unlock(); usleep(1000); } } } } <commit_msg>Fixed error codes<commit_after>#include "ExternalInput.h" #include "../WebRtcConnection.h" #include "../RTPSink.h" #include <cstdio> #include <boost/cstdint.hpp> #include <sys/time.h> #include <arpa/inet.h> namespace erizo { ExternalInput::ExternalInput(const std::string& inputUrl){ sourcefbSink_=NULL; context_ = NULL; sendVideoBuffer_=NULL; running_ = false; url_ = inputUrl; } ExternalInput::~ExternalInput(){ printf("Destructor EI\n"); this->closeSource(); } int ExternalInput::init(){ context_ = avformat_alloc_context(); av_register_all(); avcodec_register_all(); avformat_network_init(); //open rtsp printf("trying to open input\n"); int res = avformat_open_input(&context_, url_.c_str(),NULL,NULL); char errbuff[500]; printf ("RES %d\n", res); if(res != 0){ av_strerror(res, (char*)(&errbuff), 500); printf("fail when opening input %s\n", errbuff); return res; } res = avformat_find_stream_info(context_,NULL); if(res!=0){ av_strerror(res, (char*)(&errbuff), 500); printf("fail when finding stream info %s\n", errbuff); return res; } VideoCodecInfo info; int streamNo = av_find_best_stream(context_, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); if (streamNo < 0){ printf("No video stream?\n"); return streamNo; } sendVideoBuffer_ = (char*) malloc(2000); video_stream_index_ = streamNo; AVStream* st = context_->streams[streamNo]; inCodec_.initDecoder(st->codec); bufflen_ = st->codec->width*st->codec->height*3/2; decodedBuffer_ = (unsigned char*) malloc(bufflen_); MediaInfo om; om.proccessorType = RTP_ONLY; om.videoCodec.codec = VIDEO_CODEC_VP8; om.videoCodec.bitRate = 1000000; om.videoCodec.width = 640; om.videoCodec.height = 480; om.videoCodec.frameRate = 20; om.hasVideo = true; om.hasAudio = false; if (om.hasAudio) { om.audioCodec.sampleRate = 8000; om.audioCodec.bitRate = 64000; } op_ = new OutputProcessor(); op_->init(om, this); printf("Success initializing external input for codec %s\n", st->codec->codec_name); av_init_packet(&avpacket_); AVStream* stream=NULL; int cnt = 0; thread_ = boost::thread(&ExternalInput::receiveLoop, this); running_ = true; encodeThread_ = boost::thread(&ExternalInput::encodeLoop, this); return true; } void ExternalInput::closeSource() { running_ = false; encodeThread_.join(); thread_.join(); av_free_packet(&avpacket_); if (context_!=NULL) avformat_free_context(context_); if (sendVideoBuffer_!=NULL) free(sendVideoBuffer_); if(decodedBuffer_!=NULL) free(decodedBuffer_); } int ExternalInput::sendFirPacket() { return 0; } void ExternalInput::receiveRtpData(unsigned char*rtpdata, int len) { if (videoSink_!=NULL){ memcpy(sendVideoBuffer_, rtpdata, len); videoSink_->deliverVideoData(sendVideoBuffer_, len); } } void ExternalInput::receiveLoop(){ av_read_play(context_);//play RTSP int gotDecodedFrame = 0; while(av_read_frame(context_,&avpacket_)>=0&& running_==true){//read 100 frames if(avpacket_.stream_index == video_stream_index_){//packet is video // packet.stream_index = stream->id; inCodec_.decodeVideo(avpacket_.data, avpacket_.size, decodedBuffer_, bufflen_, &gotDecodedFrame); RawDataPacket packetR; if (gotDecodedFrame){ packetR.data = decodedBuffer_; packetR.length = bufflen_; packetR.type = VIDEO; queueMutex_.lock(); packetQueue_.push(packetR); queueMutex_.unlock(); gotDecodedFrame=0; } } av_free_packet(&avpacket_); av_init_packet(&avpacket_); } running_=false; av_read_pause(context_); } void ExternalInput::encodeLoop() { while (running_ == true) { queueMutex_.lock(); if (packetQueue_.size() > 0) { op_->receiveRawData(packetQueue_.front()); packetQueue_.pop(); // printf("Queue Size! %d\n", packetQueue_.size()); queueMutex_.unlock(); } else { queueMutex_.unlock(); usleep(1000); } } } } <|endoftext|>
<commit_before>#include "ControlUtil.h" #include <algorithm> #include <limits> #include <cmath> using namespace std; typedef Matrix<double, 6,1> Vector6d; struct PelvisMotionControlData { RigidBodyManipulator* r; double alpha; double pelvis_height_previous; double nominal_pelvis_height; Vector6d Kp; Vector6d Kd; int pelvis_body_index; int rfoot_body_index; int lfoot_body_index; }; // TODO: remove me---stick me in controlUtil in drake and templetize template <typename DerivedPhi1, typename DerivedPhi2, typename DerivedD> void angleDiff(const MatrixBase<DerivedPhi1>& phi1, const MatrixBase<DerivedPhi2>& phi2, MatrixBase<DerivedD>& d) { d = phi2 - phi1; for (int i = 0; i < phi1.rows(); i++) { for (int j = 0; j < phi1.cols(); j++) { if (d(i,j) < -M_PI) { d(i,j) = fmod(d(i,j) + M_PI, 2*M_PI) + M_PI; } else { d(i,j) = fmod(d(i,j) + M_PI, 2*M_PI) - M_PI; } } } } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs<1) mexErrMsgTxt("usage: ptr = pelvisMotionControlmex(0,robot_obj,alpha,nominal_pelvis_height,Kp,Kd); y=pelvisMotionControlmex(ptr,x)"); if (nlhs<1) mexErrMsgTxt("take at least one output... please."); struct PelvisMotionControlData* pdata; double* pr; if (mxGetScalar(prhs[0])==0) { // then construct the data object and return pdata = new struct PelvisMotionControlData; // get robot mex model ptr if (!mxIsNumeric(prhs[1]) || mxGetNumberOfElements(prhs[1])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the second argument should be the robot mex ptr"); memcpy(&(pdata->r),mxGetData(prhs[1]),sizeof(pdata->r)); if (!mxIsNumeric(prhs[2]) || mxGetNumberOfElements(prhs[2])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the third argument should be alpha"); memcpy(&(pdata->alpha),mxGetPr(prhs[2]),sizeof(pdata->alpha)); if (!mxIsNumeric(prhs[3]) || mxGetNumberOfElements(prhs[3])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the third argument should be nominal_pelvis_height"); memcpy(&(pdata->nominal_pelvis_height),mxGetPr(prhs[3]),sizeof(pdata->nominal_pelvis_height)); if (!mxIsNumeric(prhs[4]) || mxGetM(prhs[4])!=6 || mxGetN(prhs[4])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fourth argument should be Kp"); memcpy(&(pdata->Kp),mxGetPr(prhs[4]),sizeof(pdata->Kp)); if (!mxIsNumeric(prhs[5]) || mxGetM(prhs[5])!=6 || mxGetN(prhs[5])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fifth argument should be Kd"); memcpy(&(pdata->Kd),mxGetPr(prhs[5]),sizeof(pdata->Kd)); mxClassID cid; if (sizeof(pdata)==4) cid = mxUINT32_CLASS; else if (sizeof(pdata)==8) cid = mxUINT64_CLASS; else mexErrMsgIdAndTxt("Drake:pelvisMotionControlmex:PointerSize","Are you on a 32-bit machine or 64-bit machine??"); pdata->pelvis_height_previous = -1; pdata->pelvis_body_index = pdata->r->findLinkInd("pelvis", 0); pdata->rfoot_body_index = pdata->r->findLinkInd("r_foot", 0); pdata->lfoot_body_index = pdata->r->findLinkInd("l_foot", 0); plhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL); memcpy(mxGetData(plhs[0]),&pdata,sizeof(pdata)); return; } // first get the ptr back from matlab if (!mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the first argument should be the ptr"); memcpy(&pdata,mxGetData(prhs[0]),sizeof(pdata)); int nq = pdata->r->num_dof; double *q = mxGetPr(prhs[1]); double *qd = &q[nq]; Map<VectorXd> qdvec(qd,nq); pdata->r->doKinematics(q,false,qd); // TODO: this must be updated to use quaternions/spatial velocity Vector6d pelvis_pose,rfoot_pose,lfoot_pose; MatrixXd Jpelvis = MatrixXd::Zero(6,pdata->r->num_dof); Vector4d zero = Vector4d::Zero(); zero(3) = 1.0; pdata->r->forwardKin(pdata->pelvis_body_index,zero,1,pelvis_pose); pdata->r->forwardJac(pdata->pelvis_body_index,zero,1,Jpelvis); pdata->r->forwardKin(pdata->rfoot_body_index,zero,1,rfoot_pose); pdata->r->forwardKin(pdata->lfoot_body_index,zero,1,lfoot_pose); if (pdata->pelvis_height_previous<0) { pdata->pelvis_height_previous = pelvis_pose(2); } double min_foot_z = min(lfoot_pose(2),rfoot_pose(2)); double mean_foot_yaw = (lfoot_pose(5)+rfoot_pose(5))/2.0; double pelvis_height_desired = pdata->alpha*pdata->pelvis_height_previous + (1.0-pdata->alpha)*(min_foot_z + pdata->nominal_pelvis_height); pdata->pelvis_height_previous = pelvis_pose(2); Vector6d body_des; double nan = std::numeric_limits<double>::quiet_NaN(); body_des << nan,nan,pelvis_height_desired,0,0,mean_foot_yaw; Vector6d error; error.head<3>()= body_des.head<3>()-pelvis_pose.head<3>(); Vector3d error_rpy; angleDiff(body_des.tail<3>(),pelvis_pose.tail<3>(),error_rpy); error.tail(3) = error_rpy; Matrix<double,6,1> body_vdot = (pdata->Kp.array()*error.array()).matrix() - (pdata->Kd.array()*(Jpelvis*qdvec).array()).matrix(); plhs[0] = eigenToMatlab(body_vdot); }<commit_msg>fixed bug in angle diff call<commit_after>#include "ControlUtil.h" #include <algorithm> #include <limits> #include <cmath> using namespace std; typedef Matrix<double, 6,1> Vector6d; struct PelvisMotionControlData { RigidBodyManipulator* r; double alpha; double pelvis_height_previous; double nominal_pelvis_height; Vector6d Kp; Vector6d Kd; int pelvis_body_index; int rfoot_body_index; int lfoot_body_index; }; // TODO: remove me---stick me in controlUtil in drake and templetize template <typename DerivedPhi1, typename DerivedPhi2, typename DerivedD> void angleDiff(const MatrixBase<DerivedPhi1>& phi1, const MatrixBase<DerivedPhi2>& phi2, MatrixBase<DerivedD>& d) { d = phi2 - phi1; for (int i = 0; i < phi1.rows(); i++) { for (int j = 0; j < phi1.cols(); j++) { if (d(i,j) < -M_PI) { d(i,j) = fmod(d(i,j) + M_PI, 2*M_PI) + M_PI; } else { d(i,j) = fmod(d(i,j) + M_PI, 2*M_PI) - M_PI; } } } } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs<1) mexErrMsgTxt("usage: ptr = pelvisMotionControlmex(0,robot_obj,alpha,nominal_pelvis_height,Kp,Kd); y=pelvisMotionControlmex(ptr,x)"); if (nlhs<1) mexErrMsgTxt("take at least one output... please."); struct PelvisMotionControlData* pdata; if (mxGetScalar(prhs[0])==0) { // then construct the data object and return pdata = new struct PelvisMotionControlData; // get robot mex model ptr if (!mxIsNumeric(prhs[1]) || mxGetNumberOfElements(prhs[1])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the second argument should be the robot mex ptr"); memcpy(&(pdata->r),mxGetData(prhs[1]),sizeof(pdata->r)); if (!mxIsNumeric(prhs[2]) || mxGetNumberOfElements(prhs[2])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the third argument should be alpha"); memcpy(&(pdata->alpha),mxGetPr(prhs[2]),sizeof(pdata->alpha)); if (!mxIsNumeric(prhs[3]) || mxGetNumberOfElements(prhs[3])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fourth argument should be nominal_pelvis_height"); memcpy(&(pdata->nominal_pelvis_height),mxGetPr(prhs[3]),sizeof(pdata->nominal_pelvis_height)); if (!mxIsNumeric(prhs[4]) || mxGetM(prhs[4])!=6 || mxGetN(prhs[4])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the fifth argument should be Kp"); memcpy(&(pdata->Kp),mxGetPr(prhs[4]),sizeof(pdata->Kp)); if (!mxIsNumeric(prhs[5]) || mxGetM(prhs[5])!=6 || mxGetN(prhs[5])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the sixth argument should be Kd"); memcpy(&(pdata->Kd),mxGetPr(prhs[5]),sizeof(pdata->Kd)); mxClassID cid; if (sizeof(pdata)==4) cid = mxUINT32_CLASS; else if (sizeof(pdata)==8) cid = mxUINT64_CLASS; else mexErrMsgIdAndTxt("Drake:pelvisMotionControlmex:PointerSize","Are you on a 32-bit machine or 64-bit machine??"); pdata->pelvis_height_previous = -1; pdata->pelvis_body_index = pdata->r->findLinkInd("pelvis", 0); pdata->rfoot_body_index = pdata->r->findLinkInd("r_foot", 0); pdata->lfoot_body_index = pdata->r->findLinkInd("l_foot", 0); plhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL); memcpy(mxGetData(plhs[0]),&pdata,sizeof(pdata)); return; } // first get the ptr back from matlab if (!mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1) mexErrMsgIdAndTxt("DRC:pelvisMotionControlmex:BadInputs","the first argument should be the ptr"); memcpy(&pdata,mxGetData(prhs[0]),sizeof(pdata)); int nq = pdata->r->num_dof; double *q = mxGetPr(prhs[1]); double *qd = &q[nq]; Map<VectorXd> qdvec(qd,nq); pdata->r->doKinematics(q,false,qd); // TODO: this must be updated to use quaternions/spatial velocity Vector6d pelvis_pose,rfoot_pose,lfoot_pose; MatrixXd Jpelvis = MatrixXd::Zero(6,pdata->r->num_dof); Vector4d zero = Vector4d::Zero(); zero(3) = 1.0; pdata->r->forwardKin(pdata->pelvis_body_index,zero,1,pelvis_pose); pdata->r->forwardJac(pdata->pelvis_body_index,zero,1,Jpelvis); pdata->r->forwardKin(pdata->rfoot_body_index,zero,1,rfoot_pose); pdata->r->forwardKin(pdata->lfoot_body_index,zero,1,lfoot_pose); if (pdata->pelvis_height_previous<0) { pdata->pelvis_height_previous = pelvis_pose(2); } double min_foot_z = min(lfoot_pose(2),rfoot_pose(2)); double mean_foot_yaw = (lfoot_pose(5)+rfoot_pose(5))/2.0; double pelvis_height_desired = pdata->alpha*pdata->pelvis_height_previous + (1.0-pdata->alpha)*(min_foot_z + pdata->nominal_pelvis_height); pdata->pelvis_height_previous = pelvis_pose(2); Vector6d body_des; double nan = std::numeric_limits<double>::quiet_NaN(); body_des << nan,nan,pelvis_height_desired,0,0,mean_foot_yaw; Vector6d error; error.head<3>()= body_des.head<3>()-pelvis_pose.head<3>(); Vector3d error_rpy; angleDiff(pelvis_pose.tail<3>(),body_des.tail<3>(),error_rpy); error.tail(3) = error_rpy; Matrix<double,6,1> body_vdot = (pdata->Kp.array()*error.array()).matrix() - (pdata->Kd.array()*(Jpelvis*qdvec).array()).matrix(); plhs[0] = eigenToMatlab(body_vdot); }<|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "kalarmdclient.h" #include "kalarmd/alarmdaemoniface_stub.h" #include <kstandarddirs.h> #include <kprocess.h> #include <dcopclient.h> #include <kapplication.h> #include <kdebug.h> #include <qstring.h> #include <qfile.h> KalarmdClient::KalarmdClient() : mAlarmDaemonIface("kalarmd","ad") { } KalarmdClient::~KalarmdClient() { } void KalarmdClient::startDaemon() { if( !kapp->dcopClient()->isApplicationRegistered( "kalarmd" ) ) { // Start alarmdaemon. It is a KUniqueApplication, that means it is // automatically made sure that there is only one instance of the alarm daemon // running. QString execStr = locate( "exe", "kalarmd" ); system( QFile::encodeName( execStr ) ); } if( kapp->dcopClient()->isApplicationRegistered( "korgac" ) ) { // Alarm daemon already registered return; } KProcess *proc = new KProcess; *proc << "korgac"; *proc << "--miniicon" << "korganizer"; connect( proc, SIGNAL( processExited( KProcess* ) ), SLOT( startCompleted( KProcess* ) ) ); if( !proc->start() ) delete proc; } void KalarmdClient::startCompleted( KProcess* process ) { delete process; // Register this application with the alarm daemon AlarmDaemonIface_stub stub( "kalarmd", "ad" ); stub.registerApp( "korgac", "KOrganizer", "ac", 3, true ); if( !stub.ok() ) { kdDebug() << "KalarmdClient::startCompleted(): dcop send failed" << endl; } } bool KalarmdClient::addCalendar( const KURL &url ) { mAlarmDaemonIface.addCal( "korgac", url.url() ); return mAlarmDaemonIface.ok(); } bool KalarmdClient::removeCalendar( const KURL &url ) { mAlarmDaemonIface.removeCal( url.url() ); return mAlarmDaemonIface.ok(); } bool KalarmdClient::reloadCalendar( const KURL &url ) { mAlarmDaemonIface.reloadCal( "korgac", url.url() ); return mAlarmDaemonIface.ok(); } <commit_msg>Includemoc<commit_after>/* This file is part of KOrganizer. Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "kalarmdclient.h" #include "kalarmdclient.moc" #include "kalarmd/alarmdaemoniface_stub.h" #include <kstandarddirs.h> #include <kprocess.h> #include <dcopclient.h> #include <kapplication.h> #include <kdebug.h> #include <qstring.h> #include <qfile.h> KalarmdClient::KalarmdClient() : mAlarmDaemonIface("kalarmd","ad") { } KalarmdClient::~KalarmdClient() { } void KalarmdClient::startDaemon() { if( !kapp->dcopClient()->isApplicationRegistered( "kalarmd" ) ) { // Start alarmdaemon. It is a KUniqueApplication, that means it is // automatically made sure that there is only one instance of the alarm daemon // running. QString execStr = locate( "exe", "kalarmd" ); system( QFile::encodeName( execStr ) ); } if( kapp->dcopClient()->isApplicationRegistered( "korgac" ) ) { // Alarm daemon already registered return; } KProcess *proc = new KProcess; *proc << "korgac"; *proc << "--miniicon" << "korganizer"; connect( proc, SIGNAL( processExited( KProcess* ) ), SLOT( startCompleted( KProcess* ) ) ); if( !proc->start() ) delete proc; } void KalarmdClient::startCompleted( KProcess* process ) { delete process; // Register this application with the alarm daemon AlarmDaemonIface_stub stub( "kalarmd", "ad" ); stub.registerApp( "korgac", "KOrganizer", "ac", 3, true ); if( !stub.ok() ) { kdDebug() << "KalarmdClient::startCompleted(): dcop send failed" << endl; } } bool KalarmdClient::addCalendar( const KURL &url ) { mAlarmDaemonIface.addCal( "korgac", url.url() ); return mAlarmDaemonIface.ok(); } bool KalarmdClient::removeCalendar( const KURL &url ) { mAlarmDaemonIface.removeCal( url.url() ); return mAlarmDaemonIface.ok(); } bool KalarmdClient::reloadCalendar( const KURL &url ) { mAlarmDaemonIface.reloadCal( "korgac", url.url() ); return mAlarmDaemonIface.ok(); } <|endoftext|>
<commit_before>/** * @file * * @date 12.04.2021 * @author Alexander Kalmuk */ #include <stdio.h> #include <drivers/video/fb.h> #include <util/log.h> #include <algorithm> #include <cv_embox_imshowfb.hpp> void imshowfb(cv::Mat& img, int fbx) { struct fb_info *fbi; int w, h; fbi = fb_lookup(fbx); if (!fbi) { fprintf(stderr, "%s: fb%d not found\n", __func__, fbx); return; } log_debug("\nimage width: %d\n" "image height: %d\n" "image size: %dx%d\n" "image depth: %d\n" "image channels: %d\n" "image type: %d", img.cols, img.rows, img.size().width, img.size().height, img.depth(), img.channels(), img.type()); if (img.channels() != 1 && img.channels() != 3) { fprintf(stderr, "%s: Unsupported channels count: %d\n", __func__, img.channels()); return; } if (fbi->var.fmt != BGRA8888 && fbi->var.fmt != RGBA8888) { fprintf(stderr, "%s: Unsupported framebuffer format: %d\n", __func__, fbi->var.fmt); return; } h = std::min((int) fbi->var.yres, img.rows); w = std::min((int) (fbi->var.bits_per_pixel * fbi->var.xres) / 8, img.channels() * img.cols); for (int y = 0; y < h; y++) { const uchar *row = &img.at<uchar>(y, 0); for (int x = 0; x < w; x += img.channels()) { uint32_t pixel = 0; switch (img.channels()) { case 1: { unsigned val = unsigned(row[x]); pixel = 0xFF000000 | val | (val << 8) | (val << 16); break; } case 3: { uint32_t in; in = unsigned(row[x + 2]) | (unsigned(row[x + 1]) << 8) | (unsigned(row[x]) << 16); pix_fmt_convert(&in, &pixel, 1, RGB888, fbi->var.fmt); break; } default: break; } ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / img.channels()] = pixel; } } } <commit_msg>opencv: Clear fb with a white color in cv_embox_imshowfb<commit_after>/** * @file * * @date 12.04.2021 * @author Alexander Kalmuk */ #include <stdio.h> #include <drivers/video/fb.h> #include <util/log.h> #include <algorithm> #include <cv_embox_imshowfb.hpp> void imshowfb(cv::Mat& img, int fbx) { struct fb_info *fbi; int w, h; fbi = fb_lookup(fbx); if (!fbi) { fprintf(stderr, "%s: fb%d not found\n", __func__, fbx); return; } log_debug("\nimage width: %d\n" "image height: %d\n" "image size: %dx%d\n" "image depth: %d\n" "image channels: %d\n" "image type: %d", img.cols, img.rows, img.size().width, img.size().height, img.depth(), img.channels(), img.type()); if (img.channels() != 1 && img.channels() != 3) { fprintf(stderr, "%s: Unsupported channels count: %d\n", __func__, img.channels()); return; } if (fbi->var.fmt != BGRA8888 && fbi->var.fmt != RGBA8888) { fprintf(stderr, "%s: Unsupported framebuffer format: %d\n", __func__, fbi->var.fmt); return; } h = std::min((int) fbi->var.yres, img.rows); w = std::min((int) (fbi->var.bits_per_pixel * fbi->var.xres) / 8, img.channels() * img.cols); /* Clear fb with white color. */ memset(fbi->screen_base, 0xff, (fbi->var.xres * fbi->var.yres * fbi->var.bits_per_pixel) / 8); for (int y = 0; y < h; y++) { const uchar *row = &img.at<uchar>(y, 0); for (int x = 0; x < w; x += img.channels()) { uint32_t pixel = 0; switch (img.channels()) { case 1: { unsigned val = unsigned(row[x]); pixel = 0xFF000000 | val | (val << 8) | (val << 16); break; } case 3: { uint32_t in; in = unsigned(row[x + 2]) | (unsigned(row[x + 1]) << 8) | (unsigned(row[x]) << 16); pix_fmt_convert(&in, &pixel, 1, RGB888, fbi->var.fmt); break; } default: break; } ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / img.channels()] = pixel; } } } <|endoftext|>
<commit_before>#ifndef _PROPHY_GENERATED_FULL_Unions_HPP #define _PROPHY_GENERATED_FULL_Unions_HPP #include <stdint.h> #include <numeric> #include <vector> #include <string> #include <prophy/array.hpp> #include <prophy/endianness.hpp> #include <prophy/optional.hpp> #include <prophy/detail/byte_size.hpp> #include <prophy/detail/message.hpp> #include <prophy/detail/mpl.hpp> #include "Arrays.ppf.hpp" namespace prophy { namespace generated { struct Union : prophy::detail::message<Union> { enum { encoded_byte_size = 12 }; enum _discriminator { discriminator_a = 1, discriminator_b = 2, discriminator_c = 3 } discriminator; typedef prophy::detail::int2type<discriminator_a> _discriminator_a_t; typedef prophy::detail::int2type<discriminator_b> _discriminator_b_t; typedef prophy::detail::int2type<discriminator_c> _discriminator_c_t; static const _discriminator_a_t discriminator_a_t; static const _discriminator_b_t discriminator_b_t; static const _discriminator_c_t discriminator_c_t; uint8_t a; uint32_t b; Builtin c; Union(): discriminator(discriminator_a), a(), b() { } Union(_discriminator_a_t, uint8_t _1): discriminator(discriminator_a), a(_1) { } Union(_discriminator_b_t, uint32_t _1): discriminator(discriminator_b), b(_1) { } Union(_discriminator_c_t, const Builtin& _1): discriminator(discriminator_c), c(_1) { } size_t get_byte_size() const { return 12; } }; struct BuiltinOptional : prophy::detail::message<BuiltinOptional> { enum { encoded_byte_size = 8 }; optional<uint32_t> x; BuiltinOptional() { } BuiltinOptional(const optional<uint32_t>& _1): x(_1) { } size_t get_byte_size() const { return 8; } }; struct FixcompOptional : prophy::detail::message<FixcompOptional> { enum { encoded_byte_size = 12 }; optional<Builtin> x; FixcompOptional() { } FixcompOptional(const optional<Builtin>& _1): x(_1) { } size_t get_byte_size() const { return 12; } }; } // namespace generated } // namespace prophy #endif /* _PROPHY_GENERATED_FULL_Unions_HPP */ <commit_msg>less code generated, discriminator_a_ is not required anywhere<commit_after>#ifndef _PROPHY_GENERATED_FULL_Unions_HPP #define _PROPHY_GENERATED_FULL_Unions_HPP #include <stdint.h> #include <numeric> #include <vector> #include <string> #include <prophy/array.hpp> #include <prophy/endianness.hpp> #include <prophy/optional.hpp> #include <prophy/detail/byte_size.hpp> #include <prophy/detail/message.hpp> #include <prophy/detail/mpl.hpp> #include "Arrays.ppf.hpp" namespace prophy { namespace generated { struct Union : prophy::detail::message<Union> { enum { encoded_byte_size = 12 }; enum _discriminator { discriminator_a = 1, discriminator_b = 2, discriminator_c = 3 } discriminator; static const prophy::detail::int2type<discriminator_a> discriminator_a_t; static const prophy::detail::int2type<discriminator_b> discriminator_b_t; static const prophy::detail::int2type<discriminator_c> discriminator_c_t; uint8_t a; uint32_t b; Builtin c; Union(): discriminator(discriminator_a), a(), b() { } Union(prophy::detail::int2type<discriminator_a>, uint8_t _1): discriminator(discriminator_a), a(_1) { } Union(prophy::detail::int2type<discriminator_b>, uint32_t _1): discriminator(discriminator_b), b(_1) { } Union(prophy::detail::int2type<discriminator_c>, const Builtin& _1): discriminator(discriminator_c), c(_1) { } size_t get_byte_size() const { return 12; } }; struct BuiltinOptional : prophy::detail::message<BuiltinOptional> { enum { encoded_byte_size = 8 }; optional<uint32_t> x; BuiltinOptional() { } BuiltinOptional(const optional<uint32_t>& _1): x(_1) { } size_t get_byte_size() const { return 8; } }; struct FixcompOptional : prophy::detail::message<FixcompOptional> { enum { encoded_byte_size = 12 }; optional<Builtin> x; FixcompOptional() { } FixcompOptional(const optional<Builtin>& _1): x(_1) { } size_t get_byte_size() const { return 12; } }; } // namespace generated } // namespace prophy #endif /* _PROPHY_GENERATED_FULL_Unions_HPP */ <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_OS2014_HH #define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_OS2014_HH #include <memory> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/expression.hh> #include <dune/pymor/functions/default.hh> #include "../../../linearelliptic/problems/default.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Problems { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim = 1 > class OS2014 { static_assert(AlwaysFalse< EntityImp >::value, "Not available for dimRange > 1!"); }; template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class OS2014< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > : public Default< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > { typedef Default< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > BaseType; typedef OS2014< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ThisType; typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ConstantScalarFunctionType; typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ConstantMatrixFunctionType; typedef Pymor::Function::NonparametricDefault< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ParametricScalarFunctionType; typedef Pymor::Function::NonparametricDefault< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ParametricMatrixFunctionType; typedef Stuff::Functions::Expression< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ExpressionFunctionType; typedef Pymor::Function::AffinelyDecomposableDefault< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > DefaultParametricFunctionType; typedef typename ConstantMatrixFunctionType::RangeType MatrixType; public: static std::string static_id() { return BaseType::BaseType::static_id() + ".OS2014"; } static Stuff::Common::ConfigTree default_config(const std::string sub_name = "") { Stuff::Common::ConfigTree config("integration_order", "3"); if (sub_name.empty()) return config; else { Stuff::Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Stuff::Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { const Stuff::Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; return Stuff::Common::make_unique< ThisType >(cfg.get("integration_order", default_config().get< size_t >("integration_order"))); } // ... create(...) OS2014(const size_t integration_order = default_config().get< size_t >("integration_order")) : BaseType(create_diffusion_factor_(integration_order), std::make_shared< ParametricMatrixFunctionType >(new ConstantMatrixFunctionType(unit_matrix_(), "diffusion_tensor")), std::make_shared< ParametricScalarFunctionType >(new ConstantScalarFunctionType(1, "force")), std::make_shared< ParametricScalarFunctionType >(new ConstantScalarFunctionType(0, "dirichlet")), std::make_shared< ParametricScalarFunctionType >(new ConstantScalarFunctionType(0, "neumann"))) {} virtual std::string type() const DS_OVERRIDE { return BaseType::BaseType::static_id() + ".ESV2007"; } private: static MatrixType unit_matrix_() { MatrixType matrix(RangeFieldImp(0)); matrix[0][0] = RangeFieldImp(1); matrix[1][1] = RangeFieldImp(1); return matrix; } static std::shared_ptr< DefaultParametricFunctionType > create_diffusion_factor_(const size_t integration_order) { auto ret = std::make_shared< DefaultParametricFunctionType >(new ExpressionFunctionType( "x", "1+sin(2*pi*x[0])*sin(2*pi*x[1])", integration_order, "sin")); ret->register_component(new ExpressionFunctionType("x", "-sin(2*pi*x[0])*sin(2*pi*x[1])", integration_order, "sin"), new Pymor::ParameterFunctional("mu", 1, "mu")); return ret; } // ... create_diffusion_factor_(...) }; // class OS2014< ..., 1 > } // namespace Problems } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_OS2014_HH <commit_msg>[linearelliptic.problems.OS2014]<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_OS2014_HH #define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_OS2014_HH #include <memory> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/expression.hh> #include <dune/pymor/functions/default.hh> #include "../../../linearelliptic/problems/default.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Problems { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim = 1 > class OS2014 { static_assert(AlwaysFalse< EntityImp >::value, "Not available for dimRange > 1!"); }; template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class OS2014< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > : public Default< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > { typedef Default< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > BaseType; typedef OS2014< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ThisType; typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ConstantScalarFunctionType; typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ConstantMatrixFunctionType; typedef Pymor::Function::NonparametricDefault< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ParametricScalarFunctionType; typedef Pymor::Function::NonparametricDefault< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ParametricMatrixFunctionType; typedef Stuff::Functions::Expression< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > ExpressionFunctionType; typedef Pymor::Function::AffinelyDecomposableDefault< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1 > DefaultParametricFunctionType; typedef typename ConstantMatrixFunctionType::RangeType MatrixType; public: static std::string static_id() { return BaseType::BaseType::static_id() + ".OS2014"; } static Stuff::Common::ConfigTree default_config(const std::string sub_name = "") { Stuff::Common::ConfigTree config("integration_order", "3"); if (sub_name.empty()) return config; else { Stuff::Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Stuff::Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { const Stuff::Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; return Stuff::Common::make_unique< ThisType >(cfg.get("integration_order", default_config().get< size_t >("integration_order"))); } // ... create(...) OS2014(const size_t integration_order = default_config().get< size_t >("integration_order")) : BaseType(create_diffusion_factor_(integration_order), std::make_shared< ParametricMatrixFunctionType >(new ConstantMatrixFunctionType(unit_matrix_(), "diffusion_tensor")), std::make_shared< ParametricScalarFunctionType >(new ConstantScalarFunctionType(1, "force")), std::make_shared< ParametricScalarFunctionType >(new ConstantScalarFunctionType(0, "dirichlet")), std::make_shared< ParametricScalarFunctionType >(new ConstantScalarFunctionType(0, "neumann"))) {} virtual std::string type() const DS_OVERRIDE { return BaseType::BaseType::static_id() + ".OS2014"; } private: static MatrixType unit_matrix_() { MatrixType matrix(RangeFieldImp(0)); matrix[0][0] = RangeFieldImp(1); matrix[1][1] = RangeFieldImp(1); return matrix; } static std::shared_ptr< DefaultParametricFunctionType > create_diffusion_factor_(const size_t integration_order) { auto ret = std::make_shared< DefaultParametricFunctionType >(new ExpressionFunctionType( "x", "1+sin(2*pi*x[0])*sin(2*pi*x[1])", integration_order, "affine_part")); ret->register_component(new ExpressionFunctionType("x", "-sin(2*pi*x[0])*sin(2*pi*x[1])", integration_order, "component_0"), new Pymor::ParameterFunctional("mu", 1, "mu")); return ret; } // ... create_diffusion_factor_(...) }; // class OS2014< ..., 1 > } // namespace Problems } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_OS2014_HH <|endoftext|>
<commit_before>// Copyright (c) 2016 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <string.h> #include "../basic/TConfig.h" #include "TSocketSupport.h" #include "TEndian.h" #include "TInetAddress.h" namespace tyr { namespace net { static const in_addr_t kInAddrAny = INADDR_ANY; static const in_addr_t kInAddrLoopback = INADDR_LOOPBACK; static_assert(sizeof(InetAddress) == sizeof(struct sockaddr_in6), "InetAddress is same size as sockaddr_in6"); static_assert(offsetof(sockaddr_in, sin_family) == 0, "sin_family offset must be 0"); static_assert(offsetof(sockaddr_in6, sin6_family) == 0, "sin6_family offset must be 0"); static_assert(offsetof(sockaddr_in, sin_port) == 2, "sin_port offset must be 2"); static_assert(offsetof(sockaddr_in6, sin6_port) == 2, "sin6_port offset must be 2"); InetAddress::InetAddress(uint16_t port, bool loopback_only, bool ipv6) { static_assert(offsetof(InetAddress, addr_) == 0, "addr_ offset must be 0"); static_assert(offsetof(InetAddress, addr6_) == 0, "addr6_ offset must be 0"); if (ipv6) { memset(&addr6_, 0, sizeof(addr6_)); addr6_.sin6_family = AF_INET6; addr6_.sin6_addr = loopback_only ? in6addr_loopback : in6addr_any; addr6_.sin6_port = host_to_net16(port); } else { memset(&addr_, 0, sizeof(addr_)); addr_.sin_family = AF_INET; addr_.sin_addr.s_addr = host_to_net32(loopback_only ? kInAddrLoopback : kInAddrAny); addr_.sin_port = host_to_net16(port); } } InetAddress::InetAddress(basic::StringPiece host, uint16_t port, bool ipv6) { if (ipv6) { memset(&addr6_, 0, sizeof(addr6_)); SocketSupport::kern_from_ip_port(host.data(), port, &addr6_); } else { memset(&addr_, 0, sizeof(addr_)); SocketSupport::kern_from_ip_port(host.data(), port, &addr_); } } std::string InetAddress::to_host(void) const { char buf[64] = {0}; SocketSupport::kern_to_ip(buf, sizeof(buf), get_address()); return buf; } std::string InetAddress::to_host_port(void) const { char buf[64] = {0}; SocketSupport::kern_to_ip_port(buf, sizeof(buf), get_address()); return buf; } uint16_t InetAddress::to_port(void) const { return net_to_host16(get_port_endian()); } uint32_t InetAddress::get_host_endian(void) const { assert(get_family() == AF_INET); return addr_.sin_addr.s_addr; } #if defined(TYR_WINDOWS) static __declspec(thread) char t_resolve_buff[64* 1024]; #else static __thread char t_resolve_buff[64* 1024]; #endif // bool InetAddress::resolve(basic::StringPiece hostname, InetAddress* result) { // struct hostent hent = {0}; // struct hostent* hentp = nullptr; // int herrno = 0; // // int ret = gethostbyname(hostname.data(), &hent, t_resolve_buff, sizeof(t_resolve_buff), &hentp, &herrno); // // return true; // } }} <commit_msg>:sparkles: chore(resolve): add resolve method for InetAddress<commit_after>// Copyright (c) 2016 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <string.h> #include "../basic/TConfig.h" #include "../basic/TLogging.h" #include "TSocketSupport.h" #include "TEndian.h" #include "TInetAddress.h" namespace tyr { namespace net { static const in_addr_t kInAddrAny = INADDR_ANY; static const in_addr_t kInAddrLoopback = INADDR_LOOPBACK; static_assert(sizeof(InetAddress) == sizeof(struct sockaddr_in6), "InetAddress is same size as sockaddr_in6"); static_assert(offsetof(sockaddr_in, sin_family) == 0, "sin_family offset must be 0"); static_assert(offsetof(sockaddr_in6, sin6_family) == 0, "sin6_family offset must be 0"); static_assert(offsetof(sockaddr_in, sin_port) == 2, "sin_port offset must be 2"); static_assert(offsetof(sockaddr_in6, sin6_port) == 2, "sin6_port offset must be 2"); InetAddress::InetAddress(uint16_t port, bool loopback_only, bool ipv6) { static_assert(offsetof(InetAddress, addr_) == 0, "addr_ offset must be 0"); static_assert(offsetof(InetAddress, addr6_) == 0, "addr6_ offset must be 0"); if (ipv6) { memset(&addr6_, 0, sizeof(addr6_)); addr6_.sin6_family = AF_INET6; addr6_.sin6_addr = loopback_only ? in6addr_loopback : in6addr_any; addr6_.sin6_port = host_to_net16(port); } else { memset(&addr_, 0, sizeof(addr_)); addr_.sin_family = AF_INET; addr_.sin_addr.s_addr = host_to_net32(loopback_only ? kInAddrLoopback : kInAddrAny); addr_.sin_port = host_to_net16(port); } } InetAddress::InetAddress(basic::StringPiece host, uint16_t port, bool ipv6) { if (ipv6) { memset(&addr6_, 0, sizeof(addr6_)); SocketSupport::kern_from_ip_port(host.data(), port, &addr6_); } else { memset(&addr_, 0, sizeof(addr_)); SocketSupport::kern_from_ip_port(host.data(), port, &addr_); } } std::string InetAddress::to_host(void) const { char buf[64] = {0}; SocketSupport::kern_to_ip(buf, sizeof(buf), get_address()); return buf; } std::string InetAddress::to_host_port(void) const { char buf[64] = {0}; SocketSupport::kern_to_ip_port(buf, sizeof(buf), get_address()); return buf; } uint16_t InetAddress::to_port(void) const { return net_to_host16(get_port_endian()); } uint32_t InetAddress::get_host_endian(void) const { assert(get_family() == AF_INET); return addr_.sin_addr.s_addr; } #if defined(TYR_WINDOWS) static __declspec(thread) char t_resolve_buff[64* 1024]; #else static __thread char t_resolve_buff[64* 1024]; #endif bool InetAddress::resolve(basic::StringPiece hostname, InetAddress* result) { struct hostent* hentp = nullptr; int ret = 0; #if defined(TYR_WINDOWS) hentp = gethostbyname(hostname.data()); if (nullptr == hentp) ret = -1; #else struct hostent hent = {0}; int herrno = 0; ret = gethostbyname_r(hostname.data(), &hent, t_resolve_buff, sizeof(t_resolve_buff), &hentp, &herrno); #endif if (0 == ret && nullptr != hentp) { assert(hentp->h_addrtype == AF_INET && hentp->h_length == sizeof(uint32_t)); result->addr_.sin_addr = *reinterpret_cast<struct in_addr*>(hentp->h_addr); return true; } else { if (0 != ret) TYRLOG_SYSERR << "InetAddress::resolve"; return false; } } }} <|endoftext|>
<commit_before>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <string> #include <vector> #include "elang/compiler/semantics/formatters/text_formatter.h" #include "base/containers/adapters.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "elang/compiler/ast/class.h" #include "elang/compiler/ast/enum.h" #include "elang/compiler/ast/method.h" #include "elang/compiler/ast/types.h" #include "elang/compiler/semantics/nodes.h" #include "elang/compiler/semantics/visitor.h" #include "elang/compiler/parameter_kind.h" namespace base { std::ostream& operator<<(std::ostream& ostream, const base::StringPiece16& piece) { return ostream << base::UTF16ToUTF8(piece.as_string()); } } // namespace base namespace elang { namespace compiler { namespace sm { namespace { ////////////////////////////////////////////////////////////////////// // // Formatter // class Formatter final : public Visitor { public: explicit Formatter(std::ostream* ostream); ~Formatter() = default; void Format(const sm::Semantic* semantic); private: // Visitor #define V(Name) void Visit##Name(Name* semantic) final; FOR_EACH_CONCRETE_SEMANTIC(V) #undef V std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(Formatter); }; Formatter::Formatter(std::ostream* ostream) : ostream_(*ostream) { } void Formatter::Format(const Semantic* semantic) { const_cast<Semantic*>(semantic)->Accept(this); } struct AsPath { Semantic* last_component; }; std::ostream& operator<<(std::ostream& ostream, const AsPath& path) { std::vector<Semantic*> components; for (auto runner = path.last_component; runner && runner->name(); runner = runner->outer()) { components.push_back(runner); } auto separator = ""; for (auto component : base::Reversed(components)) { ostream << separator << component->name(); separator = "."; } return ostream; } // Visitor // Element type of array type is omitting left most rank, e.g. // element_type_of(T[A]) = T // element_type_of(T[A][B}) = T[B] // element_type_of(T[A][B}[C]) = T[B][C] void Formatter::VisitArrayType(ArrayType* semantic) { std::vector<ArrayType*> array_types; for (Type* runner = semantic; runner->is<ArrayType>(); runner = runner->as<ArrayType>()->element_type()) { array_types.push_back(runner->as<ArrayType>()); } ostream_ << *array_types.back()->element_type(); for (auto array_type : array_types) { ostream_ << "["; auto separator = ""; auto separator2 = ""; for (auto dimension : array_type->dimensions()) { ostream_ << separator; if (dimension >= 0) ostream_ << separator2 << dimension; separator = ","; separator2 = " "; } ostream_ << "]"; } } void Formatter::VisitClass(Class* node) { if (!node->has_base()) { ostream_ << "#" << AsPath{node}; return; } ostream_ << AsPath{node}; } void Formatter::VisitEnum(Enum* node) { if (!node->has_base()) { ostream_ << "#enum " << AsPath{node}; return; } ostream_ << "enum " << AsPath{node} << " : " << AsPath{node->enum_base()} << " {"; auto separator = ""; for (auto const member : node->members()) { ostream_ << separator << *member->name(); if (member->has_value()) ostream_ << " = " << *member->value(); separator = ", "; } ostream_ << "}"; } void Formatter::VisitEnumMember(EnumMember* node) { ostream_ << AsPath{node->owner()} << "." << node->name(); if (!node->has_value()) return; ostream_ << " = " << *node->value(); } void Formatter::VisitInvalidValue(InvalidValue* node) { ostream_ << "InvalidValue(" << *node->type() << ", " << node->token() << ")"; } void Formatter::VisitField(Field* node) { ostream_ << AsPath{node}; } void Formatter::VisitLiteral(Literal* literal) { ostream_ << *literal->data(); } void Formatter::VisitMethod(Method* method) { ostream_ << *method->return_type() << " " << AsPath{method} << "("; auto separator = ""; for (auto const parameter : method->parameters()) { ostream_ << separator << *parameter->type(); separator = ", "; } ostream_ << ")"; } void Formatter::VisitMethodGroup(MethodGroup* method_group) { ostream_ << *method_group->owner() << "." << method_group->name() << "{"; auto separator = ""; for (auto const method : method_group->methods()) { ostream_ << separator << *method; separator = ", "; } ostream_ << "}"; } void Formatter::VisitNamespace(Namespace* node) { if (!node->name()) { ostream_ << "global_namespace"; return; } ostream_ << "namespace " << AsPath{node}; } void Formatter::VisitParameter(Parameter* parameter) { ostream_ << *parameter->type(); if (parameter->kind() == ParameterKind::Rest) ostream_ << "..."; ostream_ << " " << *parameter->name(); if (parameter->kind() == ParameterKind::Optional) ostream_ << " = " << *parameter->default_value(); } void Formatter::VisitSignature(Signature* signature) { ostream_ << *signature->return_type() << " "; auto separator = ""; for (auto const parameter : signature->parameters()) { ostream_ << separator << *parameter; separator = ", "; } ostream_ << ")"; } void Formatter::VisitUndefinedType(UndefinedType* node) { ostream_ << "UndefinedType(" << *node->token() << ")"; } void Formatter::VisitVariable(Variable* variable) { ostream_ << variable->storage() << " " << *variable->type() << " " << variable->ast_node()->name(); } } // namespace std::ostream& operator<<(std::ostream& ostream, const Semantic& semantic) { Formatter formatter(&ostream); formatter.Format(&semantic); return ostream; } std::ostream& operator<<(std::ostream& ostream, const Semantic* semantic) { if (!semantic) return ostream << "nil"; return ostream << *semantic; } std::ostream& operator<<(std::ostream& ostream, StorageClass storage_class) { static const char* const texts[] = { #define V(Name) #Name, FOR_EACH_STORAGE_CLASS(V) #undef V "Invalid", }; return ostream << texts[std::min(static_cast<size_t>(storage_class), arraysize(texts) - 1)]; } ////////////////////////////////////////////////////////////////////// // // TextFormatter // TextFormatter::TextFormatter(std::ostream* ostream) : ostream_(*ostream) { } TextFormatter::~TextFormatter() { } void TextFormatter::Format(const Semantic* semantic) { Formatter formatter(&ostream_); formatter.Format(semantic); } } // namespace sm } // namespace compiler } // namespace elang <commit_msg>elang/compiler/semantics: Simplify |EnumMember| printer.<commit_after>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <string> #include <vector> #include "elang/compiler/semantics/formatters/text_formatter.h" #include "base/containers/adapters.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "elang/compiler/ast/class.h" #include "elang/compiler/ast/enum.h" #include "elang/compiler/ast/method.h" #include "elang/compiler/ast/types.h" #include "elang/compiler/semantics/nodes.h" #include "elang/compiler/semantics/visitor.h" #include "elang/compiler/parameter_kind.h" namespace base { std::ostream& operator<<(std::ostream& ostream, const base::StringPiece16& piece) { return ostream << base::UTF16ToUTF8(piece.as_string()); } } // namespace base namespace elang { namespace compiler { namespace sm { namespace { ////////////////////////////////////////////////////////////////////// // // Formatter // class Formatter final : public Visitor { public: explicit Formatter(std::ostream* ostream); ~Formatter() = default; void Format(const sm::Semantic* semantic); private: // Visitor #define V(Name) void Visit##Name(Name* semantic) final; FOR_EACH_CONCRETE_SEMANTIC(V) #undef V std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(Formatter); }; Formatter::Formatter(std::ostream* ostream) : ostream_(*ostream) { } void Formatter::Format(const Semantic* semantic) { const_cast<Semantic*>(semantic)->Accept(this); } struct AsPath { Semantic* last_component; }; std::ostream& operator<<(std::ostream& ostream, const AsPath& path) { std::vector<Semantic*> components; for (auto runner = path.last_component; runner && runner->name(); runner = runner->outer()) { components.push_back(runner); } auto separator = ""; for (auto component : base::Reversed(components)) { ostream << separator << component->name(); separator = "."; } return ostream; } // Visitor // Element type of array type is omitting left most rank, e.g. // element_type_of(T[A]) = T // element_type_of(T[A][B}) = T[B] // element_type_of(T[A][B}[C]) = T[B][C] void Formatter::VisitArrayType(ArrayType* semantic) { std::vector<ArrayType*> array_types; for (Type* runner = semantic; runner->is<ArrayType>(); runner = runner->as<ArrayType>()->element_type()) { array_types.push_back(runner->as<ArrayType>()); } ostream_ << *array_types.back()->element_type(); for (auto array_type : array_types) { ostream_ << "["; auto separator = ""; auto separator2 = ""; for (auto dimension : array_type->dimensions()) { ostream_ << separator; if (dimension >= 0) ostream_ << separator2 << dimension; separator = ","; separator2 = " "; } ostream_ << "]"; } } void Formatter::VisitClass(Class* node) { if (!node->has_base()) { ostream_ << "#" << AsPath{node}; return; } ostream_ << AsPath{node}; } void Formatter::VisitEnum(Enum* node) { if (!node->has_base()) { ostream_ << "#enum " << AsPath{node}; return; } ostream_ << "enum " << AsPath{node} << " : " << AsPath{node->enum_base()} << " {"; auto separator = ""; for (auto const member : node->members()) { ostream_ << separator << *member->name(); if (member->has_value()) ostream_ << " = " << *member->value(); separator = ", "; } ostream_ << "}"; } void Formatter::VisitEnumMember(EnumMember* node) { ostream_ << AsPath{node}; if (!node->has_value()) return; ostream_ << " = " << *node->value(); } void Formatter::VisitInvalidValue(InvalidValue* node) { ostream_ << "InvalidValue(" << *node->type() << ", " << node->token() << ")"; } void Formatter::VisitField(Field* node) { ostream_ << AsPath{node}; } void Formatter::VisitLiteral(Literal* literal) { ostream_ << *literal->data(); } void Formatter::VisitMethod(Method* method) { ostream_ << *method->return_type() << " " << AsPath{method} << "("; auto separator = ""; for (auto const parameter : method->parameters()) { ostream_ << separator << *parameter->type(); separator = ", "; } ostream_ << ")"; } void Formatter::VisitMethodGroup(MethodGroup* method_group) { ostream_ << *method_group->owner() << "." << method_group->name() << "{"; auto separator = ""; for (auto const method : method_group->methods()) { ostream_ << separator << *method; separator = ", "; } ostream_ << "}"; } void Formatter::VisitNamespace(Namespace* node) { if (!node->name()) { ostream_ << "global_namespace"; return; } ostream_ << "namespace " << AsPath{node}; } void Formatter::VisitParameter(Parameter* parameter) { ostream_ << *parameter->type(); if (parameter->kind() == ParameterKind::Rest) ostream_ << "..."; ostream_ << " " << *parameter->name(); if (parameter->kind() == ParameterKind::Optional) ostream_ << " = " << *parameter->default_value(); } void Formatter::VisitSignature(Signature* signature) { ostream_ << *signature->return_type() << " "; auto separator = ""; for (auto const parameter : signature->parameters()) { ostream_ << separator << *parameter; separator = ", "; } ostream_ << ")"; } void Formatter::VisitUndefinedType(UndefinedType* node) { ostream_ << "UndefinedType(" << *node->token() << ")"; } void Formatter::VisitVariable(Variable* variable) { ostream_ << variable->storage() << " " << *variable->type() << " " << variable->ast_node()->name(); } } // namespace std::ostream& operator<<(std::ostream& ostream, const Semantic& semantic) { Formatter formatter(&ostream); formatter.Format(&semantic); return ostream; } std::ostream& operator<<(std::ostream& ostream, const Semantic* semantic) { if (!semantic) return ostream << "nil"; return ostream << *semantic; } std::ostream& operator<<(std::ostream& ostream, StorageClass storage_class) { static const char* const texts[] = { #define V(Name) #Name, FOR_EACH_STORAGE_CLASS(V) #undef V "Invalid", }; return ostream << texts[std::min(static_cast<size_t>(storage_class), arraysize(texts) - 1)]; } ////////////////////////////////////////////////////////////////////// // // TextFormatter // TextFormatter::TextFormatter(std::ostream* ostream) : ostream_(*ostream) { } TextFormatter::~TextFormatter() { } void TextFormatter::Format(const Semantic* semantic) { Formatter formatter(&ostream_); formatter.Format(semantic); } } // namespace sm } // namespace compiler } // namespace elang <|endoftext|>
<commit_before>#include "himan_unit.h" #include "numerical_functions.h" #include "numerical_functions_helper.h" #include "timer.h" #define BOOST_TEST_MODULE numerical_functions using namespace std; using namespace himan; const double kEpsilon = 1e-3; void Dump(const himan::matrix<double>& m) { for (size_t i=0; i < m.SizeX();++i){ for (size_t j=0; j < m.SizeY();++j){ std::cout << m.At(i,j,0) << " "; } std::cout << std::endl; } } BOOST_AUTO_TEST_CASE(FILTER2D) { // Filter a plane with given filter kernel // Declare matrices himan::matrix<double> A(11,8,1,kFloatMissing); himan::matrix<double> B(3,3,1,kFloatMissing); himan::matrix<double> C; himan::matrix<double> D(11,8,1,kFloatMissing); FilterTestSetup(A, B, D); // Compute smoothened matrix C = himan::numerical_functions::Filter2D(A,B); // Compare results for(size_t i=0; i < C.Size(); ++i) { BOOST_CHECK_CLOSE(C.At(i),D.At(i),kEpsilon); } // computed filtered matrix std::cout << "Matrix C computed with Filter2D:" << std::endl; Dump(C); std::cout << std::endl << "Matrix D as reference case for Filter2D computation:" << std::endl; Dump(D); } BOOST_AUTO_TEST_CASE(FILTER2D_LARGE) { // Filter a plane with given filter kernel // Declare matrices himan::matrix<double> A(2001,1000,1,kFloatMissing); himan::matrix<double> B(3,3,1,kFloatMissing); himan::matrix<double> D(2001,1000,1,kFloatMissing); FilterTestSetup(A, B, D); himan::timer timer; timer.Start(); // Compute smoothened matrix himan::matrix<double> C = himan::numerical_functions::Filter2D(A,B); timer.Stop(); // Compare results for(size_t i=0; i < C.Size(); ++i) { BOOST_CHECK_CLOSE(C.At(i),D.At(i),kEpsilon); } std::cout << "Filter2D took " << timer.GetTime() << " ms " << std::endl; } BOOST_AUTO_TEST_CASE(MAX2D) { himan::matrix<double> A(5, 5, 1, kFloatMissing); A.Set({1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}); himan::matrix<double> B(3, 3, 1, kFloatMissing); B.Set({0, 1, 0, 1, 1, 1, 0, 1, 0}); auto result = numerical_functions::Max2D(A, B); std::cout << "source" << std::endl; Dump(A); std::cout << "kernel" << std::endl; Dump(B); std::cout << "result of Max2D()" << std::endl; Dump(result); BOOST_REQUIRE(result.At(0) == 6); BOOST_REQUIRE(result.At(19) == 9); B.Set({0, 0, 0, 0, 1, 0, 0, 0, 0}); // should return A result = numerical_functions::Max2D(A, B); for(size_t i=0; i < A.Size(); ++i) { BOOST_REQUIRE(A.At(i) == result.At(i)); } } <commit_msg>a couple of more tests<commit_after>#include "himan_unit.h" #include "numerical_functions.h" #include "numerical_functions_helper.h" #include "timer.h" #define BOOST_TEST_MODULE numerical_functions using namespace std; using namespace himan; const double kEpsilon = 1e-3; void Dump(const himan::matrix<double>& m) { for (size_t i=0; i < m.SizeX();++i){ for (size_t j=0; j < m.SizeY();++j){ std::cout << m.At(i,j,0) << " "; } std::cout << std::endl; } } BOOST_AUTO_TEST_CASE(FILTER2D) { // Filter a plane with given filter kernel // Declare matrices himan::matrix<double> A(11,8,1,kFloatMissing); himan::matrix<double> B(3,3,1,kFloatMissing); himan::matrix<double> C; himan::matrix<double> D(11,8,1,kFloatMissing); FilterTestSetup(A, B, D); // Compute smoothened matrix C = himan::numerical_functions::Filter2D(A,B); // Compare results for(size_t i=0; i < C.Size(); ++i) { BOOST_CHECK_CLOSE(C.At(i),D.At(i),kEpsilon); } // computed filtered matrix std::cout << "Matrix C computed with Filter2D:" << std::endl; Dump(C); std::cout << std::endl << "Matrix D as reference case for Filter2D computation:" << std::endl; Dump(D); } BOOST_AUTO_TEST_CASE(FILTER2D_LARGE) { // Filter a plane with given filter kernel // Declare matrices himan::matrix<double> A(2001,1000,1,kFloatMissing); himan::matrix<double> B(3,3,1,kFloatMissing); himan::matrix<double> D(2001,1000,1,kFloatMissing); FilterTestSetup(A, B, D); himan::timer timer; timer.Start(); // Compute smoothened matrix himan::matrix<double> C = himan::numerical_functions::Filter2D(A,B); timer.Stop(); // Compare results for(size_t i=0; i < C.Size(); ++i) { BOOST_CHECK_CLOSE(C.At(i),D.At(i),kEpsilon); } std::cout << "Filter2D took " << timer.GetTime() << " ms " << std::endl; } BOOST_AUTO_TEST_CASE(MAX2D) { himan::matrix<double> A(5, 5, 1, kFloatMissing); A.Set({1, 2, 3, 4, 5, 6, 7, 8, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}); himan::matrix<double> B(3, 3, 1, kFloatMissing); B.Set({0, 1, 0, 1, 1, 1, 0, 1, 0}); auto result = numerical_functions::Max2D(A, B); std::cout << "source" << std::endl; Dump(A); std::cout << "kernel" << std::endl; Dump(B); std::cout << "result of Max2D()" << std::endl; Dump(result); BOOST_REQUIRE(result.At(0) == 6); BOOST_REQUIRE(result.At(19) == 9); B.Set({0, 0, 0, 0, 1, 0, 0, 0, 0}); // should return A result = numerical_functions::Max2D(A, B); for(size_t i=0; i < A.Size(); ++i) { BOOST_REQUIRE(A.At(i) == result.At(i)); } A.Set({-1, -2, -3, -4, -5, -6, -7, -8, -9, -0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -0, -1, -2, -3, -4, -5}); B.Set(std::vector<double>(9, 1)); result = numerical_functions::Max2D(A, B); std::cout << "source" << std::endl; Dump(A); std::cout << "kernel" << std::endl; Dump(B); std::cout << "result of Max2D()" << std::endl; Dump(result); BOOST_REQUIRE(result.At(0) == -1); BOOST_REQUIRE(result.At(19) == 0); } <|endoftext|>
<commit_before>// // Copyright (C) 2010-2011 SIPez LLC. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> #define LOG_NDEBUG 0 //#define LOG_TAG defined in <mp/MpAndroidX_XAudioRecord.h> //#define ENABLE_FRAME_TIME_LOGGING //#define ENABLE_FILE_LOGGING // SIPX INCLUDES #if defined(ANDROID_2_3) || defined(ANDROID_2_3_4) // Must include specific version of pthreads here before Android audio stuff for Android 2.3 so // so that this can be compiled for Android 2.3 using NDK r3 # include <development/ndk/platforms/android-9/include/pthread.h> #endif #include <mp/MpAndroidX_XAudioRecord.h> // SYSTEM INCLUDES #include <utils/Log.h> //#include <media/AudioSystem.h> using namespace android; // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ MpAndroidAudioRecord* createAndroidAudioRecord() { return(new MP_ANDROID_AUDIO_RECORD()); } /* ============================ CREATORS ================================== */ // Default constructor MP_ANDROID_AUDIO_RECORD::MP_ANDROID_AUDIO_RECORD() : mpAudioRecord(NULL) { LOGV("%s constructor\n", QUOTED_MP_ANDROID_AUDIO_RECORD); mpAudioRecord = new AudioRecord(); } MP_ANDROID_AUDIO_RECORD::~MP_ANDROID_AUDIO_RECORD() { LOGV("%s destructor\n", QUOTED_MP_ANDROID_AUDIO_RECORD); if(mpAudioRecord) { delete mpAudioRecord; mpAudioRecord = NULL; } } /* ============================ MANIPULATORS ============================== */ int /*status_t*/ MP_ANDROID_AUDIO_RECORD::start() { mpAudioRecord->start(); } void MP_ANDROID_AUDIO_RECORD::stop() { mpAudioRecord->stop(); } int /*status_t*/ MP_ANDROID_AUDIO_RECORD::set(int inputSource, int sampleRate, sipXcallback_t audioCallback, void* user, int notificationFrames) { return(mpAudioRecord->set(inputSource, sampleRate, AudioSystem::PCM_16_BIT, // format AudioSystem::CHANNEL_IN_MONO, // channels 0, // frameCount AudioRecord::RECORD_AGC_ENABLE | AudioRecord::RECORD_NS_ENABLE, // flags audioCallback, // cbf user, notificationFrames, false)); // threadCanCallJava } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ <commit_msg>Android AudioRecord enumeration name changes in 4.X<commit_after>// // Copyright (C) 2010-2011 SIPez LLC. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> #define LOG_NDEBUG 0 //#define LOG_TAG defined in <mp/MpAndroidX_XAudioRecord.h> //#define ENABLE_FRAME_TIME_LOGGING //#define ENABLE_FILE_LOGGING // SIPX INCLUDES #if defined(ANDROID_2_3) || defined(ANDROID_2_3_4) || defined(ANDROID_4_0_1) // Must include specific version of pthreads here before Android audio stuff for Android 2.3 so // so that this can be compiled for Android 2.3 using NDK r3 # include <development/ndk/platforms/android-9/include/pthread.h> #endif #include <mp/MpAndroidX_XAudioRecord.h> // SYSTEM INCLUDES #include <utils/Log.h> //#include <media/AudioSystem.h> using namespace android; // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ MpAndroidAudioRecord* createAndroidAudioRecord() { return(new MP_ANDROID_AUDIO_RECORD()); } /* ============================ CREATORS ================================== */ // Default constructor MP_ANDROID_AUDIO_RECORD::MP_ANDROID_AUDIO_RECORD() : mpAudioRecord(NULL) { LOGV("%s constructor\n", QUOTED_MP_ANDROID_AUDIO_RECORD); mpAudioRecord = new AudioRecord(); } MP_ANDROID_AUDIO_RECORD::~MP_ANDROID_AUDIO_RECORD() { LOGV("%s destructor\n", QUOTED_MP_ANDROID_AUDIO_RECORD); if(mpAudioRecord) { delete mpAudioRecord; mpAudioRecord = NULL; } } /* ============================ MANIPULATORS ============================== */ int /*status_t*/ MP_ANDROID_AUDIO_RECORD::start() { mpAudioRecord->start(); } void MP_ANDROID_AUDIO_RECORD::stop() { mpAudioRecord->stop(); } int /*status_t*/ MP_ANDROID_AUDIO_RECORD::set(int inputSource, int sampleRate, sipXcallback_t audioCallback, void* user, int notificationFrames) { return(mpAudioRecord->set(inputSource, sampleRate, #ifdef ANDROID_4_0_1 AUDIO_FORMAT_PCM_16_BIT, // format AUDIO_CHANNEL_IN_MONO, // # channels #else AudioSystem::PCM_16_BIT, // format AudioSystem::CHANNEL_IN_MONO, // # channels #endif 0, // frameCount AudioRecord::RECORD_AGC_ENABLE | AudioRecord::RECORD_NS_ENABLE, // flags audioCallback, // cbf user, notificationFrames, false)); // threadCanCallJava } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ <|endoftext|>
<commit_before>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpAudioBuf.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsTask.h> #include <os/OsEvent.h> #define TEST_SAMPLES_PER_FRAME_SIZE 80 #define BUFFER_NUM 500 #define TEST_SAMPLES_PER_SECOND 8000 #define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*1) #define TEST_SAMPLE_DATA_MAGNITUDE 32000 #define TEST_SAMPLE_DATA_PERIOD (1000000/60) //in microseconds 60 Hz #define CREATE_TEST_RUNS_NUMBER 3 #define ENABLE_DISABLE_TEST_RUNS_NUMBER 5 #define ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER 10 #define DIRECT_WRITE_TEST_RUNS_NUMBER 3 #define TICKER_TEST_WRITE_RUNS_NUMBER 3 #undef USE_TEST_DRIVER #ifdef USE_TEST_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_SAMPLE_DATA_SIZE*1000/TEST_SAMPLES_PER_SECOND #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #include <mp/MpodWinMM.h> #define OUTPUT_DRIVER MpodWinMM #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS MpodWinMM::getDefaultDeviceName() #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOss.h> #define OUTPUT_DRIVER MpodOss #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_posix__ ] #error Unknown platform! #endif //static MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; //static UtlBoolean sampleDataInitialized=FALSE; static void calculateSampleData(int frequency, MpAudioSample sampleData[], int sampleDataSz, int samplesPerFrame, int samplesPerSecond) { for (int i=0; i<sampleDataSz; i++) { sampleData[i] = MpSineWaveGeneratorDeviceDriver::calculateSample(0, TEST_SAMPLE_DATA_MAGNITUDE, 1000000 / frequency, i, samplesPerFrame, samplesPerSecond); } } /** * Unittest for MpOutputDeviceDriver */ class MpOutputDeviceDriverTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpOutputDeviceDriverTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testEnableDisable); CPPUNIT_TEST(testEnableDisableFast); // This test is disabled, because it audio quality during it may be very bad. // Thus enable it only to test brand new drivers, which don't support notifications yet. // CPPUNIT_TEST(testDirectWrite); CPPUNIT_TEST(testTickerNotification); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), BUFFER_NUM); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCreate() { for (int i=0; i<CREATE_TEST_RUNS_NUMBER; i++) { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisable() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); OsTask::delay(50); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisableFast() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testDirectWrite() { MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; calculateSampleData(440, sampleData, TEST_SAMPLE_DATA_SIZE, 80, 8000); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<DIRECT_WRITE_TEST_RUNS_NUMBER; i++) { MpFrameTime frameTime=0; driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE/TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, frameTime)); frameTime += TEST_SAMPLES_PER_FRAME_SIZE*1000/TEST_SAMPLES_PER_SECOND; } driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testTickerNotification() { OsEvent notificationEvent; int sampleRates[]={8000, 16000, 32000, 48000}; int numRates = sizeof(sampleRates)/sizeof(int); int frequencies[] = {1000, 2000, 4000, 8000, 16000, 20000, 24000, 28000}; int numFreqs = sizeof(frequencies)/sizeof(int); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); int rateIndex; for(rateIndex = 0; rateIndex < numRates; rateIndex++) { int sampleDataSz = sampleRates[rateIndex]; MpAudioSample* sampleData = new MpAudioSample[sampleDataSz]; for (int i=0; i<numFreqs; i++) { printf("Frequency: %d (Hz) Sample rate: %d/sec.\n", frequencies[i], sampleRates[rateIndex]); calculateSampleData(frequencies[i], sampleData, sampleDataSz, sampleRates[rateIndex]/100, sampleRates[rateIndex]); MpFrameTime frameTime=0; driver.enableDevice(sampleRates[rateIndex]/100, sampleRates[rateIndex], 0); CPPUNIT_ASSERT(driver.isEnabled()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.setTickerNotification(&notificationEvent)); // Write some data to device. for (int frame=0; frame<100; frame++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, notificationEvent.wait(OsTime(1000))); notificationEvent.reset(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(sampleRates[rateIndex]/100, sampleData + sampleRates[rateIndex]/100*frame, frameTime)); frameTime += sampleRates[rateIndex]/100*1000/sampleRates[rateIndex]; } CPPUNIT_ASSERT(driver.setTickerNotification(NULL) == OS_SUCCESS); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } delete[] sampleData; } } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers }; CPPUNIT_TEST_SUITE_REGISTRATION(MpOutputDeviceDriverTest); <commit_msg>Checking in MpOutputDeviceDriverTest::measureJitter() test. This test is dedicated to measure soundcards' notification times jitter on different sample rates.<commit_after>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpAudioBuf.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsTask.h> #include <os/OsEvent.h> #include <os/OsDateTime.h> #include <utl/UtlString.h> #include <os/OsFS.h> #define TEST_SAMPLES_PER_FRAME_SIZE 80 #define BUFFER_NUM 500 #define TEST_SAMPLES_PER_SECOND 8000 #define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*1) #define TEST_SAMPLE_DATA_MAGNITUDE 32000 #define TEST_SAMPLE_DATA_PERIOD (1000000/60) //in microseconds 60 Hz #define CREATE_TEST_RUNS_NUMBER 3 #define ENABLE_DISABLE_TEST_RUNS_NUMBER 5 #define ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER 10 #define DIRECT_WRITE_TEST_RUNS_NUMBER 3 #define TICKER_TEST_WRITE_RUNS_NUMBER 3 #define MEASURE_JITTER_TEST_RUNS_NUMBER 1 #define MEASURE_JITTER_TEST_LENGTH_SEC 5 // Define this to enable writing of colected jitter data to files. //#define WRITE_JITTER_RESULTS_TO_FILE #undef USE_TEST_DRIVER #ifdef USE_TEST_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_SAMPLE_DATA_SIZE*1000/TEST_SAMPLES_PER_SECOND #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #include <mp/MpodWinMM.h> #define OUTPUT_DRIVER MpodWinMM #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS MpodWinMM::getDefaultDeviceName() #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOss.h> #define OUTPUT_DRIVER MpodOss #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_posix__ ] #error Unknown platform! #endif //static MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; //static UtlBoolean sampleDataInitialized=FALSE; static void calculateSampleData(int frequency, MpAudioSample sampleData[], int sampleDataSz, int samplesPerFrame, int samplesPerSecond) { for (int i=0; i<sampleDataSz; i++) { sampleData[i] = MpSineWaveGeneratorDeviceDriver::calculateSample(0, TEST_SAMPLE_DATA_MAGNITUDE, 1000000 / frequency, i, samplesPerFrame, samplesPerSecond); } } /** * Unittest for MpOutputDeviceDriver */ class MpOutputDeviceDriverTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpOutputDeviceDriverTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testEnableDisable); CPPUNIT_TEST(testEnableDisableFast); // This test is disabled, because it audio quality during it may be very bad. // Thus enable it only to test brand new drivers, which don't support notifications yet. // CPPUNIT_TEST(testDirectWrite); CPPUNIT_TEST(testTickerNotification); CPPUNIT_TEST(measureJitter); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), BUFFER_NUM); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCreate() { for (int i=0; i<CREATE_TEST_RUNS_NUMBER; i++) { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisable() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); OsTask::delay(50); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisableFast() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testDirectWrite() { MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; calculateSampleData(440, sampleData, TEST_SAMPLE_DATA_SIZE, 80, 8000); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<DIRECT_WRITE_TEST_RUNS_NUMBER; i++) { MpFrameTime frameTime=0; driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE/TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, frameTime)); frameTime += TEST_SAMPLES_PER_FRAME_SIZE*1000/TEST_SAMPLES_PER_SECOND; } driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testTickerNotification() { OsEvent notificationEvent; int sampleRates[]={8000, 16000, 32000, 48000}; int numRates = sizeof(sampleRates)/sizeof(int); int frequencies[] = {1000, 2000, 4000, 8000, 16000, 20000, 24000, 28000}; int numFreqs = sizeof(frequencies)/sizeof(int); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); int rateIndex; for(rateIndex = 0; rateIndex < numRates; rateIndex++) { int sampleDataSz = sampleRates[rateIndex]; MpAudioSample* sampleData = new MpAudioSample[sampleDataSz]; for (int i=0; i<numFreqs; i++) { printf("Frequency: %d (Hz) Sample rate: %d/sec.\n", frequencies[i], sampleRates[rateIndex]); calculateSampleData(frequencies[i], sampleData, sampleDataSz, sampleRates[rateIndex]/100, sampleRates[rateIndex]); MpFrameTime frameTime=0; driver.enableDevice(sampleRates[rateIndex]/100, sampleRates[rateIndex], 0); CPPUNIT_ASSERT(driver.isEnabled()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.setTickerNotification(&notificationEvent)); // Write some data to device. for (int frame=0; frame<100; frame++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, notificationEvent.wait(OsTime(1000))); notificationEvent.reset(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(sampleRates[rateIndex]/100, sampleData + sampleRates[rateIndex]/100*frame, frameTime)); frameTime += sampleRates[rateIndex]/100*1000/sampleRates[rateIndex]; } CPPUNIT_ASSERT(driver.setTickerNotification(NULL) == OS_SUCCESS); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } delete[] sampleData; } } void measureJitter() { OsEvent notificationEvent; int sampleRates[]={8000, 16000, 32000, 44100, 48000, 96000}; int numRates = sizeof(sampleRates)/sizeof(int); // The tone we will test with is an 'A' 440Hz sine tone. int testFrequency = 440; OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); int rateIndex; for(rateIndex = 0; rateIndex < numRates; rateIndex++) { int sampleDataSz = MEASURE_JITTER_TEST_LENGTH_SEC*sampleRates[rateIndex]; int samplesPerFrame = sampleRates[rateIndex]/100; // 10ms(=1/100sec) frames int numFrames = sampleDataSz/samplesPerFrame; MpAudioSample* sampleData = new MpAudioSample[sampleDataSz]; MpFrameTime frameTime=0; // Calculate the data for playing one tone calculateSampleData(testFrequency, sampleData, sampleDataSz, samplesPerFrame, sampleRates[rateIndex]); // Create buffers for capturing jitter data OsTime* jitterTimes[MEASURE_JITTER_TEST_RUNS_NUMBER]; for(int i = 0; i< MEASURE_JITTER_TEST_RUNS_NUMBER; i++) jitterTimes[i] = new OsTime[numFrames]; // Collect a number of runs of test data defined at the top of the test file. for (int curRunIdx=0; curRunIdx<MEASURE_JITTER_TEST_RUNS_NUMBER; curRunIdx++) { MpFrameTime frameTime=0; // Enable the device for each run so that we get an accurate setup/teardown // for enable/disable cycle captured in each test run. driver.enableDevice(samplesPerFrame, sampleRates[rateIndex], 0); CPPUNIT_ASSERT(driver.isEnabled()); // Register a callback to receive ticker notifications from the device driver. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.setTickerNotification(&notificationEvent)); // Write all the data we calculated to the device. for (int frame=0; frame<numFrames; frame++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, notificationEvent.wait(OsTime(1000))); OsDateTime::getCurTime(jitterTimes[curRunIdx][frame]); notificationEvent.reset(); // Push the frame to the device! CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(samplesPerFrame, sampleData + samplesPerFrame*frame, frameTime)); frameTime += samplesPerFrame*1000/sampleRates[rateIndex]; } // Disable the ticker notifications CPPUNIT_ASSERT(driver.setTickerNotification(NULL) == OS_SUCCESS); // Reset any notifications that may have been triggered. notificationEvent.reset(); // Disable the device to complete the run -- so that we get an accurate // setup/teardown for enable/disable cycle captured. driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); // Now we write out the jitter data we collected to a csv file // First we create a UtlString that contains the formatting of data to write // to file. UtlString jitterDataStr = ""; #define TMPBUFLEN 50 char tmpBuf[TMPBUFLEN]; int curTmpBufLen = 0; for(int run = 0; run<MEASURE_JITTER_TEST_RUNS_NUMBER; run++) { for(int frame=0; frame<numFrames; frame++) { curTmpBufLen = snprintf(tmpBuf, TMPBUFLEN, "%d", jitterTimes[curRunIdx][frame].cvtToMsecs()-jitterTimes[curRunIdx][0].cvtToMsecs()); jitterDataStr += tmpBuf; jitterDataStr += ","; } jitterDataStr += "\n"; } printf(jitterDataStr.data()); #ifdef WRITE_JITTER_RESULTS_TO_FILE // [ curTmpBufLen = snprintf(tmpBuf, TMPBUFLEN, "./audiodevice_out_jitter_%dHz.csv", sampleRates[rateIndex]); CPPUNIT_ASSERT_EQUAL(jitterDataStr.length(), (size_t)OsFile::openAndWrite(tmpBuf, jitterDataStr)); #endif // WRITE_JITTER_RESULTS_TO_FILE ] } // Clean up - delete each of the second arrays of the jitterTimes multidimensional array. for(int i = 0; i< MEASURE_JITTER_TEST_RUNS_NUMBER; i++) delete[] jitterTimes[i]; delete[] sampleData; } } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers }; CPPUNIT_TEST_SUITE_REGISTRATION(MpOutputDeviceDriverTest); <|endoftext|>
<commit_before>// // CompositeTileImageProvider.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/23/14. // // #include "CompositeTileImageProvider.hpp" #include "TileImageListener.hpp" #include "Tile.hpp" #include "CompositeTileImageContribution.hpp" #include "IFactory.hpp" #include "ICanvas.hpp" #include "IImage.hpp" #include "FrameTasksExecutor.hpp" CompositeTileImageProvider::~CompositeTileImageProvider() { for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; child->_release(); } #ifdef JAVA_CODE super.dispose(); #endif } const TileImageContribution* CompositeTileImageProvider::contribution(const Tile* tile) { std::vector<const CompositeTileImageContribution::ChildContribution*> childrenContributions; for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; const TileImageContribution* childContribution = child->contribution(tile); if (childContribution != NULL) { // ignore previous contributions, they are covered by the current fullCoverage & Opaque contribution. const int childrenContributionsSize = childrenContributions.size(); if ((childrenContributionsSize > 0) && childContribution->isFullCoverageAndOpaque()) { for (int j = 0; j < childrenContributionsSize; j++) { const CompositeTileImageContribution::ChildContribution* previousContribution = childrenContributions[j]; #ifdef C_CODE delete previousContribution; #endif #ifdef JAVA_CODE previousContribution.dispose(); #endif } childrenContributions.clear(); } childrenContributions.push_back( new CompositeTileImageContribution::ChildContribution(i, childContribution) ); } } return CompositeTileImageContribution::create(childrenContributions); } CompositeTileImageProvider::ChildResult::ChildResult(const bool isError, const bool isCanceled, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const std::string& error) : _isError(isError), _isCanceled(isCanceled), _image(image), _imageId(imageId), _contribution(contribution), _error(error) { // TileImageContribution::retainContribution(_contribution); } CompositeTileImageProvider::ChildResult::~ChildResult() { delete _image; #warning DEBUG MEMORY TileImageContribution::releaseContribution(_contribution); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::image(const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { return new CompositeTileImageProvider::ChildResult(false , // isError false, // isCanceled image, imageId, contribution, "" // error ); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::error(const std::string& error) { return new CompositeTileImageProvider::ChildResult(true, // isError false, // isCanceled NULL, // image "", // imageId NULL, // contribution error); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::cancelation() { return new CompositeTileImageProvider::ChildResult(false, // isError true, // isCanceled NULL, // image "", // imageId NULL, // contribution "" // error ); } CompositeTileImageProvider::Composer::Composer(int width, int height, CompositeTileImageProvider* compositeTileImageProvider, const std::string& tileId, const Sector& tileSector, TileImageListener* listener, bool deleteListener, const CompositeTileImageContribution* compositeContribution, FrameTasksExecutor* frameTasksExecutor) : _width(width), _height(height), _compositeTileImageProvider(compositeTileImageProvider), _tileId(tileId), _listener(listener), _deleteListener(deleteListener), _compositeContribution(compositeContribution), _contributionsSize( compositeContribution->size() ), _frameTasksExecutor(frameTasksExecutor), _stepsDone(0), _anyError(false), _anyCancelation(false), _canceled(false), _tileSector(tileSector) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(_compositeContribution); for (int i = 0; i < _contributionsSize; i++) { _results.push_back( NULL ); } } CompositeTileImageProvider::Composer::~Composer() { for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; delete result; } TileImageContribution::releaseContribution(_compositeContribution); #ifdef JAVA_CODE super.dispose(); #endif } void CompositeTileImageProvider::Composer::cleanUp() { if (_deleteListener) { delete _listener; _listener = NULL; } _compositeTileImageProvider->composerDone(this); } void CompositeTileImageProvider::Composer::done() { if (_canceled) { cleanUp(); return; } if (_contributionsSize == 1) { const ChildResult* singleResult = _results[0]; if (singleResult->_isError) { _listener->imageCreationError(_tileId, singleResult->_error); } else if (singleResult->_isCanceled) { _listener->imageCreationCanceled(_tileId); } else { _listener->imageCreated(singleResult->_imageId, singleResult->_image->shallowCopy(), singleResult->_imageId, singleResult->_contribution); } cleanUp(); } else { if (_anyError) { std::string composedError = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* childResult = _results[i]; if (childResult->_isError) { composedError += childResult->_error + " "; } } _listener->imageCreationError(_tileId, composedError); cleanUp(); } else if (_anyCancelation) { _listener->imageCreationCanceled(_tileId); cleanUp(); } else { // ICanvas* canvas = IFactory::instance()->createCanvas(); // // canvas->initialize(_width, _height); // // std::string imageId = ""; // // for (int i = 0; i < _contributionsSize; i++) { // const ChildResult* result = _results[i]; // // imageId += result->_imageId + "|"; //#warning JM: consider sector and transparency // canvas->drawImage(result->_image, 0, 0); // } // _imageId = imageId; // // canvas->createImage(new ComposerImageListener(this), true); // // delete canvas; _frameTasksExecutor->addPreRenderTask(new ComposerFrameTask(this)); } } } RectangleF* CompositeTileImageProvider::Composer::getInnerRectangle(int wholeSectorWidth, int wholeSectorHeight, const Sector& wholeSector, const Sector& innerSector) const { if (wholeSector.isEquals(innerSector)){ return new RectangleF(0, 0, wholeSectorWidth, wholeSectorHeight); } const double widthFactor = innerSector._deltaLongitude.div(wholeSector._deltaLongitude); const double heightFactor = innerSector._deltaLatitude.div(wholeSector._deltaLatitude); const Vector2D lowerUV = wholeSector.getUVCoordinates(innerSector.getNW()); return new RectangleF((float) (lowerUV._x * wholeSectorWidth), (float) (lowerUV._y * wholeSectorHeight), (float) (widthFactor * wholeSectorWidth), (float) (heightFactor * wholeSectorHeight)); } void CompositeTileImageProvider::Composer::mixResult() { if (_canceled) { cleanUp(); return; } ICanvas* canvas = IFactory::instance()->createCanvas(); canvas->initialize(_width, _height); std::string imageId = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; imageId += result->_imageId + "|"; #warning //For now, we consider the whole image will appear on the tile (no source rect needed) const IImage* image = result->_image; const float alpha = result->_contribution->_alpha; if (result->_contribution->isFullCoverageAndOpaque()) { canvas->drawImage(image, 0, 0); } else { if (result->_contribution->isFullCoverage()) { canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT 0, 0, _width, _height, alpha); } else { const Sector* imageSector = result->_contribution->getSector(); const RectangleF* destRect = getInnerRectangle(_width, _height, _tileSector, *imageSector); //TEST MADRID // if (_tileSector.contains(Angle::fromDegrees(40.41677540051771), Angle::fromDegrees(-3.7037901976145804))){ // printf("TS: %s\nIS: %s\nR: %s\n",_tileSector.description().c_str(), // imageSector->description().c_str(), // rect->description().c_str()); // } canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT destRect->_x, destRect->_y, destRect->_width, destRect->_height, alpha); delete destRect; } } } _imageId = imageId; canvas->createImage(new ComposerImageListener(this), true); delete canvas; } bool CompositeTileImageProvider::ComposerFrameTask::isCanceled(const G3MRenderContext* rc) { return false; } void CompositeTileImageProvider::ComposerFrameTask::execute(const G3MRenderContext* rc) { _composer->mixResult(); } void CompositeTileImageProvider::Composer::imageCreated(const IImage* image) { const CompositeTileImageContribution* compositeContribution = _compositeContribution; _compositeContribution = NULL; // the _compositeContribution ownership moved to the listener _listener->imageCreated(_tileId, image, _imageId, compositeContribution); cleanUp(); } void CompositeTileImageProvider::Composer::stepDone() { _stepsDone++; if (_stepsDone == _contributionsSize) { done(); } } void CompositeTileImageProvider::Composer::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const int index) { #warning DEBUG MEMORY TileImageContribution::retainContribution(contribution); _results[index] = ChildResult::image(image, imageId, contribution); stepDone(); } void CompositeTileImageProvider::Composer::imageCreationError(const std::string& error, const int index) { _results[index] = ChildResult::error(error); _anyError = true; stepDone(); } void CompositeTileImageProvider::Composer::imageCreationCanceled(const int index) { _results[index] = ChildResult::cancelation(); _anyCancelation = true; stepDone(); } void CompositeTileImageProvider::Composer::cancel(const std::string& tileId) { _canceled = true; _compositeTileImageProvider->cancelChildren(tileId, _compositeContribution); } void CompositeTileImageProvider::ChildTileImageListener::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { _composer->imageCreated(tileId, image, imageId, contribution, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationError(const std::string& tileId, const std::string& error) { _composer->imageCreationError(error, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationCanceled(const std::string& tileId) { _composer->imageCreationCanceled(_index); } void CompositeTileImageProvider::create(const Tile* tile, const TileImageContribution* contribution, const Vector2I& resolution, long long tileDownloadPriority, bool logDownloadActivity, TileImageListener* listener, bool deleteListener, FrameTasksExecutor* frameTasksExecutor) { const CompositeTileImageContribution* compositeContribution = (const CompositeTileImageContribution*) contribution; const std::string tileId = tile->_id; Composer* composer = new Composer(resolution._x, resolution._y, this, tileId, tile->_sector, listener, deleteListener, compositeContribution, frameTasksExecutor); _composers[ tileId ] = composer; const int contributionsSize = compositeContribution->size(); for (int i = 0; i < contributionsSize; i++) { const CompositeTileImageContribution::ChildContribution* childContribution = compositeContribution->get(i); TileImageProvider* child = _children[ childContribution->_childIndex ]; #warning DEBUG MEMORY childContribution->_contribution->_retain(); child->create(tile, childContribution->_contribution, resolution, tileDownloadPriority, logDownloadActivity, new ChildTileImageListener(composer, i), true, frameTasksExecutor); } } void CompositeTileImageProvider::cancel(const std::string& tileId) { #ifdef C_CODE if (_composers.find(tileId) != _composers.end()) { Composer* composer = _composers[tileId]; composer->cancel(tileId); _composers.erase(tileId); } #endif #ifdef JAVA_CODE final Composer composer = _composers.remove(tileId); if (composer != null) { composer.cancel(tileId); } #endif } void CompositeTileImageProvider::composerDone(Composer* composer) { _composers.erase( composer->_tileId ); composer->_release(); } void CompositeTileImageProvider::cancelChildren(const std::string& tileId, const CompositeTileImageContribution* compositeContribution) { const int contributionsSize = compositeContribution->size(); // store all the indexes before calling child->cancel(). // child->cancel() can force the deletion of the builder (and in order the deletion of compositeContribution) int* indexes = new int[contributionsSize]; for (int i = 0; i < contributionsSize; i++) { indexes[i] = compositeContribution->get(i)->_childIndex; } for (int i = 0; i < contributionsSize; i++) { TileImageProvider* child = _children[ indexes[i] ]; child->cancel(tileId); } delete [] indexes; } <commit_msg>Tile's image creation refactoring - NOT YET USABLE<commit_after>// // CompositeTileImageProvider.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/23/14. // // #include "CompositeTileImageProvider.hpp" #include "TileImageListener.hpp" #include "Tile.hpp" #include "CompositeTileImageContribution.hpp" #include "IFactory.hpp" #include "ICanvas.hpp" #include "IImage.hpp" #include "FrameTasksExecutor.hpp" CompositeTileImageProvider::~CompositeTileImageProvider() { for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; child->_release(); } #ifdef JAVA_CODE super.dispose(); #endif } const TileImageContribution* CompositeTileImageProvider::contribution(const Tile* tile) { std::vector<const CompositeTileImageContribution::ChildContribution*> childrenContributions; for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; const TileImageContribution* childContribution = child->contribution(tile); if (childContribution != NULL) { // ignore previous contributions, they are covered by the current fullCoverage & Opaque contribution. const int childrenContributionsSize = childrenContributions.size(); if ((childrenContributionsSize > 0) && childContribution->isFullCoverageAndOpaque()) { for (int j = 0; j < childrenContributionsSize; j++) { const CompositeTileImageContribution::ChildContribution* previousContribution = childrenContributions[j]; #ifdef C_CODE delete previousContribution; #endif #ifdef JAVA_CODE previousContribution.dispose(); #endif } childrenContributions.clear(); } childrenContributions.push_back( new CompositeTileImageContribution::ChildContribution(i, childContribution) ); } } return CompositeTileImageContribution::create(childrenContributions); } CompositeTileImageProvider::ChildResult::ChildResult(const bool isError, const bool isCanceled, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const std::string& error) : _isError(isError), _isCanceled(isCanceled), _image(image), _imageId(imageId), _contribution(contribution), _error(error) { // TileImageContribution::retainContribution(_contribution); } CompositeTileImageProvider::ChildResult::~ChildResult() { delete _image; #warning DEBUG MEMORY TileImageContribution::releaseContribution(_contribution); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::image(const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { return new CompositeTileImageProvider::ChildResult(false , // isError false, // isCanceled image, imageId, contribution, "" // error ); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::error(const std::string& error) { return new CompositeTileImageProvider::ChildResult(true, // isError false, // isCanceled NULL, // image "", // imageId NULL, // contribution error); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::cancelation() { return new CompositeTileImageProvider::ChildResult(false, // isError true, // isCanceled NULL, // image "", // imageId NULL, // contribution "" // error ); } CompositeTileImageProvider::Composer::Composer(int width, int height, CompositeTileImageProvider* compositeTileImageProvider, const std::string& tileId, const Sector& tileSector, TileImageListener* listener, bool deleteListener, const CompositeTileImageContribution* compositeContribution, FrameTasksExecutor* frameTasksExecutor) : _width(width), _height(height), _compositeTileImageProvider(compositeTileImageProvider), _tileId(tileId), _listener(listener), _deleteListener(deleteListener), _compositeContribution(compositeContribution), _contributionsSize( compositeContribution->size() ), _frameTasksExecutor(frameTasksExecutor), _stepsDone(0), _anyError(false), _anyCancelation(false), _canceled(false), _tileSector(tileSector) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(_compositeContribution); for (int i = 0; i < _contributionsSize; i++) { _results.push_back( NULL ); } } CompositeTileImageProvider::Composer::~Composer() { for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; delete result; } TileImageContribution::releaseContribution(_compositeContribution); #ifdef JAVA_CODE super.dispose(); #endif } void CompositeTileImageProvider::Composer::cleanUp() { if (_deleteListener) { delete _listener; _listener = NULL; } _compositeTileImageProvider->composerDone(this); } void CompositeTileImageProvider::Composer::done() { if (_canceled) { cleanUp(); return; } if (_contributionsSize == 1) { const ChildResult* singleResult = _results[0]; if (singleResult->_isError) { _listener->imageCreationError(_tileId, singleResult->_error); } else if (singleResult->_isCanceled) { _listener->imageCreationCanceled(_tileId); } else { #warning MEMORY singleResult->_contribution->_retain(); _listener->imageCreated(singleResult->_imageId, singleResult->_image->shallowCopy(), singleResult->_imageId, singleResult->_contribution); } cleanUp(); } else { if (_anyError) { std::string composedError = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* childResult = _results[i]; if (childResult->_isError) { composedError += childResult->_error + " "; } } _listener->imageCreationError(_tileId, composedError); cleanUp(); } else if (_anyCancelation) { _listener->imageCreationCanceled(_tileId); cleanUp(); } else { // ICanvas* canvas = IFactory::instance()->createCanvas(); // // canvas->initialize(_width, _height); // // std::string imageId = ""; // // for (int i = 0; i < _contributionsSize; i++) { // const ChildResult* result = _results[i]; // // imageId += result->_imageId + "|"; //#warning JM: consider sector and transparency // canvas->drawImage(result->_image, 0, 0); // } // _imageId = imageId; // // canvas->createImage(new ComposerImageListener(this), true); // // delete canvas; _frameTasksExecutor->addPreRenderTask(new ComposerFrameTask(this)); } } } RectangleF* CompositeTileImageProvider::Composer::getInnerRectangle(int wholeSectorWidth, int wholeSectorHeight, const Sector& wholeSector, const Sector& innerSector) const { if (wholeSector.isEquals(innerSector)){ return new RectangleF(0, 0, wholeSectorWidth, wholeSectorHeight); } const double widthFactor = innerSector._deltaLongitude.div(wholeSector._deltaLongitude); const double heightFactor = innerSector._deltaLatitude.div(wholeSector._deltaLatitude); const Vector2D lowerUV = wholeSector.getUVCoordinates(innerSector.getNW()); return new RectangleF((float) (lowerUV._x * wholeSectorWidth), (float) (lowerUV._y * wholeSectorHeight), (float) (widthFactor * wholeSectorWidth), (float) (heightFactor * wholeSectorHeight)); } void CompositeTileImageProvider::Composer::mixResult() { if (_canceled) { cleanUp(); return; } ICanvas* canvas = IFactory::instance()->createCanvas(); canvas->initialize(_width, _height); std::string imageId = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; imageId += result->_imageId + "|"; #warning //For now, we consider the whole image will appear on the tile (no source rect needed) const IImage* image = result->_image; const float alpha = result->_contribution->_alpha; if (result->_contribution->isFullCoverageAndOpaque()) { canvas->drawImage(image, 0, 0); } else { if (result->_contribution->isFullCoverage()) { canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT 0, 0, _width, _height, alpha); } else { const Sector* imageSector = result->_contribution->getSector(); const RectangleF* destRect = getInnerRectangle(_width, _height, _tileSector, *imageSector); //TEST MADRID // if (_tileSector.contains(Angle::fromDegrees(40.41677540051771), Angle::fromDegrees(-3.7037901976145804))){ // printf("TS: %s\nIS: %s\nR: %s\n",_tileSector.description().c_str(), // imageSector->description().c_str(), // rect->description().c_str()); // } canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT destRect->_x, destRect->_y, destRect->_width, destRect->_height, alpha); delete destRect; } } #warning MEMORY // result->_contribution->_release(); } _imageId = imageId; canvas->createImage(new ComposerImageListener(this), true); delete canvas; } bool CompositeTileImageProvider::ComposerFrameTask::isCanceled(const G3MRenderContext* rc) { return false; } void CompositeTileImageProvider::ComposerFrameTask::execute(const G3MRenderContext* rc) { _composer->mixResult(); } void CompositeTileImageProvider::Composer::imageCreated(const IImage* image) { const CompositeTileImageContribution* compositeContribution = _compositeContribution; _compositeContribution = NULL; // the _compositeContribution ownership moved to the listener _listener->imageCreated(_tileId, image, _imageId, compositeContribution); cleanUp(); } void CompositeTileImageProvider::Composer::stepDone() { _stepsDone++; if (_stepsDone == _contributionsSize) { done(); } } void CompositeTileImageProvider::Composer::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const int index) { #warning DEBUG MEMORY - DIEGO AT WORK -> moves to ChildResult::image() TileImageContribution::retainContribution(contribution); _results[index] = ChildResult::image(image, imageId, contribution); stepDone(); } void CompositeTileImageProvider::Composer::imageCreationError(const std::string& error, const int index) { _results[index] = ChildResult::error(error); _anyError = true; stepDone(); } void CompositeTileImageProvider::Composer::imageCreationCanceled(const int index) { _results[index] = ChildResult::cancelation(); _anyCancelation = true; stepDone(); } void CompositeTileImageProvider::Composer::cancel(const std::string& tileId) { _canceled = true; _compositeTileImageProvider->cancelChildren(tileId, _compositeContribution); } void CompositeTileImageProvider::ChildTileImageListener::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { _composer->imageCreated(tileId, image, imageId, contribution, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationError(const std::string& tileId, const std::string& error) { _composer->imageCreationError(error, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationCanceled(const std::string& tileId) { _composer->imageCreationCanceled(_index); } void CompositeTileImageProvider::create(const Tile* tile, const TileImageContribution* contribution, const Vector2I& resolution, long long tileDownloadPriority, bool logDownloadActivity, TileImageListener* listener, bool deleteListener, FrameTasksExecutor* frameTasksExecutor) { const CompositeTileImageContribution* compositeContribution = (const CompositeTileImageContribution*) contribution; const std::string tileId = tile->_id; Composer* composer = new Composer(resolution._x, resolution._y, this, tileId, tile->_sector, listener, deleteListener, compositeContribution, frameTasksExecutor); _composers[ tileId ] = composer; const int contributionsSize = compositeContribution->size(); for (int i = 0; i < contributionsSize; i++) { const CompositeTileImageContribution::ChildContribution* childContribution = compositeContribution->get(i); TileImageProvider* child = _children[ childContribution->_childIndex ]; #warning DEBUG MEMORY // childContribution->_contribution->_retain(); child->create(tile, childContribution->_contribution, resolution, tileDownloadPriority, logDownloadActivity, new ChildTileImageListener(composer, i), true, frameTasksExecutor); } } void CompositeTileImageProvider::cancel(const std::string& tileId) { #ifdef C_CODE if (_composers.find(tileId) != _composers.end()) { Composer* composer = _composers[tileId]; composer->cancel(tileId); _composers.erase(tileId); } #endif #ifdef JAVA_CODE final Composer composer = _composers.remove(tileId); if (composer != null) { composer.cancel(tileId); } #endif } void CompositeTileImageProvider::composerDone(Composer* composer) { _composers.erase( composer->_tileId ); composer->_release(); } void CompositeTileImageProvider::cancelChildren(const std::string& tileId, const CompositeTileImageContribution* compositeContribution) { const int contributionsSize = compositeContribution->size(); // store all the indexes before calling child->cancel(). // child->cancel() can force the deletion of the builder (and in order the deletion of compositeContribution) int* indexes = new int[contributionsSize]; for (int i = 0; i < contributionsSize; i++) { indexes[i] = compositeContribution->get(i)->_childIndex; } for (int i = 0; i < contributionsSize; i++) { TileImageProvider* child = _children[ indexes[i] ]; child->cancel(tileId); } delete [] indexes; } <|endoftext|>
<commit_before>/* * Copyright (c) 2020 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "ModelCommand.h" #include <app/InteractionModelEngine.h> #include <inttypes.h> using namespace ::chip; namespace { constexpr uint16_t kWaitDurationInSeconds = 10; } // namespace CHIP_ERROR ModelCommand::Run(PersistentStorage & storage, NodeId localId, NodeId remoteId) { CHIP_ERROR err = CHIP_NO_ERROR; mOpCredsIssuer.Initialize(); chip::Controller::CommissionerInitParams initParams; initParams.storageDelegate = &storage; initParams.operationalCredentialsDelegate = &mOpCredsIssuer; err = mCommissioner.SetUdpListenPort(storage.GetListenPort()); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", ErrorStr(err))); err = mCommissioner.Init(localId, initParams); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", ErrorStr(err))); err = mCommissioner.ServiceEvents(); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Run Loop: %s", ErrorStr(err))); err = mCommissioner.GetDevice(remoteId, &mDevice); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(chipTool, "Init failure! No pairing for device: %" PRIu64, localId)); err = SendCommand(mDevice, mEndPointId); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(chipTool, "Failed to send message: %s", ErrorStr(err))); UpdateWaitForResponse(true); WaitForResponse(kWaitDurationInSeconds); VerifyOrExit(GetCommandExitStatus(), err = CHIP_ERROR_INTERNAL); exit: mCommissioner.ServiceEventSignal(); mCommissioner.Shutdown(); return err; } <commit_msg>[chip-tool] Fix UpdateWaitForResponse call in ModelCommand (#6665)<commit_after>/* * Copyright (c) 2020 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "ModelCommand.h" #include <app/InteractionModelEngine.h> #include <inttypes.h> using namespace ::chip; namespace { constexpr uint16_t kWaitDurationInSeconds = 10; } // namespace CHIP_ERROR ModelCommand::Run(PersistentStorage & storage, NodeId localId, NodeId remoteId) { CHIP_ERROR err = CHIP_NO_ERROR; mOpCredsIssuer.Initialize(); chip::Controller::CommissionerInitParams initParams; initParams.storageDelegate = &storage; initParams.operationalCredentialsDelegate = &mOpCredsIssuer; err = mCommissioner.SetUdpListenPort(storage.GetListenPort()); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", ErrorStr(err))); err = mCommissioner.Init(localId, initParams); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", ErrorStr(err))); err = mCommissioner.ServiceEvents(); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Run Loop: %s", ErrorStr(err))); err = mCommissioner.GetDevice(remoteId, &mDevice); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(chipTool, "Init failure! No pairing for device: %" PRIu64, localId)); UpdateWaitForResponse(true); err = SendCommand(mDevice, mEndPointId); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(chipTool, "Failed to send message: %s", ErrorStr(err))); WaitForResponse(kWaitDurationInSeconds); VerifyOrExit(GetCommandExitStatus(), err = CHIP_ERROR_INTERNAL); exit: mCommissioner.ServiceEventSignal(); mCommissioner.Shutdown(); return err; } <|endoftext|>
<commit_before>/* * Copyright 2014-2015 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include <thread> #include <kaa/Kaa.hpp> #include <kaa/IKaaClient.hpp> #include <kaa/profile/DefaultProfileContainer.hpp> #include <kaa/configuration/storage/IConfigurationPersistenceManager.hpp> #include <kaa/configuration/manager/IConfigurationReceiver.hpp> #include <kaa/configuration/storage/FileConfigurationStorage.hpp> #include <kaa/logging/Log.hpp> #include <stdio.h> using namespace kaa; using std::cout; using std::endl; class UserConfigurationReceiver : public IConfigurationReceiver { public: void displayConfiguration(const KaaRootConfiguration &configuration) { if (!configuration.AddressList.is_null()) { cout<<"Configuration body:\n"; auto links = configuration.AddressList.get_array(); for(auto& e : links) { cout<<e.label<<" - "<<e.url<<endl; } } } virtual void onConfigurationUpdated(const KaaRootConfiguration &configuration) { cout<<"Configuration was updated\n"; displayConfiguration(configuration); } }; int main() { Kaa::init(); cout<<"Configuration demo started"<<endl; IKaaClient& kaaClient = Kaa::getKaaClient(); // Set up default profile container kaaClient.setProfileContainer(std::make_shared<DefaultProfileContainer>()); kaaClient.updateProfile(); // Set up a configuration subunit IConfigurationStoragePtr storage(std::make_shared<FileConfigurationStorage>("saved_config.cfg")); kaaClient.setConfigurationStorage(storage); UserConfigurationReceiver receiver; kaaClient.addConfigurationListener(receiver); Kaa::start(); for (int i = 0; i < 100; ++i) std::this_thread::sleep_for(std::chrono::seconds(1)); Kaa::stop(); cout<<"Configuration demo stopped"<<endl; return 0; } <commit_msg>KAA-449:<commit_after>/* * Copyright 2014-2015 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include <thread> #include <kaa/Kaa.hpp> #include <kaa/IKaaClient.hpp> #include <kaa/profile/DefaultProfileContainer.hpp> #include <kaa/configuration/storage/IConfigurationPersistenceManager.hpp> #include <kaa/configuration/manager/IConfigurationReceiver.hpp> #include <kaa/configuration/storage/FileConfigurationStorage.hpp> #include <kaa/logging/Log.hpp> #include <stdio.h> using namespace kaa; using std::cout; using std::endl; class UserConfigurationReceiver : public IConfigurationReceiver { public: void displayConfiguration(const KaaRootConfiguration &configuration) { if (!configuration.AddressList.is_null()) { cout<<"Configuration body:\n"; auto links = configuration.AddressList.get_array(); for(auto& e : links) { cout<<e.label<<" - "<<e.url<<endl; } } } virtual void onConfigurationUpdated(const KaaRootConfiguration &configuration) { cout<<"Configuration was updated\n"; displayConfiguration(configuration); } }; int main() { Kaa::init(); cout<<"Configuration demo started"<<endl; IKaaClient& kaaClient = Kaa::getKaaClient(); // Set up default profile container kaaClient.setProfileContainer(std::make_shared<DefaultProfileContainer>()); kaaClient.updateProfile(); // Set up a configuration subunit IConfigurationStoragePtr storage(std::make_shared<FileConfigurationStorage>("saved_config.cfg")); kaaClient.setConfigurationStorage(storage); UserConfigurationReceiver receiver; kaaClient.addConfigurationListener(receiver); Kaa::start(); for (int i = 0; i < 100; ++i) std::this_thread::sleep_for(std::chrono::seconds(1)); Kaa::stop(); cout<<"Configuration demo stopped"<<endl; return 0; } <|endoftext|>
<commit_before>/* Copyright Sven Bergström 2014 created for snow https://github.com/underscorediscovery/snow MIT license */ #ifdef HX_WINDOWS #include <windows.h> #include "SDL.h" #include "SDL_syswm.h" namespace snow { namespace platform { namespace window { void load_icon(SDL_Window* _window) { SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version) if (SDL_GetWindowWMInfo(_window,&wminfo)) { HINSTANCE handle = ::GetModuleHandle(NULL); HWND hwnd = wminfo.info.win.window; HICON icon = ::LoadIcon(handle, "IDI_MAIN_ICON"); ::SetClassLong(hwnd, GCL_HICON, (LONG) icon); } } //load_icon } //window } //platform namespace } //snow namespace #endif //HX_WINDOWS <commit_msg>Fix msvc windows 64 build; Add windows 64 bit prebuilt lib<commit_after>/* Copyright Sven Bergström 2014 created for snow https://github.com/underscorediscovery/snow MIT license */ #ifdef HX_WINDOWS #include <windows.h> #include "SDL.h" #include "SDL_syswm.h" namespace snow { namespace platform { namespace window { void load_icon(SDL_Window* _window) { SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version) if (SDL_GetWindowWMInfo(_window,&wminfo)) { HINSTANCE handle = ::GetModuleHandle(NULL); HWND hwnd = wminfo.info.win.window; HICON icon = ::LoadIcon(handle, "IDI_MAIN_ICON"); ::SetClassLong(hwnd, GCLP_HICON, (LONG) icon); } } //load_icon } //window } //platform namespace } //snow namespace #endif //HX_WINDOWS <|endoftext|>
<commit_before>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __elxMetricBase_hxx #define __elxMetricBase_hxx #include "elxMetricBase.h" namespace elastix { /** * ********************* Constructor **************************** */ template< class TElastix > MetricBase< TElastix > ::MetricBase() { /** Initialize. */ this->m_ShowExactMetricValue = false; this->m_ExactMetricSampler = 0; this->m_CurrentExactMetricValue = 0.0; this->m_ExactMetricSampleGridSpacing.Fill( 1 ); this->m_ExactMetricEachXNumberOfIterations = 1; } // end Constructor /** * ******************* BeforeEachResolutionBase ****************** */ template< class TElastix > void MetricBase< TElastix > ::BeforeEachResolutionBase( void ) { /** Get the current resolution level. */ unsigned int level = this->m_Registration->GetAsITKBaseType()->GetCurrentLevel(); /** Check if the exact metric value, computed on all pixels, should be shown. */ /** Define the name of the ExactMetric column */ std::string exactMetricColumn = "Exact"; exactMetricColumn += this->GetComponentLabel(); /** Remove the ExactMetric-column, if it already existed. */ xl::xout[ "iteration" ].RemoveTargetCell( exactMetricColumn.c_str() ); /** Read the parameter file: Show the exact metric in every iteration? */ bool showExactMetricValue = false; this->GetConfiguration()->ReadParameter( showExactMetricValue, "ShowExactMetricValue", this->GetComponentLabel(), level, 0 ); this->m_ShowExactMetricValue = showExactMetricValue; if( showExactMetricValue ) { /** Create a new column in the iteration info table */ xl::xout[ "iteration" ].AddTargetCell( exactMetricColumn.c_str() ); xl::xout[ "iteration" ][ exactMetricColumn.c_str() ] << std::showpoint << std::fixed; } /** Read the sample grid spacing for computing the "exact" metric */ if( showExactMetricValue ) { typedef typename ExactMetricImageSamplerType::SampleGridSpacingValueType SampleGridSpacingValueType; this->m_ExactMetricSampleGridSpacing.Fill( 1 ); /** Read the desired grid spacing of the samples. */ unsigned int spacing_dim; for( unsigned int dim = 0; dim < FixedImageDimension; dim++ ) { spacing_dim = this->m_ExactMetricSampleGridSpacing[ dim ]; this->GetConfiguration()->ReadParameter( spacing_dim, "ExactMetricSampleGridSpacing", this->GetComponentLabel(), level * FixedImageDimension + dim, -1 ); this->m_ExactMetricSampleGridSpacing[ dim ] = static_cast< SampleGridSpacingValueType >( spacing_dim ); } /** Read the requested frequency of exact metric evaluation. */ unsigned int eachXNumberOfIterations = 1; this->GetConfiguration()->ReadParameter( eachXNumberOfIterations, "ExactMetricEveryXIterations", this->GetComponentLabel(), level, 0 ); this->m_ExactMetricEachXNumberOfIterations = eachXNumberOfIterations; } /** Cast this to AdvancedMetricType. */ AdvancedMetricType * thisAsAdvanced = dynamic_cast< AdvancedMetricType * >( this ); /** For advanced metrics several other things can be set. */ if( thisAsAdvanced != 0 ) { /** Should the metric check for enough samples? */ bool checkNumberOfSamples = true; this->GetConfiguration()->ReadParameter( checkNumberOfSamples, "CheckNumberOfSamples", this->GetComponentLabel(), level, 0 ); /** Get the required ratio. */ float ratio = 0.25; this->GetConfiguration()->ReadParameter( ratio, "RequiredRatioOfValidSamples", this->GetComponentLabel(), level, 0, false ); /** Set it. */ if( !checkNumberOfSamples ) { thisAsAdvanced->SetRequiredRatioOfValidSamples( 0.0 ); } else { thisAsAdvanced->SetRequiredRatioOfValidSamples( ratio ); } /** Set moving image derivative scales. */ std::size_t usescales = this->GetConfiguration() ->CountNumberOfParameterEntries( "MovingImageDerivativeScales" ); if( usescales == 0 ) { thisAsAdvanced->SetUseMovingImageDerivativeScales( false ); thisAsAdvanced->SetScaleGradientWithRespectToMovingImageOrientation( false ); } else { thisAsAdvanced->SetUseMovingImageDerivativeScales( true ); /** Read the scales from the parameter file. */ MovingImageDerivativeScalesType movingImageDerivativeScales; for( unsigned int i = 0; i < MovingImageDimension; ++i ) { this->GetConfiguration()->ReadParameter( movingImageDerivativeScales[ i ], "MovingImageDerivativeScales", this->GetComponentLabel(), i, -1, false ); } /** Set and report. */ thisAsAdvanced->SetMovingImageDerivativeScales( movingImageDerivativeScales ); elxout << "Multiplying moving image derivatives by: " << movingImageDerivativeScales << std::endl; /** Check if the scales are applied taking into account the moving image orientation. */ bool wrtMoving = false; this->GetConfiguration()->ReadParameter( wrtMoving, "ScaleGradientWithRespectToMovingImageOrientation", this->GetComponentLabel(), level, false ); thisAsAdvanced->SetScaleGradientWithRespectToMovingImageOrientation( wrtMoving ); } /** Should the metric use multi-threading? */ bool useMultiThreading = true; this->GetConfiguration()->ReadParameter( useMultiThreading, "UseMultiThreadingForMetrics", this->GetComponentLabel(), level, 0 ); thisAsAdvanced->SetUseMultiThread( useMultiThreading ); if( useMultiThreading ) { std::string tmp = this->m_Configuration->GetCommandLineArgument( "-threads" ); if( tmp != "" ) { const unsigned int nrOfThreads = atoi( tmp.c_str() ); thisAsAdvanced->SetNumberOfThreads( nrOfThreads ); } } } // end advanced metric } // end BeforeEachResolutionBase() /** * ******************* AfterEachIterationBase ****************** */ template< class TElastix > void MetricBase< TElastix > ::AfterEachIterationBase( void ) { /** Show the metric value computed on all voxels, if the user wanted it. */ /** Define the name of the ExactMetric column (ExactMetric<i>). */ std::string exactMetricColumn = "Exact"; exactMetricColumn += this->GetComponentLabel(); this->m_CurrentExactMetricValue = 0.0; if( this->m_ShowExactMetricValue && ( this->m_Elastix->GetIterationCounter() % this->m_ExactMetricEachXNumberOfIterations == 0 ) ) { this->m_CurrentExactMetricValue = this->GetExactValue( this->GetElastix()->GetElxOptimizerBase() ->GetAsITKBaseType()->GetCurrentPosition() ); xl::xout[ "iteration" ][ exactMetricColumn.c_str() ] << this->m_CurrentExactMetricValue; } } // end AfterEachIterationBase() /** * ********************* SelectNewSamples ************************ */ template< class TElastix > void MetricBase< TElastix > ::SelectNewSamples( void ) { if( this->GetAdvancedMetricImageSampler() ) { /** Force the metric to base its computation on a new subset of image samples. */ this->GetAdvancedMetricImageSampler()->SelectNewSamplesOnUpdate(); } else { /** Not every metric may have implemented this, so give a warning when this * method is called for a metric without sampler support. * To avoid the warning, this method may be overridden by a subclass. */ xl::xout[ "warning" ] << "WARNING: The NewSamplesEveryIteration option was set to \"true\", but " << this->GetComponentLabel() << " does not use a sampler." << std::endl; } } // end SelectNewSamples() /** * ********************* GetExactValue ************************ */ template< class TElastix > typename MetricBase< TElastix >::MeasureType MetricBase< TElastix > ::GetExactValue( const ParametersType & parameters ) { /** Get the current image sampler. */ typename ImageSamplerBaseType::Pointer currentSampler = this->GetAdvancedMetricImageSampler(); /** Useless implementation if no image sampler is used; we may as * well throw an error, but the ShowExactMetricValue is not really * essential for good registration... */ if( currentSampler.IsNull() ) { return itk::NumericTraits< MeasureType >::Zero; } /** Try to cast the current Sampler to a FullSampler. */ ExactMetricImageSamplerType * testPointer = dynamic_cast< ExactMetricImageSamplerType * >( currentSampler.GetPointer() ); if( testPointer != 0 ) { /** GetValue gives us the exact value! */ return this->GetAsITKBaseType()->GetValue( parameters ); } /** We have to provide the metric a full (or actually 'grid') sampler, * calls its GetValue and set back its original sampler. */ if( this->m_ExactMetricSampler.IsNull() ) { this->m_ExactMetricSampler = ExactMetricImageSamplerType::New(); } /** Copy settings from current sampler. */ this->m_ExactMetricSampler->SetInput( currentSampler->GetInput() ); this->m_ExactMetricSampler->SetMask( currentSampler->GetMask() ); this->m_ExactMetricSampler->SetInputImageRegion( currentSampler->GetInputImageRegion() ); this->m_ExactMetricSampler->SetSampleGridSpacing( this->m_ExactMetricSampleGridSpacing ); this->SetAdvancedMetricImageSampler( this->m_ExactMetricSampler ); /** Compute the metric value on the full images. */ MeasureType exactValue = this->GetAsITKBaseType()->GetValue( parameters ); /** Reset the original sampler. */ this->SetAdvancedMetricImageSampler( currentSampler ); return exactValue; } // end GetExactValue() /** * ******************* GetAdvancedMetricUseImageSampler ******************** */ template< class TElastix > bool MetricBase< TElastix > ::GetAdvancedMetricUseImageSampler( void ) const { /** Cast this to AdvancedMetricType. */ const AdvancedMetricType * thisAsMetricWithSampler = dynamic_cast< const AdvancedMetricType * >( this ); /** If no AdvancedMetricType, return false. */ if( thisAsMetricWithSampler == 0 ) { return false; } return thisAsMetricWithSampler->GetUseImageSampler(); } // end GetAdvancedMetricUseImageSampler() /** * ******************* SetAdvancedMetricImageSampler ******************** */ template< class TElastix > void MetricBase< TElastix > ::SetAdvancedMetricImageSampler( ImageSamplerBaseType * sampler ) { /** Cast this to AdvancedMetricType. */ AdvancedMetricType * thisAsMetricWithSampler = dynamic_cast< AdvancedMetricType * >( this ); /** If no AdvancedMetricType, or if the MetricWithSampler does not * utilize the sampler, return. */ if( thisAsMetricWithSampler == 0 ) { return; } if( thisAsMetricWithSampler->GetUseImageSampler() == false ) { return; } /** Set the sampler. */ thisAsMetricWithSampler->SetImageSampler( sampler ); } // end SetAdvancedMetricImageSampler() /** * ******************* GetAdvancedMetricImageSampler ******************** */ template< class TElastix > typename MetricBase< TElastix >::ImageSamplerBaseType * MetricBase< TElastix > ::GetAdvancedMetricImageSampler( void ) const { /** Cast this to AdvancedMetricType. */ const AdvancedMetricType * thisAsMetricWithSampler = dynamic_cast< const AdvancedMetricType * >( this ); /** If no AdvancedMetricType, or if the MetricWithSampler does not * utilize the sampler, return 0. */ if( thisAsMetricWithSampler == 0 ) { return 0; } if( thisAsMetricWithSampler->GetUseImageSampler() == false ) { return 0; } /** Return the sampler. */ return thisAsMetricWithSampler->GetImageSampler(); } // end GetAdvancedMetricImageSampler() } // end namespace elastix #endif // end #ifndef __elxMetricBase_hxx <commit_msg>ENH: Initialize movingImageDerivativeScales to prevent ValGrind warnings<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __elxMetricBase_hxx #define __elxMetricBase_hxx #include "elxMetricBase.h" namespace elastix { /** * ********************* Constructor **************************** */ template< class TElastix > MetricBase< TElastix > ::MetricBase() { /** Initialize. */ this->m_ShowExactMetricValue = false; this->m_ExactMetricSampler = 0; this->m_CurrentExactMetricValue = 0.0; this->m_ExactMetricSampleGridSpacing.Fill( 1 ); this->m_ExactMetricEachXNumberOfIterations = 1; } // end Constructor /** * ******************* BeforeEachResolutionBase ****************** */ template< class TElastix > void MetricBase< TElastix > ::BeforeEachResolutionBase( void ) { /** Get the current resolution level. */ unsigned int level = this->m_Registration->GetAsITKBaseType()->GetCurrentLevel(); /** Check if the exact metric value, computed on all pixels, should be shown. */ /** Define the name of the ExactMetric column */ std::string exactMetricColumn = "Exact"; exactMetricColumn += this->GetComponentLabel(); /** Remove the ExactMetric-column, if it already existed. */ xl::xout[ "iteration" ].RemoveTargetCell( exactMetricColumn.c_str() ); /** Read the parameter file: Show the exact metric in every iteration? */ bool showExactMetricValue = false; this->GetConfiguration()->ReadParameter( showExactMetricValue, "ShowExactMetricValue", this->GetComponentLabel(), level, 0 ); this->m_ShowExactMetricValue = showExactMetricValue; if( showExactMetricValue ) { /** Create a new column in the iteration info table */ xl::xout[ "iteration" ].AddTargetCell( exactMetricColumn.c_str() ); xl::xout[ "iteration" ][ exactMetricColumn.c_str() ] << std::showpoint << std::fixed; } /** Read the sample grid spacing for computing the "exact" metric */ if( showExactMetricValue ) { typedef typename ExactMetricImageSamplerType::SampleGridSpacingValueType SampleGridSpacingValueType; this->m_ExactMetricSampleGridSpacing.Fill( 1 ); /** Read the desired grid spacing of the samples. */ unsigned int spacing_dim; for( unsigned int dim = 0; dim < FixedImageDimension; dim++ ) { spacing_dim = this->m_ExactMetricSampleGridSpacing[ dim ]; this->GetConfiguration()->ReadParameter( spacing_dim, "ExactMetricSampleGridSpacing", this->GetComponentLabel(), level * FixedImageDimension + dim, -1 ); this->m_ExactMetricSampleGridSpacing[ dim ] = static_cast< SampleGridSpacingValueType >( spacing_dim ); } /** Read the requested frequency of exact metric evaluation. */ unsigned int eachXNumberOfIterations = 1; this->GetConfiguration()->ReadParameter( eachXNumberOfIterations, "ExactMetricEveryXIterations", this->GetComponentLabel(), level, 0 ); this->m_ExactMetricEachXNumberOfIterations = eachXNumberOfIterations; } /** Cast this to AdvancedMetricType. */ AdvancedMetricType * thisAsAdvanced = dynamic_cast< AdvancedMetricType * >( this ); /** For advanced metrics several other things can be set. */ if( thisAsAdvanced != 0 ) { /** Should the metric check for enough samples? */ bool checkNumberOfSamples = true; this->GetConfiguration()->ReadParameter( checkNumberOfSamples, "CheckNumberOfSamples", this->GetComponentLabel(), level, 0 ); /** Get the required ratio. */ float ratio = 0.25; this->GetConfiguration()->ReadParameter( ratio, "RequiredRatioOfValidSamples", this->GetComponentLabel(), level, 0, false ); /** Set it. */ if( !checkNumberOfSamples ) { thisAsAdvanced->SetRequiredRatioOfValidSamples( 0.0 ); } else { thisAsAdvanced->SetRequiredRatioOfValidSamples( ratio ); } /** Set moving image derivative scales. */ std::size_t usescales = this->GetConfiguration() ->CountNumberOfParameterEntries( "MovingImageDerivativeScales" ); if( usescales == 0 ) { thisAsAdvanced->SetUseMovingImageDerivativeScales( false ); thisAsAdvanced->SetScaleGradientWithRespectToMovingImageOrientation( false ); } else { thisAsAdvanced->SetUseMovingImageDerivativeScales( true ); /** Read the scales from the parameter file. */ MovingImageDerivativeScalesType movingImageDerivativeScales; movingImageDerivativeScales.Fill( 1.0 ); for( unsigned int i = 0; i < MovingImageDimension; ++i ) { this->GetConfiguration()->ReadParameter( movingImageDerivativeScales[ i ], "MovingImageDerivativeScales", this->GetComponentLabel(), i, -1, false ); } /** Set and report. */ thisAsAdvanced->SetMovingImageDerivativeScales( movingImageDerivativeScales ); elxout << "Multiplying moving image derivatives by: " << movingImageDerivativeScales << std::endl; /** Check if the scales are applied taking into account the moving image orientation. */ bool wrtMoving = false; this->GetConfiguration()->ReadParameter( wrtMoving, "ScaleGradientWithRespectToMovingImageOrientation", this->GetComponentLabel(), level, false ); thisAsAdvanced->SetScaleGradientWithRespectToMovingImageOrientation( wrtMoving ); } /** Should the metric use multi-threading? */ bool useMultiThreading = true; this->GetConfiguration()->ReadParameter( useMultiThreading, "UseMultiThreadingForMetrics", this->GetComponentLabel(), level, 0 ); thisAsAdvanced->SetUseMultiThread( useMultiThreading ); if( useMultiThreading ) { std::string tmp = this->m_Configuration->GetCommandLineArgument( "-threads" ); if( tmp != "" ) { const unsigned int nrOfThreads = atoi( tmp.c_str() ); thisAsAdvanced->SetNumberOfThreads( nrOfThreads ); } } } // end advanced metric } // end BeforeEachResolutionBase() /** * ******************* AfterEachIterationBase ****************** */ template< class TElastix > void MetricBase< TElastix > ::AfterEachIterationBase( void ) { /** Show the metric value computed on all voxels, if the user wanted it. */ /** Define the name of the ExactMetric column (ExactMetric<i>). */ std::string exactMetricColumn = "Exact"; exactMetricColumn += this->GetComponentLabel(); this->m_CurrentExactMetricValue = 0.0; if( this->m_ShowExactMetricValue && ( this->m_Elastix->GetIterationCounter() % this->m_ExactMetricEachXNumberOfIterations == 0 ) ) { this->m_CurrentExactMetricValue = this->GetExactValue( this->GetElastix()->GetElxOptimizerBase() ->GetAsITKBaseType()->GetCurrentPosition() ); xl::xout[ "iteration" ][ exactMetricColumn.c_str() ] << this->m_CurrentExactMetricValue; } } // end AfterEachIterationBase() /** * ********************* SelectNewSamples ************************ */ template< class TElastix > void MetricBase< TElastix > ::SelectNewSamples( void ) { if( this->GetAdvancedMetricImageSampler() ) { /** Force the metric to base its computation on a new subset of image samples. */ this->GetAdvancedMetricImageSampler()->SelectNewSamplesOnUpdate(); } else { /** Not every metric may have implemented this, so give a warning when this * method is called for a metric without sampler support. * To avoid the warning, this method may be overridden by a subclass. */ xl::xout[ "warning" ] << "WARNING: The NewSamplesEveryIteration option was set to \"true\", but " << this->GetComponentLabel() << " does not use a sampler." << std::endl; } } // end SelectNewSamples() /** * ********************* GetExactValue ************************ */ template< class TElastix > typename MetricBase< TElastix >::MeasureType MetricBase< TElastix > ::GetExactValue( const ParametersType & parameters ) { /** Get the current image sampler. */ typename ImageSamplerBaseType::Pointer currentSampler = this->GetAdvancedMetricImageSampler(); /** Useless implementation if no image sampler is used; we may as * well throw an error, but the ShowExactMetricValue is not really * essential for good registration... */ if( currentSampler.IsNull() ) { return itk::NumericTraits< MeasureType >::Zero; } /** Try to cast the current Sampler to a FullSampler. */ ExactMetricImageSamplerType * testPointer = dynamic_cast< ExactMetricImageSamplerType * >( currentSampler.GetPointer() ); if( testPointer != 0 ) { /** GetValue gives us the exact value! */ return this->GetAsITKBaseType()->GetValue( parameters ); } /** We have to provide the metric a full (or actually 'grid') sampler, * calls its GetValue and set back its original sampler. */ if( this->m_ExactMetricSampler.IsNull() ) { this->m_ExactMetricSampler = ExactMetricImageSamplerType::New(); } /** Copy settings from current sampler. */ this->m_ExactMetricSampler->SetInput( currentSampler->GetInput() ); this->m_ExactMetricSampler->SetMask( currentSampler->GetMask() ); this->m_ExactMetricSampler->SetInputImageRegion( currentSampler->GetInputImageRegion() ); this->m_ExactMetricSampler->SetSampleGridSpacing( this->m_ExactMetricSampleGridSpacing ); this->SetAdvancedMetricImageSampler( this->m_ExactMetricSampler ); /** Compute the metric value on the full images. */ MeasureType exactValue = this->GetAsITKBaseType()->GetValue( parameters ); /** Reset the original sampler. */ this->SetAdvancedMetricImageSampler( currentSampler ); return exactValue; } // end GetExactValue() /** * ******************* GetAdvancedMetricUseImageSampler ******************** */ template< class TElastix > bool MetricBase< TElastix > ::GetAdvancedMetricUseImageSampler( void ) const { /** Cast this to AdvancedMetricType. */ const AdvancedMetricType * thisAsMetricWithSampler = dynamic_cast< const AdvancedMetricType * >( this ); /** If no AdvancedMetricType, return false. */ if( thisAsMetricWithSampler == 0 ) { return false; } return thisAsMetricWithSampler->GetUseImageSampler(); } // end GetAdvancedMetricUseImageSampler() /** * ******************* SetAdvancedMetricImageSampler ******************** */ template< class TElastix > void MetricBase< TElastix > ::SetAdvancedMetricImageSampler( ImageSamplerBaseType * sampler ) { /** Cast this to AdvancedMetricType. */ AdvancedMetricType * thisAsMetricWithSampler = dynamic_cast< AdvancedMetricType * >( this ); /** If no AdvancedMetricType, or if the MetricWithSampler does not * utilize the sampler, return. */ if( thisAsMetricWithSampler == 0 ) { return; } if( thisAsMetricWithSampler->GetUseImageSampler() == false ) { return; } /** Set the sampler. */ thisAsMetricWithSampler->SetImageSampler( sampler ); } // end SetAdvancedMetricImageSampler() /** * ******************* GetAdvancedMetricImageSampler ******************** */ template< class TElastix > typename MetricBase< TElastix >::ImageSamplerBaseType * MetricBase< TElastix > ::GetAdvancedMetricImageSampler( void ) const { /** Cast this to AdvancedMetricType. */ const AdvancedMetricType * thisAsMetricWithSampler = dynamic_cast< const AdvancedMetricType * >( this ); /** If no AdvancedMetricType, or if the MetricWithSampler does not * utilize the sampler, return 0. */ if( thisAsMetricWithSampler == 0 ) { return 0; } if( thisAsMetricWithSampler->GetUseImageSampler() == false ) { return 0; } /** Return the sampler. */ return thisAsMetricWithSampler->GetImageSampler(); } // end GetAdvancedMetricImageSampler() } // end namespace elastix #endif // end #ifndef __elxMetricBase_hxx <|endoftext|>
<commit_before>/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/declaration.h" #include "kernel/type_checker.h" #include "library/aux_recursors.h" #include "library/user_recursors.h" #include "library/normalize.h" #include "library/util.h" #include "compiler/eta_expansion.h" #include "compiler/simp_pr1_rec.h" void pp_detail(lean::environment const & env, lean::expr const & e); void pp(lean::environment const & env, lean::expr const & e); namespace lean { static expr expand_aux_recursors(environment const & env, expr const & e) { auto tc = mk_type_checker(env, name_generator(), [=](name const & n) { return !is_aux_recursor(env, n) && !is_user_defined_recursor(env, n); }); constraint_seq cs; return normalize(*tc, e, cs); } static name * g_tmp_prefix = nullptr; class preprocess_rec_fn { environment m_env; buffer<name> & m_aux_decls; bool check(declaration const & d, expr const & v) { type_checker tc(m_env); expr t = tc.check(v, d.get_univ_params()).first; if (!tc.is_def_eq(d.get_type(), t).first) throw exception("preprocess_rec failed"); return true; } public: preprocess_rec_fn(environment const & env, buffer<name> & aux_decls): m_env(env), m_aux_decls(aux_decls) {} environment operator()(declaration const & d) { expr v = d.get_value(); v = expand_aux_recursors(m_env, v); v = eta_expand(m_env, v); v = simp_pr1_rec(m_env, v); ::pp(m_env, v); // TODO(Leo) check(d, v); return m_env; } }; environment preprocess_rec(environment const & env, declaration const & d, buffer<name> & aux_decls) { return preprocess_rec_fn(env, aux_decls)(d); } void initialize_preprocess_rec() { g_tmp_prefix = new name(name::mk_internal_unique_name()); } void finalize_preprocess_rec() { delete g_tmp_prefix; } } <commit_msg>fix(compiler/preprocess_rec): warning when compiling using clang on OSX<commit_after>/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/declaration.h" #include "kernel/type_checker.h" #include "library/aux_recursors.h" #include "library/user_recursors.h" #include "library/normalize.h" #include "library/util.h" #include "compiler/eta_expansion.h" #include "compiler/simp_pr1_rec.h" void pp_detail(lean::environment const & env, lean::expr const & e); void pp(lean::environment const & env, lean::expr const & e); namespace lean { static expr expand_aux_recursors(environment const & env, expr const & e) { auto tc = mk_type_checker(env, name_generator(), [=](name const & n) { return !is_aux_recursor(env, n) && !is_user_defined_recursor(env, n); }); constraint_seq cs; return normalize(*tc, e, cs); } static name * g_tmp_prefix = nullptr; class preprocess_rec_fn { environment m_env; // buffer<name> & m_aux_decls; // TODO(Leo): bool check(declaration const & d, expr const & v) { type_checker tc(m_env); expr t = tc.check(v, d.get_univ_params()).first; if (!tc.is_def_eq(d.get_type(), t).first) throw exception("preprocess_rec failed"); return true; } public: preprocess_rec_fn(environment const & env, buffer<name> & /* aux_decls */): m_env(env) {} // , m_aux_decls(aux_decls) {} environment operator()(declaration const & d) { expr v = d.get_value(); v = expand_aux_recursors(m_env, v); v = eta_expand(m_env, v); v = simp_pr1_rec(m_env, v); ::pp(m_env, v); // TODO(Leo) check(d, v); return m_env; } }; environment preprocess_rec(environment const & env, declaration const & d, buffer<name> & aux_decls) { return preprocess_rec_fn(env, aux_decls)(d); } void initialize_preprocess_rec() { g_tmp_prefix = new name(name::mk_internal_unique_name()); } void finalize_preprocess_rec() { delete g_tmp_prefix; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: framegrabber.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:44:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <tools/prewin.h> #include <windows.h> #include <objbase.h> #include <strmif.h> #include <Amvideo.h> #include <Qedit.h> #include <uuids.h> #include <tools/postwin.h> #include "framegrabber.hxx" #include "player.hxx" #include <tools/stream.hxx> #include <vcl/graph.hxx> #include <unotools/localfilehelper.hxx> #define AVMEDIA_WIN_FRAMEGRABBER_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.FrameGrabber_DirectX" #define AVMEDIA_WIN_FRAMEGRABBER_SERVICENAME "com.sun.star.media.FrameGrabber_DirectX" using namespace ::com::sun::star; namespace avmedia { namespace win { // ---------------- // - FrameGrabber - // ---------------- FrameGrabber::FrameGrabber( const uno::Reference< lang::XMultiServiceFactory >& rxMgr ) : mxMgr( rxMgr ) { ::CoInitialize( NULL ); } // ------------------------------------------------------------------------------ FrameGrabber::~FrameGrabber() { ::CoUninitialize(); } // ------------------------------------------------------------------------------ IMediaDet* FrameGrabber::implCreateMediaDet( const ::rtl::OUString& rURL ) const { IMediaDet* pDet = NULL; if( SUCCEEDED( CoCreateInstance( CLSID_MediaDet, NULL, CLSCTX_INPROC_SERVER, IID_IMediaDet, (void**) &pDet ) ) ) { String aLocalStr; if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( rURL, aLocalStr ) && aLocalStr.Len() ) { if( !SUCCEEDED( pDet->put_Filename( ::SysAllocString( aLocalStr.GetBuffer() ) ) ) ) { pDet->Release(); pDet = NULL; } } } return pDet; } // ------------------------------------------------------------------------------ bool FrameGrabber::create( const ::rtl::OUString& rURL ) { // just check if a MediaDet interface can be created with the given URL IMediaDet* pDet = implCreateMediaDet( rURL ); if( pDet ) { maURL = rURL; pDet->Release(); pDet = NULL; } else maURL = ::rtl::OUString(); return( maURL.getLength() > 0 ); } // ------------------------------------------------------------------------------ uno::Reference< graphic::XGraphic > SAL_CALL FrameGrabber::grabFrame( double fMediaTime ) throw (uno::RuntimeException) { uno::Reference< graphic::XGraphic > xRet; IMediaDet* pDet = implCreateMediaDet( maURL ); if( pDet ) { double fLength; long nStreamCount; bool bFound = false; if( SUCCEEDED( pDet->get_OutputStreams( &nStreamCount ) ) ) { for( long n = 0; ( n < nStreamCount ) && !bFound; ++n ) { GUID aMajorType; if( SUCCEEDED( pDet->put_CurrentStream( n ) ) && SUCCEEDED( pDet->get_StreamType( &aMajorType ) ) && ( aMajorType == MEDIATYPE_Video ) ) { bFound = true; } } } if( bFound && ( S_OK == pDet->get_StreamLength( &fLength ) ) && ( fLength > 0.0 ) && ( fMediaTime >= 0.0 ) && ( fMediaTime <= fLength ) ) { AM_MEDIA_TYPE aMediaType; long nWidth = 0, nHeight = 0, nSize = 0; if( SUCCEEDED( pDet->get_StreamMediaType( &aMediaType ) ) ) { if( ( aMediaType.formattype == FORMAT_VideoInfo ) && ( aMediaType.cbFormat >= sizeof( VIDEOINFOHEADER ) ) ) { VIDEOINFOHEADER* pVih = reinterpret_cast< VIDEOINFOHEADER* >( aMediaType.pbFormat ); nWidth = pVih->bmiHeader.biWidth; nHeight = pVih->bmiHeader.biHeight; if( nHeight < 0 ) nHeight *= -1; } if( aMediaType.cbFormat != 0 ) { ::CoTaskMemFree( (PVOID) aMediaType.pbFormat ); aMediaType.cbFormat = 0; aMediaType.pbFormat = NULL; } if( aMediaType.pUnk != NULL ) { aMediaType.pUnk->Release(); aMediaType.pUnk = NULL; } } if( ( nWidth > 0 ) && ( nHeight > 0 ) && SUCCEEDED( pDet->GetBitmapBits( 0, &nSize, NULL, nWidth, nHeight ) ) && ( nSize > 0 ) ) { char* pBuffer = new char[ nSize ]; try { if( SUCCEEDED( pDet->GetBitmapBits( fMediaTime, NULL, pBuffer, nWidth, nHeight ) ) ) { SvMemoryStream aMemStm( pBuffer, nSize, STREAM_READ | STREAM_WRITE ); Bitmap aBmp; if( aBmp.Read( aMemStm, false ) && !aBmp.IsEmpty() ) { const Graphic aGraphic( aBmp ); xRet = aGraphic.GetXGraphic(); } } } catch( ... ) { } delete [] pBuffer; } } pDet->Release(); } return xRet; } // ------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL FrameGrabber::getImplementationName( ) throw (uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( AVMEDIA_WIN_FRAMEGRABBER_IMPLEMENTATIONNAME ) ); } // ------------------------------------------------------------------------------ sal_Bool SAL_CALL FrameGrabber::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( AVMEDIA_WIN_FRAMEGRABBER_SERVICENAME ) ); } // ------------------------------------------------------------------------------ uno::Sequence< ::rtl::OUString > SAL_CALL FrameGrabber::getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence< ::rtl::OUString > aRet(1); aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( AVMEDIA_WIN_FRAMEGRABBER_SERVICENAME ) ); return aRet; } } // namespace win } // namespace avmedia <commit_msg>INTEGRATION: CWS sb59 (1.3.64); FILE MERGED 2006/08/16 16:02:26 sb 1.3.64.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: framegrabber.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-10-12 11:26:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <tools/prewin.h> #if defined _MSC_VER #pragma warning(push, 1) #pragma warning(disable: 4917) #endif #include <windows.h> #include <objbase.h> #include <strmif.h> #include <Amvideo.h> #include <Qedit.h> #include <uuids.h> #if defined _MSC_VER #pragma warning(pop) #endif #include <tools/postwin.h> #include "framegrabber.hxx" #include "player.hxx" #include <tools/stream.hxx> #include <vcl/graph.hxx> #include <unotools/localfilehelper.hxx> #define AVMEDIA_WIN_FRAMEGRABBER_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.FrameGrabber_DirectX" #define AVMEDIA_WIN_FRAMEGRABBER_SERVICENAME "com.sun.star.media.FrameGrabber_DirectX" using namespace ::com::sun::star; namespace avmedia { namespace win { // ---------------- // - FrameGrabber - // ---------------- FrameGrabber::FrameGrabber( const uno::Reference< lang::XMultiServiceFactory >& rxMgr ) : mxMgr( rxMgr ) { ::CoInitialize( NULL ); } // ------------------------------------------------------------------------------ FrameGrabber::~FrameGrabber() { ::CoUninitialize(); } // ------------------------------------------------------------------------------ IMediaDet* FrameGrabber::implCreateMediaDet( const ::rtl::OUString& rURL ) const { IMediaDet* pDet = NULL; if( SUCCEEDED( CoCreateInstance( CLSID_MediaDet, NULL, CLSCTX_INPROC_SERVER, IID_IMediaDet, (void**) &pDet ) ) ) { String aLocalStr; if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( rURL, aLocalStr ) && aLocalStr.Len() ) { if( !SUCCEEDED( pDet->put_Filename( ::SysAllocString( aLocalStr.GetBuffer() ) ) ) ) { pDet->Release(); pDet = NULL; } } } return pDet; } // ------------------------------------------------------------------------------ bool FrameGrabber::create( const ::rtl::OUString& rURL ) { // just check if a MediaDet interface can be created with the given URL IMediaDet* pDet = implCreateMediaDet( rURL ); if( pDet ) { maURL = rURL; pDet->Release(); pDet = NULL; } else maURL = ::rtl::OUString(); return( maURL.getLength() > 0 ); } // ------------------------------------------------------------------------------ uno::Reference< graphic::XGraphic > SAL_CALL FrameGrabber::grabFrame( double fMediaTime ) throw (uno::RuntimeException) { uno::Reference< graphic::XGraphic > xRet; IMediaDet* pDet = implCreateMediaDet( maURL ); if( pDet ) { double fLength; long nStreamCount; bool bFound = false; if( SUCCEEDED( pDet->get_OutputStreams( &nStreamCount ) ) ) { for( long n = 0; ( n < nStreamCount ) && !bFound; ++n ) { GUID aMajorType; if( SUCCEEDED( pDet->put_CurrentStream( n ) ) && SUCCEEDED( pDet->get_StreamType( &aMajorType ) ) && ( aMajorType == MEDIATYPE_Video ) ) { bFound = true; } } } if( bFound && ( S_OK == pDet->get_StreamLength( &fLength ) ) && ( fLength > 0.0 ) && ( fMediaTime >= 0.0 ) && ( fMediaTime <= fLength ) ) { AM_MEDIA_TYPE aMediaType; long nWidth = 0, nHeight = 0, nSize = 0; if( SUCCEEDED( pDet->get_StreamMediaType( &aMediaType ) ) ) { if( ( aMediaType.formattype == FORMAT_VideoInfo ) && ( aMediaType.cbFormat >= sizeof( VIDEOINFOHEADER ) ) ) { VIDEOINFOHEADER* pVih = reinterpret_cast< VIDEOINFOHEADER* >( aMediaType.pbFormat ); nWidth = pVih->bmiHeader.biWidth; nHeight = pVih->bmiHeader.biHeight; if( nHeight < 0 ) nHeight *= -1; } if( aMediaType.cbFormat != 0 ) { ::CoTaskMemFree( (PVOID) aMediaType.pbFormat ); aMediaType.cbFormat = 0; aMediaType.pbFormat = NULL; } if( aMediaType.pUnk != NULL ) { aMediaType.pUnk->Release(); aMediaType.pUnk = NULL; } } if( ( nWidth > 0 ) && ( nHeight > 0 ) && SUCCEEDED( pDet->GetBitmapBits( 0, &nSize, NULL, nWidth, nHeight ) ) && ( nSize > 0 ) ) { char* pBuffer = new char[ nSize ]; try { if( SUCCEEDED( pDet->GetBitmapBits( fMediaTime, NULL, pBuffer, nWidth, nHeight ) ) ) { SvMemoryStream aMemStm( pBuffer, nSize, STREAM_READ | STREAM_WRITE ); Bitmap aBmp; if( aBmp.Read( aMemStm, false ) && !aBmp.IsEmpty() ) { const Graphic aGraphic( aBmp ); xRet = aGraphic.GetXGraphic(); } } } catch( ... ) { } delete [] pBuffer; } } pDet->Release(); } return xRet; } // ------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL FrameGrabber::getImplementationName( ) throw (uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( AVMEDIA_WIN_FRAMEGRABBER_IMPLEMENTATIONNAME ) ); } // ------------------------------------------------------------------------------ sal_Bool SAL_CALL FrameGrabber::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( AVMEDIA_WIN_FRAMEGRABBER_SERVICENAME ) ); } // ------------------------------------------------------------------------------ uno::Sequence< ::rtl::OUString > SAL_CALL FrameGrabber::getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence< ::rtl::OUString > aRet(1); aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( AVMEDIA_WIN_FRAMEGRABBER_SERVICENAME ) ); return aRet; } } // namespace win } // namespace avmedia <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ /*TODO - change "singleton" behaviour by using new helper ::comhelper::SingletonRef - rename method exist() to existHandlerForURL() or similar one - may it's a good idea to replace struct ProtocolHandler by css::beans::NamedValue type?! */ #include <classes/protocolhandlercache.hxx> #include <classes/converter.hxx> #include <threadhelp/lockhelper.hxx> #include <tools/wldcrd.hxx> #include <unotools/configpaths.hxx> #include <rtl/ustrbuf.hxx> namespace framework{ /** @short overloaded index operator of hash map to support pattern key search @descr All keys inside this hash map are URL pattern which points to an uno implementation name of a protocol handler service which is registered for this pattern. This operator makes it easy to find such registered handler by using a full qualified URL and compare it with all pattern keys. @param sURL the full qualified URL which should match to a registered pattern @return An iterator which points to the found item inside the hash or PatternHash::end() if no pattern match this given <var>sURL</var>. */ PatternHash::iterator PatternHash::findPatternKey( const OUString& sURL ) { PatternHash::iterator pItem = this->begin(); while( pItem!=this->end() ) { WildCard aPattern(pItem->first); if (aPattern.Matches(sURL)) break; ++pItem; } return pItem; } /** @short initialize static member of class HandlerCache @descr We use a singleton pattern to implement this handler cache. That means it use two static member list to hold all necessary information and a ref count mechanism to create/destroy it on demand. */ HandlerHash* HandlerCache::m_pHandler = NULL; PatternHash* HandlerCache::m_pPattern = NULL; sal_Int32 HandlerCache::m_nRefCount = 0 ; HandlerCFGAccess* HandlerCache::m_pConfig = NULL; /** @short ctor of the cache of all registered protoco handler @descr It tries to open the right configuration package automaticly and fill the internal structures. After that the cache can be used for read access on this data and perform some search operations on it. */ HandlerCache::HandlerCache() { osl::MutexGuard g(LockHelper::getGlobalLock()); if (m_nRefCount==0) { m_pHandler = new HandlerHash(); m_pPattern = new PatternHash(); m_pConfig = new HandlerCFGAccess(PACKAGENAME_PROTOCOLHANDLER); m_pConfig->read(&m_pHandler,&m_pPattern); m_pConfig->setCache(this); } ++m_nRefCount; } /** @short dtor of the cache @descr It frees all used memory. In further implementations (may if we support write access too) it's a good place to flush changes back to the configuration - but not needed yet. */ HandlerCache::~HandlerCache() { osl::MutexGuard g(LockHelper::getGlobalLock()); if( m_nRefCount==1) { m_pConfig->setCache(NULL); m_pHandler->free(); m_pPattern->free(); delete m_pConfig; delete m_pHandler; delete m_pPattern; m_pConfig = NULL; m_pHandler= NULL; m_pPattern= NULL; } --m_nRefCount; } /** @short dtor of the cache @descr It frees all used memory. In further implementations (may if we support write access too) it's a good place to flush changes back to the configuration - but not needed yet. */ sal_Bool HandlerCache::search( const OUString& sURL, ProtocolHandler* pReturn ) const { sal_Bool bFound = sal_False; /* SAFE */{ osl::MutexGuard g(LockHelper::getGlobalLock()); PatternHash::const_iterator pItem = m_pPattern->findPatternKey(sURL); if (pItem!=m_pPattern->end()) { *pReturn = (*m_pHandler)[pItem->second]; bFound = sal_True; } /* SAFE */} return bFound; } /** @short search for a registered handler by using an URL struct @descr We combine necessary parts of this struct to a valid URL string and call our other search method ... It's a helper for outside code. */ sal_Bool HandlerCache::search( const css::util::URL& aURL, ProtocolHandler* pReturn ) const { return search( aURL.Complete, pReturn ); } void HandlerCache::takeOver(HandlerHash* pHandler, PatternHash* pPattern) { osl::MutexGuard g(LockHelper::getGlobalLock()); HandlerHash* pOldHandler = m_pHandler; PatternHash* pOldPattern = m_pPattern; m_pHandler = pHandler; m_pPattern = pPattern; pOldHandler->free(); pOldPattern->free(); delete pOldHandler; delete pOldPattern; } /** @short dtor of the config access class @descr It opens the configuration package automaticly by using base class mechanism. After that "read()" method of this class should be called to use it. @param sPackage specifies the package name of the configuration data which should be used */ HandlerCFGAccess::HandlerCFGAccess( const OUString& sPackage ) : ConfigItem( sPackage ) { css::uno::Sequence< OUString > lListenPaths(1); lListenPaths[0] = SETNAME_HANDLER; EnableNotification(lListenPaths); } /** @short use base class mechanism to fill given structures @descr User use us as a wrapper between configuration api and his internal structures. He give us some pointer to his member and we fill it. @param pHandler pointer to a list of protocol handler infos @param pPattern reverse map of handler pattern to her uno names */ void HandlerCFGAccess::read( HandlerHash** ppHandler , PatternHash** ppPattern ) { // list of all uno implementation names without encoding css::uno::Sequence< OUString > lNames = GetNodeNames( SETNAME_HANDLER, ::utl::CONFIG_NAME_LOCAL_PATH ); sal_Int32 nSourceCount = lNames.getLength(); sal_Int32 nTargetCount = nSourceCount; // list of all full qualified path names of configuration entries css::uno::Sequence< OUString > lFullNames ( nTargetCount ); // expand names to full path names sal_Int32 nSource=0; sal_Int32 nTarget=0; for( nSource=0; nSource<nSourceCount; ++nSource ) { OUStringBuffer sPath( SETNAME_HANDLER ); sPath.append(CFG_PATH_SEPARATOR); sPath.append(lNames[nSource]); sPath.append(CFG_PATH_SEPARATOR); sPath.append(PROPERTY_PROTOCOLS); lFullNames[nTarget] = sPath.makeStringAndClear(); ++nTarget; } // get values at all css::uno::Sequence< css::uno::Any > lValues = GetProperties( lFullNames ); SAL_WARN_IF( lFullNames.getLength()!=lValues.getLength(), "fwk", "HandlerCFGAccess::read(): Miss some configuration values of handler set!" ); // fill structures nSource = 0; for( nTarget=0; nTarget<nTargetCount; ++nTarget ) { // create it new for every loop to guarantee a real empty object! ProtocolHandler aHandler; aHandler.m_sUNOName = ::utl::extractFirstFromConfigurationPath(lNames[nSource]); // unpack all values of this handler css::uno::Sequence< OUString > lTemp; lValues[nTarget] >>= lTemp; aHandler.m_lProtocols = Converter::convert_seqOUString2OUStringList(lTemp); // register his pattern into the performance search hash for (OUStringList::iterator pItem =aHandler.m_lProtocols.begin(); pItem!=aHandler.m_lProtocols.end() ; ++pItem ) { (**ppPattern)[*pItem] = lNames[nSource]; } // insert the handler info into the normal handler cache (**ppHandler)[lNames[nSource]] = aHandler; ++nSource; } } void HandlerCFGAccess::Notify(const css::uno::Sequence< OUString >& /*lPropertyNames*/) { HandlerHash* pHandler = new HandlerHash; PatternHash* pPattern = new PatternHash; read(&pHandler, &pPattern); if (m_pCache) m_pCache->takeOver(pHandler, pPattern); else { delete pHandler; delete pPattern; } } void HandlerCFGAccess::Commit() { } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#738659 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ /*TODO - change "singleton" behaviour by using new helper ::comhelper::SingletonRef - rename method exist() to existHandlerForURL() or similar one - may it's a good idea to replace struct ProtocolHandler by css::beans::NamedValue type?! */ #include <classes/protocolhandlercache.hxx> #include <classes/converter.hxx> #include <threadhelp/lockhelper.hxx> #include <tools/wldcrd.hxx> #include <unotools/configpaths.hxx> #include <rtl/ustrbuf.hxx> namespace framework{ /** @short overloaded index operator of hash map to support pattern key search @descr All keys inside this hash map are URL pattern which points to an uno implementation name of a protocol handler service which is registered for this pattern. This operator makes it easy to find such registered handler by using a full qualified URL and compare it with all pattern keys. @param sURL the full qualified URL which should match to a registered pattern @return An iterator which points to the found item inside the hash or PatternHash::end() if no pattern match this given <var>sURL</var>. */ PatternHash::iterator PatternHash::findPatternKey( const OUString& sURL ) { PatternHash::iterator pItem = this->begin(); while( pItem!=this->end() ) { WildCard aPattern(pItem->first); if (aPattern.Matches(sURL)) break; ++pItem; } return pItem; } /** @short initialize static member of class HandlerCache @descr We use a singleton pattern to implement this handler cache. That means it use two static member list to hold all necessary information and a ref count mechanism to create/destroy it on demand. */ HandlerHash* HandlerCache::m_pHandler = NULL; PatternHash* HandlerCache::m_pPattern = NULL; sal_Int32 HandlerCache::m_nRefCount = 0 ; HandlerCFGAccess* HandlerCache::m_pConfig = NULL; /** @short ctor of the cache of all registered protoco handler @descr It tries to open the right configuration package automaticly and fill the internal structures. After that the cache can be used for read access on this data and perform some search operations on it. */ HandlerCache::HandlerCache() { osl::MutexGuard g(LockHelper::getGlobalLock()); if (m_nRefCount==0) { m_pHandler = new HandlerHash(); m_pPattern = new PatternHash(); m_pConfig = new HandlerCFGAccess(PACKAGENAME_PROTOCOLHANDLER); m_pConfig->read(&m_pHandler,&m_pPattern); m_pConfig->setCache(this); } ++m_nRefCount; } /** @short dtor of the cache @descr It frees all used memory. In further implementations (may if we support write access too) it's a good place to flush changes back to the configuration - but not needed yet. */ HandlerCache::~HandlerCache() { osl::MutexGuard g(LockHelper::getGlobalLock()); if( m_nRefCount==1) { m_pConfig->setCache(NULL); m_pHandler->free(); m_pPattern->free(); delete m_pConfig; delete m_pHandler; delete m_pPattern; m_pConfig = NULL; m_pHandler= NULL; m_pPattern= NULL; } --m_nRefCount; } /** @short dtor of the cache @descr It frees all used memory. In further implementations (may if we support write access too) it's a good place to flush changes back to the configuration - but not needed yet. */ sal_Bool HandlerCache::search( const OUString& sURL, ProtocolHandler* pReturn ) const { sal_Bool bFound = sal_False; /* SAFE */{ osl::MutexGuard g(LockHelper::getGlobalLock()); PatternHash::const_iterator pItem = m_pPattern->findPatternKey(sURL); if (pItem!=m_pPattern->end()) { *pReturn = (*m_pHandler)[pItem->second]; bFound = sal_True; } /* SAFE */} return bFound; } /** @short search for a registered handler by using an URL struct @descr We combine necessary parts of this struct to a valid URL string and call our other search method ... It's a helper for outside code. */ sal_Bool HandlerCache::search( const css::util::URL& aURL, ProtocolHandler* pReturn ) const { return search( aURL.Complete, pReturn ); } void HandlerCache::takeOver(HandlerHash* pHandler, PatternHash* pPattern) { osl::MutexGuard g(LockHelper::getGlobalLock()); HandlerHash* pOldHandler = m_pHandler; PatternHash* pOldPattern = m_pPattern; m_pHandler = pHandler; m_pPattern = pPattern; pOldHandler->free(); pOldPattern->free(); delete pOldHandler; delete pOldPattern; } /** @short dtor of the config access class @descr It opens the configuration package automaticly by using base class mechanism. After that "read()" method of this class should be called to use it. @param sPackage specifies the package name of the configuration data which should be used */ HandlerCFGAccess::HandlerCFGAccess( const OUString& sPackage ) : ConfigItem(sPackage) , m_pCache(0) { css::uno::Sequence< OUString > lListenPaths(1); lListenPaths[0] = SETNAME_HANDLER; EnableNotification(lListenPaths); } /** @short use base class mechanism to fill given structures @descr User use us as a wrapper between configuration api and his internal structures. He give us some pointer to his member and we fill it. @param pHandler pointer to a list of protocol handler infos @param pPattern reverse map of handler pattern to her uno names */ void HandlerCFGAccess::read( HandlerHash** ppHandler , PatternHash** ppPattern ) { // list of all uno implementation names without encoding css::uno::Sequence< OUString > lNames = GetNodeNames( SETNAME_HANDLER, ::utl::CONFIG_NAME_LOCAL_PATH ); sal_Int32 nSourceCount = lNames.getLength(); sal_Int32 nTargetCount = nSourceCount; // list of all full qualified path names of configuration entries css::uno::Sequence< OUString > lFullNames ( nTargetCount ); // expand names to full path names sal_Int32 nSource=0; sal_Int32 nTarget=0; for( nSource=0; nSource<nSourceCount; ++nSource ) { OUStringBuffer sPath( SETNAME_HANDLER ); sPath.append(CFG_PATH_SEPARATOR); sPath.append(lNames[nSource]); sPath.append(CFG_PATH_SEPARATOR); sPath.append(PROPERTY_PROTOCOLS); lFullNames[nTarget] = sPath.makeStringAndClear(); ++nTarget; } // get values at all css::uno::Sequence< css::uno::Any > lValues = GetProperties( lFullNames ); SAL_WARN_IF( lFullNames.getLength()!=lValues.getLength(), "fwk", "HandlerCFGAccess::read(): Miss some configuration values of handler set!" ); // fill structures nSource = 0; for( nTarget=0; nTarget<nTargetCount; ++nTarget ) { // create it new for every loop to guarantee a real empty object! ProtocolHandler aHandler; aHandler.m_sUNOName = ::utl::extractFirstFromConfigurationPath(lNames[nSource]); // unpack all values of this handler css::uno::Sequence< OUString > lTemp; lValues[nTarget] >>= lTemp; aHandler.m_lProtocols = Converter::convert_seqOUString2OUStringList(lTemp); // register his pattern into the performance search hash for (OUStringList::iterator pItem =aHandler.m_lProtocols.begin(); pItem!=aHandler.m_lProtocols.end() ; ++pItem ) { (**ppPattern)[*pItem] = lNames[nSource]; } // insert the handler info into the normal handler cache (**ppHandler)[lNames[nSource]] = aHandler; ++nSource; } } void HandlerCFGAccess::Notify(const css::uno::Sequence< OUString >& /*lPropertyNames*/) { HandlerHash* pHandler = new HandlerHash; PatternHash* pPattern = new PatternHash; read(&pHandler, &pPattern); if (m_pCache) m_pCache->takeOver(pHandler, pPattern); else { delete pHandler; delete pPattern; } } void HandlerCFGAccess::Commit() { } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/compositor/compositor.h" #include <GL/gl.h> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkMatrix.h" #include "third_party/skia/include/core/SkScalar.h" #include "ui/gfx/rect.h" #include "ui/gfx/transform.h" #include "ui/gfx/gl/gl_bindings.h" #include "ui/gfx/gl/gl_context.h" #include "ui/gfx/gl/gl_implementation.h" #include "ui/gfx/gl/gl_surface.h" #include "ui/gfx/gl/gl_surface_glx.h" namespace ui { namespace glHidden { class CompositorGL; class TextureGL : public Texture { public: TextureGL(CompositorGL* compositor); virtual ~TextureGL(); virtual void SetBitmap(const SkBitmap& bitmap, const gfx::Point& origin, const gfx::Size& overall_size) OVERRIDE; // Draws the texture. virtual void Draw(const ui::Transform& transform) OVERRIDE; private: unsigned int texture_id_; gfx::Size size_; CompositorGL* compositor_; DISALLOW_COPY_AND_ASSIGN(TextureGL); }; class CompositorGL : public Compositor { public: explicit CompositorGL(gfx::AcceleratedWidget widget); virtual ~CompositorGL(); void MakeCurrent(); gfx::Size GetSize(); GLuint program(); GLuint a_pos_loc(); GLuint a_tex_loc(); GLuint u_tex_loc(); GLuint u_mat_loc(); private: // Overridden from Compositor. virtual Texture* CreateTexture() OVERRIDE; virtual void NotifyStart() OVERRIDE; virtual void NotifyEnd() OVERRIDE; virtual void Blur(const gfx::Rect& bounds) OVERRIDE; // Specific to CompositorGL. bool InitShaders(); // The GL context used for compositing. scoped_refptr<gfx::GLSurface> gl_surface_; scoped_refptr<gfx::GLContext> gl_context_; gfx::Size size_; // Shader program, attributes and uniforms. // TODO(wjmaclean): Make these static so they ca be shared in a single // context. GLuint program_; GLuint a_pos_loc_; GLuint a_tex_loc_; GLuint u_tex_loc_; GLuint u_mat_loc_; // Keep track of whether compositing has started or not. bool started_; DISALLOW_COPY_AND_ASSIGN(CompositorGL); }; TextureGL::TextureGL(CompositorGL* compositor) : texture_id_(0), compositor_(compositor) { } TextureGL::~TextureGL() { if (texture_id_) { compositor_->MakeCurrent(); glDeleteTextures(1, &texture_id_); } } void TextureGL::SetBitmap(const SkBitmap& bitmap, const gfx::Point& origin, const gfx::Size& overall_size) { // Verify bitmap pixels are contiguous. DCHECK_EQ(bitmap.rowBytes(), SkBitmap::ComputeRowBytes(bitmap.config(), bitmap.width())); SkAutoLockPixels lock (bitmap); void* pixels = bitmap.getPixels(); if (!texture_id_) { // Texture needs to be created. We assume the first call is for // a full-sized canvas. size_ = overall_size; glGenTextures(1, &texture_id_); glBindTexture(GL_TEXTURE_2D, texture_id_); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size_.width(), size_.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else if (size_ != overall_size) { // Size has changed. size_ = overall_size; glBindTexture(GL_TEXTURE_2D, texture_id_); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size_.width(), size_.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); } else { // Uploading partial texture. glBindTexture(GL_TEXTURE_2D, texture_id_); glTexSubImage2D(GL_TEXTURE_2D, 0, origin.x(), origin.y(), bitmap.width(), bitmap.height(), GL_RGBA, GL_UNSIGNED_BYTE, pixels); } } void TextureGL::Draw(const ui::Transform& transform) { gfx::Size window_size = compositor_->GetSize(); ui::Transform t; t.ConcatTranslate(1,1); t.ConcatScale(size_.width()/2.0f, size_.height()/2.0f); t.ConcatTranslate(0, -size_.height()); t.ConcatScale(1, -1); t.ConcatTransform(transform); // Add view transform. t.ConcatTranslate(0, -window_size.height()); t.ConcatScale(1, -1); t.ConcatTranslate(-window_size.width()/2.0f, -window_size.height()/2.0f); t.ConcatScale(2.0f/window_size.width(), 2.0f/window_size.height()); DCHECK(compositor_->program()); glUseProgram(compositor_->program()); glActiveTexture(GL_TEXTURE0); glUniform1i(compositor_->u_tex_loc(), 0); glBindTexture(GL_TEXTURE_2D, texture_id_); GLfloat m[16]; const SkMatrix& matrix = t.matrix(); // Convert 3x3 view transform matrix (row major) into 4x4 GL matrix (column // major). Assume 2-D rotations/translations restricted to XY plane. m[ 0] = matrix[0]; m[ 1] = matrix[3]; m[ 2] = 0; m[ 3] = matrix[6]; m[ 4] = matrix[1]; m[ 5] = matrix[4]; m[ 6] = 0; m[ 7] = matrix[7]; m[ 8] = 0; m[ 9] = 0; m[10] = 1; m[11] = 0; m[12] = matrix[2]; m[13] = matrix[5]; m[14] = 0; m[15] = matrix[8]; const GLfloat vertices[] = { -1., -1., +0., +0., +1., +1., -1., +0., +1., +1., +1., +1., +0., +1., +0., -1., +1., +0., +0., +0. }; glVertexAttribPointer(compositor_->a_pos_loc(), 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), vertices); glVertexAttribPointer(compositor_->a_tex_loc(), 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), &vertices[3]); glEnableVertexAttribArray(compositor_->a_pos_loc()); glEnableVertexAttribArray(compositor_->a_tex_loc()); glUniformMatrix4fv(compositor_->u_mat_loc(), 1, GL_FALSE, m); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } CompositorGL::CompositorGL(gfx::AcceleratedWidget widget) : started_(false) { gl_surface_ = gfx::GLSurface::CreateViewGLSurface(widget); gl_context_ = gfx::GLContext::CreateGLContext(NULL, gl_surface_.get()); gl_context_->MakeCurrent(gl_surface_.get()); if (!InitShaders()) LOG(ERROR) << "Unable to initialize shaders (context = " << static_cast<void*>(gl_context_.get()) << ")" ; glColorMask(true, true, true, true); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } CompositorGL::~CompositorGL() { } void CompositorGL::MakeCurrent() { gl_context_->MakeCurrent(gl_surface_.get()); } gfx::Size CompositorGL::GetSize() { return gl_surface_->GetSize(); } GLuint CompositorGL::program() { return program_; } GLuint CompositorGL::a_pos_loc() { return a_pos_loc_; } GLuint CompositorGL::a_tex_loc() { return a_tex_loc_; } GLuint CompositorGL::u_tex_loc() { return u_tex_loc_; } GLuint CompositorGL::u_mat_loc() { return u_mat_loc_; } Texture* CompositorGL::CreateTexture() { Texture* texture = new TextureGL(this); return texture; } void CompositorGL::NotifyStart() { started_ = true; gl_context_->MakeCurrent(gl_surface_.get()); glViewport(0, 0, gl_surface_->GetSize().width(), gl_surface_->GetSize().height()); // Clear to 'psychedelic' purple to make it easy to spot un-rendered regions. glClearColor(223.0 / 255, 0, 1, 1); glColorMask(true, true, true, true); glClear(GL_COLOR_BUFFER_BIT); // Disable alpha writes, since we're using blending anyways. glColorMask(true, true, true, false); } void CompositorGL::NotifyEnd() { DCHECK(started_); gl_surface_->SwapBuffers(); started_ = false; } void CompositorGL::Blur(const gfx::Rect& bounds) { NOTIMPLEMENTED(); } namespace { GLuint CompileShader(GLenum type, const GLchar* source) { GLuint shader = glCreateShader(type); if (!shader) return 0; glShaderSource(shader, 1, &source, 0); glCompileShader(shader); GLint compiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint info_len = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_len); if (info_len > 0) { char* info_log = reinterpret_cast<char*> ( malloc(sizeof(info_log[0]) * info_len)); glGetShaderInfoLog(shader, info_len, NULL, info_log); LOG(ERROR) << "Compile error: " << info_log; free(info_log); return 0; } } return shader; } } // namespace (anonymous) bool CompositorGL::InitShaders() { const GLchar* vertex_shader_source = "attribute vec4 a_position;" "attribute vec2 a_texCoord;" "uniform mat4 u_matViewProjection;" "varying vec2 v_texCoord;" "void main()" "{" " gl_Position = u_matViewProjection * a_position;" " v_texCoord = a_texCoord;" "}"; GLuint vertex_shader = CompileShader(GL_VERTEX_SHADER, vertex_shader_source); if (!vertex_shader) return false; const GLchar* frag_shader_source = "#ifdef GL_ES\n" "precision mediump float;\n" "#endif\n" "uniform sampler2D u_tex;" "varying vec2 v_texCoord;" "void main()" "{" " gl_FragColor = texture2D(u_tex, v_texCoord).zyxw;" "}"; GLuint frag_shader = CompileShader(GL_FRAGMENT_SHADER, frag_shader_source); if (!frag_shader) return false; program_ = glCreateProgram(); glAttachShader(program_, vertex_shader); glAttachShader(program_, frag_shader); glLinkProgram(program_); if (glGetError() != GL_NO_ERROR) return false; // Store locations of program inputs. a_pos_loc_ = glGetAttribLocation(program_, "a_position"); a_tex_loc_ = glGetAttribLocation(program_, "a_texCoord"); u_tex_loc_ = glGetUniformLocation(program_, "u_tex"); u_mat_loc_ = glGetUniformLocation(program_, "u_matViewProjection"); return true; } } // namespace // static Compositor* Compositor::Create(gfx::AcceleratedWidget widget) { gfx::GLSurface::InitializeOneOff(); if (gfx::GetGLImplementation() != gfx::kGLImplementationNone) return new glHidden::CompositorGL(widget); return NULL; } } // namespace ui <commit_msg>Re-enable thread IO restriction override.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/compositor/compositor.h" #include <GL/gl.h> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/threading/thread_restrictions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkMatrix.h" #include "third_party/skia/include/core/SkScalar.h" #include "ui/gfx/rect.h" #include "ui/gfx/transform.h" #include "ui/gfx/gl/gl_bindings.h" #include "ui/gfx/gl/gl_context.h" #include "ui/gfx/gl/gl_implementation.h" #include "ui/gfx/gl/gl_surface.h" #include "ui/gfx/gl/gl_surface_glx.h" namespace ui { namespace glHidden { class CompositorGL; class TextureGL : public Texture { public: TextureGL(CompositorGL* compositor); virtual ~TextureGL(); virtual void SetBitmap(const SkBitmap& bitmap, const gfx::Point& origin, const gfx::Size& overall_size) OVERRIDE; // Draws the texture. virtual void Draw(const ui::Transform& transform) OVERRIDE; private: unsigned int texture_id_; gfx::Size size_; CompositorGL* compositor_; DISALLOW_COPY_AND_ASSIGN(TextureGL); }; class CompositorGL : public Compositor { public: explicit CompositorGL(gfx::AcceleratedWidget widget); virtual ~CompositorGL(); void MakeCurrent(); gfx::Size GetSize(); GLuint program(); GLuint a_pos_loc(); GLuint a_tex_loc(); GLuint u_tex_loc(); GLuint u_mat_loc(); private: // Overridden from Compositor. virtual Texture* CreateTexture() OVERRIDE; virtual void NotifyStart() OVERRIDE; virtual void NotifyEnd() OVERRIDE; virtual void Blur(const gfx::Rect& bounds) OVERRIDE; // Specific to CompositorGL. bool InitShaders(); // The GL context used for compositing. scoped_refptr<gfx::GLSurface> gl_surface_; scoped_refptr<gfx::GLContext> gl_context_; gfx::Size size_; // Shader program, attributes and uniforms. // TODO(wjmaclean): Make these static so they ca be shared in a single // context. GLuint program_; GLuint a_pos_loc_; GLuint a_tex_loc_; GLuint u_tex_loc_; GLuint u_mat_loc_; // Keep track of whether compositing has started or not. bool started_; DISALLOW_COPY_AND_ASSIGN(CompositorGL); }; TextureGL::TextureGL(CompositorGL* compositor) : texture_id_(0), compositor_(compositor) { } TextureGL::~TextureGL() { if (texture_id_) { compositor_->MakeCurrent(); glDeleteTextures(1, &texture_id_); } } void TextureGL::SetBitmap(const SkBitmap& bitmap, const gfx::Point& origin, const gfx::Size& overall_size) { // Verify bitmap pixels are contiguous. DCHECK_EQ(bitmap.rowBytes(), SkBitmap::ComputeRowBytes(bitmap.config(), bitmap.width())); SkAutoLockPixels lock (bitmap); void* pixels = bitmap.getPixels(); if (!texture_id_) { // Texture needs to be created. We assume the first call is for // a full-sized canvas. size_ = overall_size; glGenTextures(1, &texture_id_); glBindTexture(GL_TEXTURE_2D, texture_id_); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size_.width(), size_.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else if (size_ != overall_size) { // Size has changed. size_ = overall_size; glBindTexture(GL_TEXTURE_2D, texture_id_); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size_.width(), size_.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); } else { // Uploading partial texture. glBindTexture(GL_TEXTURE_2D, texture_id_); glTexSubImage2D(GL_TEXTURE_2D, 0, origin.x(), origin.y(), bitmap.width(), bitmap.height(), GL_RGBA, GL_UNSIGNED_BYTE, pixels); } } void TextureGL::Draw(const ui::Transform& transform) { gfx::Size window_size = compositor_->GetSize(); ui::Transform t; t.ConcatTranslate(1,1); t.ConcatScale(size_.width()/2.0f, size_.height()/2.0f); t.ConcatTranslate(0, -size_.height()); t.ConcatScale(1, -1); t.ConcatTransform(transform); // Add view transform. t.ConcatTranslate(0, -window_size.height()); t.ConcatScale(1, -1); t.ConcatTranslate(-window_size.width()/2.0f, -window_size.height()/2.0f); t.ConcatScale(2.0f/window_size.width(), 2.0f/window_size.height()); DCHECK(compositor_->program()); glUseProgram(compositor_->program()); glActiveTexture(GL_TEXTURE0); glUniform1i(compositor_->u_tex_loc(), 0); glBindTexture(GL_TEXTURE_2D, texture_id_); GLfloat m[16]; const SkMatrix& matrix = t.matrix(); // Convert 3x3 view transform matrix (row major) into 4x4 GL matrix (column // major). Assume 2-D rotations/translations restricted to XY plane. m[ 0] = matrix[0]; m[ 1] = matrix[3]; m[ 2] = 0; m[ 3] = matrix[6]; m[ 4] = matrix[1]; m[ 5] = matrix[4]; m[ 6] = 0; m[ 7] = matrix[7]; m[ 8] = 0; m[ 9] = 0; m[10] = 1; m[11] = 0; m[12] = matrix[2]; m[13] = matrix[5]; m[14] = 0; m[15] = matrix[8]; const GLfloat vertices[] = { -1., -1., +0., +0., +1., +1., -1., +0., +1., +1., +1., +1., +0., +1., +0., -1., +1., +0., +0., +0. }; glVertexAttribPointer(compositor_->a_pos_loc(), 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), vertices); glVertexAttribPointer(compositor_->a_tex_loc(), 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), &vertices[3]); glEnableVertexAttribArray(compositor_->a_pos_loc()); glEnableVertexAttribArray(compositor_->a_tex_loc()); glUniformMatrix4fv(compositor_->u_mat_loc(), 1, GL_FALSE, m); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } CompositorGL::CompositorGL(gfx::AcceleratedWidget widget) : started_(false) { gl_surface_ = gfx::GLSurface::CreateViewGLSurface(widget); gl_context_ = gfx::GLContext::CreateGLContext(NULL, gl_surface_.get()); gl_context_->MakeCurrent(gl_surface_.get()); if (!InitShaders()) LOG(ERROR) << "Unable to initialize shaders (context = " << static_cast<void*>(gl_context_.get()) << ")" ; glColorMask(true, true, true, true); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } CompositorGL::~CompositorGL() { } void CompositorGL::MakeCurrent() { gl_context_->MakeCurrent(gl_surface_.get()); } gfx::Size CompositorGL::GetSize() { return gl_surface_->GetSize(); } GLuint CompositorGL::program() { return program_; } GLuint CompositorGL::a_pos_loc() { return a_pos_loc_; } GLuint CompositorGL::a_tex_loc() { return a_tex_loc_; } GLuint CompositorGL::u_tex_loc() { return u_tex_loc_; } GLuint CompositorGL::u_mat_loc() { return u_mat_loc_; } Texture* CompositorGL::CreateTexture() { Texture* texture = new TextureGL(this); return texture; } void CompositorGL::NotifyStart() { started_ = true; gl_context_->MakeCurrent(gl_surface_.get()); glViewport(0, 0, gl_surface_->GetSize().width(), gl_surface_->GetSize().height()); // Clear to 'psychedelic' purple to make it easy to spot un-rendered regions. glClearColor(223.0 / 255, 0, 1, 1); glColorMask(true, true, true, true); glClear(GL_COLOR_BUFFER_BIT); // Disable alpha writes, since we're using blending anyways. glColorMask(true, true, true, false); } void CompositorGL::NotifyEnd() { DCHECK(started_); gl_surface_->SwapBuffers(); started_ = false; } void CompositorGL::Blur(const gfx::Rect& bounds) { NOTIMPLEMENTED(); } namespace { GLuint CompileShader(GLenum type, const GLchar* source) { GLuint shader = glCreateShader(type); if (!shader) return 0; glShaderSource(shader, 1, &source, 0); glCompileShader(shader); GLint compiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint info_len = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_len); if (info_len > 0) { char* info_log = reinterpret_cast<char*> ( malloc(sizeof(info_log[0]) * info_len)); glGetShaderInfoLog(shader, info_len, NULL, info_log); LOG(ERROR) << "Compile error: " << info_log; free(info_log); return 0; } } return shader; } } // namespace (anonymous) bool CompositorGL::InitShaders() { const GLchar* vertex_shader_source = "attribute vec4 a_position;" "attribute vec2 a_texCoord;" "uniform mat4 u_matViewProjection;" "varying vec2 v_texCoord;" "void main()" "{" " gl_Position = u_matViewProjection * a_position;" " v_texCoord = a_texCoord;" "}"; GLuint vertex_shader = CompileShader(GL_VERTEX_SHADER, vertex_shader_source); if (!vertex_shader) return false; const GLchar* frag_shader_source = "#ifdef GL_ES\n" "precision mediump float;\n" "#endif\n" "uniform sampler2D u_tex;" "varying vec2 v_texCoord;" "void main()" "{" " gl_FragColor = texture2D(u_tex, v_texCoord).zyxw;" "}"; GLuint frag_shader = CompileShader(GL_FRAGMENT_SHADER, frag_shader_source); if (!frag_shader) return false; program_ = glCreateProgram(); glAttachShader(program_, vertex_shader); glAttachShader(program_, frag_shader); glLinkProgram(program_); if (glGetError() != GL_NO_ERROR) return false; // Store locations of program inputs. a_pos_loc_ = glGetAttribLocation(program_, "a_position"); a_tex_loc_ = glGetAttribLocation(program_, "a_texCoord"); u_tex_loc_ = glGetUniformLocation(program_, "u_tex"); u_mat_loc_ = glGetUniformLocation(program_, "u_matViewProjection"); return true; } } // namespace // static Compositor* Compositor::Create(gfx::AcceleratedWidget widget) { // The following line of code exists soley to disable IO restrictions // on this thread long enough to perform the GL bindings. // TODO(wjmaclean) Remove this when GL initialisation cleaned up. base::ThreadRestrictions::ScopedAllowIO allow_io; gfx::GLSurface::InitializeOneOff(); if (gfx::GetGLImplementation() != gfx::kGLImplementationNone) return new glHidden::CompositorGL(widget); return NULL; } } // namespace ui <|endoftext|>
<commit_before>#include "ride/runner.h" #include <wx/utils.h> #include <wx/process.h> #include <wx/txtstrm.h> #include "ride/mainwindow.h" class PipedProcess; class Process; ////////////////////////////////////////////////////////////////////////// Command::Command(const wxString& r, const wxString& c) : root(r), cmd(c) { } ////////////////////////////////////////////////////////////////////////// class IdleTimer : public wxTimer { public: void Notify() { wxWakeUpIdle(); } }; ////////////////////////////////////////////////////////////////////////// struct SingleRunner::Pimpl { explicit Pimpl(SingleRunner* p) : parent_(p), processes_(NULL), delete_processes_(NULL), pid_(0), exit_code_(-1) { assert(parent_); } ~Pimpl(); void Append(const wxString& s) { parent_->Append(s); } void MarkForDeletion(Process *process); bool RunCmd(const Command& cmd); void OnCompleted() { assert(parent_); parent_->Completed(); idle_timer_.Stop(); } SingleRunner* parent_; Process* processes_; // the current running process or NULL Process* delete_processes_; // process to be deleted at the end long pid_; // the id of the current or previous running process int exit_code_; IdleTimer idle_timer_; }; class Process : public wxProcess { public: Process(SingleRunner::Pimpl* project, const wxString& cmd) : wxProcess(), cmd_(cmd) { runner_ = project; Redirect(); } virtual void OnTerminate(int pid, int status) { assert(runner_->pid_ == pid); // show the rest of the output while (HasInput()) {} runner_->MarkForDeletion(this); runner_->Append(wxString::Format(wxT("Process %u ('%s') terminated with exit code %d."), pid, cmd_.c_str(), status)); runner_->Append(""); runner_->exit_code_ = status; runner_->OnCompleted(); } virtual bool HasInput() { // original source: http://sourceforge.net/p/fourpane/code/HEAD/tree/trunk/ExecuteInDialog.cpp // The original used wxTextInputStream to read a line at a time. Fine, except when there was no \n, whereupon the thing would hang // Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString bool hasInput = false; while (IsInputAvailable()) { wxMemoryBuffer buf; do { const char c = GetInputStream()->GetC(); if (GetInputStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsInputAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); // Convert the line to utf8 runner_->Append(line); hasInput = true; } while (IsErrorAvailable()) { wxMemoryBuffer buf; do { const char c = GetErrorStream()->GetC(); if (GetErrorStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsErrorAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); runner_->Append(line); hasInput = true; } return hasInput; } protected: SingleRunner::Pimpl *runner_; wxString cmd_; }; bool SingleRunner::Pimpl::RunCmd(const Command& c) { Process* process = new Process(this, c.cmd); Append("> " + c.cmd); wxExecuteEnv env; env.cwd = c.root; const int flags = wxEXEC_ASYNC | wxEXEC_SHOW_CONSOLE; const long process_id = wxExecute(c.cmd, flags, process, &env); // async call if (!process_id) { Append(wxT("Execution failed.")); delete process; return false; } assert(processes_ == NULL); assert(pid_ == 0); processes_ = process; pid_ = process_id; idle_timer_.Start(100); return true; } void SingleRunner::Pimpl::MarkForDeletion(Process *process) { assert(processes_ == process); processes_ = NULL; delete_processes_ = process; } SingleRunner::Pimpl:: ~Pimpl() { delete delete_processes_; } ////////////////////////////////////////////////////////////////////////// SingleRunner::SingleRunner() : pimpl(new Pimpl(this)) { } SingleRunner::~SingleRunner() { } bool SingleRunner::RunCmd(const Command& cmd) { assert(pimpl); assert(this->IsRunning() == false); return pimpl->RunCmd(cmd); } bool SingleRunner::IsRunning() const { return pimpl->processes_ != NULL; } void SingleRunner::Completed() { // empty } int SingleRunner::GetExitCode() { assert(this->IsRunning() == false); assert(pimpl->pid_ != 0); return pimpl->exit_code_; } ////////////////////////////////////////////////////////////////////////// class MultiRunner::Runner : public SingleRunner { public: Runner(MultiRunner* r) : runner_(r) { assert(runner_); } virtual void Append(const wxString& str) { assert(runner_); runner_->Append(str); } virtual void Completed() { assert(runner_); runner_->RunNext(GetExitCode()); } bool Run(const Command& cmd) { return RunCmd(cmd); } private: MultiRunner* runner_; }; MultiRunner::MultiRunner(){ } MultiRunner::~MultiRunner(){ } bool MultiRunner::RunCmd(const Command& cmd) { commands_.push_back(cmd); if (IsRunning() == true) return true; return RunNext(0); } bool MultiRunner::RunNext(int last_exit_code) { assert(IsRunning() == false); if (commands_.empty()) return false; if (last_exit_code == 0) { last_runner_ = runner_; runner_.reset(new Runner(this)); const bool run_result = runner_->Run(*commands_.begin()); if (run_result) { commands_.erase(commands_.begin()); } return run_result; } else { commands_.clear(); return false; } } bool MultiRunner::IsRunning() const { if (runner_) { return runner_->IsRunning(); } return false; } <commit_msg>bugfix: build automatically finishes now<commit_after>#include "ride/runner.h" #include <wx/utils.h> #include <wx/process.h> #include <wx/txtstrm.h> #include "ride/mainwindow.h" class PipedProcess; class Process; ////////////////////////////////////////////////////////////////////////// Command::Command(const wxString& r, const wxString& c) : root(r), cmd(c) { } ////////////////////////////////////////////////////////////////////////// // idle timer to keep the process updated since wx apperently doesn't do that class IdleTimer : public wxTimer { public: IdleTimer(SingleRunner::Pimpl* p) : pimpl_(p) { } void Notify(); SingleRunner::Pimpl* pimpl_; }; ////////////////////////////////////////////////////////////////////////// struct SingleRunner::Pimpl { explicit Pimpl(SingleRunner* p) : parent_(p), processes_(NULL), delete_processes_(NULL), pid_(0), exit_code_(-1) { assert(parent_); idle_timer_.reset(new IdleTimer(this)); } ~Pimpl(); void Append(const wxString& s) { parent_->Append(s); } void MarkForDeletion(Process *process); bool RunCmd(const Command& cmd); void Notify(); void OnCompleted() { assert(parent_); parent_->Completed(); idle_timer_->Stop(); } SingleRunner* parent_; Process* processes_; // the current running process or NULL Process* delete_processes_; // process to be deleted at the end long pid_; // the id of the current or previous running process int exit_code_; std::unique_ptr<IdleTimer> idle_timer_; }; void IdleTimer::Notify() { pimpl_->Notify(); } class Process : public wxProcess { public: Process(SingleRunner::Pimpl* project, const wxString& cmd) : wxProcess(wxPROCESS_DEFAULT), cmd_(cmd) { runner_ = project; Redirect(); } virtual void OnTerminate(int pid, int status) { assert(runner_->pid_ == pid); // show the rest of the output while (HasInput()) {} runner_->MarkForDeletion(this); runner_->Append(wxString::Format(wxT("Process %u ('%s') terminated with exit code %d."), pid, cmd_.c_str(), status)); runner_->Append(""); runner_->exit_code_ = status; runner_->OnCompleted(); } virtual bool HasInput() { // original source: http://sourceforge.net/p/fourpane/code/HEAD/tree/trunk/ExecuteInDialog.cpp // The original used wxTextInputStream to read a line at a time. Fine, except when there was no \n, whereupon the thing would hang // Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString bool hasInput = false; while (IsInputAvailable()) { wxMemoryBuffer buf; do { const char c = GetInputStream()->GetC(); if (GetInputStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsInputAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); // Convert the line to utf8 runner_->Append(line); hasInput = true; } while (IsErrorAvailable()) { wxMemoryBuffer buf; do { const char c = GetErrorStream()->GetC(); if (GetErrorStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsErrorAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); runner_->Append(line); hasInput = true; } return hasInput; } protected: SingleRunner::Pimpl *runner_; wxString cmd_; }; void SingleRunner::Pimpl::Notify(){ if (processes_) { // sometimes the output hangs until we close the window // seems to be waiting for output or something // getting the input in a callback seems to remove the waiting... processes_->HasInput(); } } bool SingleRunner::Pimpl::RunCmd(const Command& c) { Process* process = new Process(this, c.cmd); Append("> " + c.cmd); wxExecuteEnv env; env.cwd = c.root; const int flags = wxEXEC_ASYNC | wxEXEC_SHOW_CONSOLE; const long process_id = wxExecute(c.cmd, flags, process, &env); // async call if (!process_id) { Append(wxT("Execution failed.")); delete process; return false; } assert(processes_ == NULL); assert(pid_ == 0); processes_ = process; pid_ = process_id; idle_timer_->Start(100); return true; } void SingleRunner::Pimpl::MarkForDeletion(Process *process) { assert(processes_ == process); processes_ = NULL; delete_processes_ = process; } SingleRunner::Pimpl:: ~Pimpl() { delete delete_processes_; } ////////////////////////////////////////////////////////////////////////// SingleRunner::SingleRunner() : pimpl(new Pimpl(this)) { } SingleRunner::~SingleRunner() { } bool SingleRunner::RunCmd(const Command& cmd) { assert(pimpl); assert(this->IsRunning() == false); return pimpl->RunCmd(cmd); } bool SingleRunner::IsRunning() const { return pimpl->processes_ != NULL; } void SingleRunner::Completed() { // empty } int SingleRunner::GetExitCode() { assert(this->IsRunning() == false); assert(pimpl->pid_ != 0); return pimpl->exit_code_; } ////////////////////////////////////////////////////////////////////////// class MultiRunner::Runner : public SingleRunner { public: Runner(MultiRunner* r) : runner_(r) { assert(runner_); } virtual void Append(const wxString& str) { assert(runner_); runner_->Append(str); } virtual void Completed() { assert(runner_); runner_->RunNext(GetExitCode()); } bool Run(const Command& cmd) { return RunCmd(cmd); } private: MultiRunner* runner_; }; MultiRunner::MultiRunner(){ } MultiRunner::~MultiRunner(){ } bool MultiRunner::RunCmd(const Command& cmd) { commands_.push_back(cmd); if (IsRunning() == true) return true; return RunNext(0); } bool MultiRunner::RunNext(int last_exit_code) { assert(IsRunning() == false); if (commands_.empty()) return false; if (last_exit_code == 0) { last_runner_ = runner_; runner_.reset(new Runner(this)); const bool run_result = runner_->Run(*commands_.begin()); if (run_result) { commands_.erase(commands_.begin()); } return run_result; } else { commands_.clear(); return false; } } bool MultiRunner::IsRunning() const { if (runner_) { return runner_->IsRunning(); } return false; } <|endoftext|>
<commit_before>/* Bacula® - The Network Backup Solution Copyright (C) 2007-2009 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation and included in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Bacula® is a registered trademark of Kern Sibbald. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ /* * Version $Id$ * * Jobs Class * * Dirk Bartley, March 2007 * */ #include "bat.h" #include "jobs/jobs.h" #include "run/run.h" #include "util/fmtwidgetitem.h" Jobs::Jobs() { setupUi(this); m_name = tr("Jobs"); pgInitialize(); QTreeWidgetItem* thisitem = mainWin->getFromHash(this); thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/run.png"))); /* tableWidget, Storage Tree Tree Widget inherited from ui_client.h */ m_populated = false; m_checkcurwidget = true; m_closeable = false; /* add context sensitive menu items specific to this classto the page * selector tree. m_contextActions is QList of QActions */ m_contextActions.append(actionRefreshJobs); createContextMenu(); dockPage(); } Jobs::~Jobs() { } /* * The main meat of the class!! The function that querries the director and * creates the widgets with appropriate values. */ void Jobs::populateTable() { m_populated = true; mainWin->waitEnter(); Freeze frz(*tableWidget); /* disable updating*/ QBrush blackBrush(Qt::black); m_checkcurwidget = false; tableWidget->clear(); m_checkcurwidget = true; QStringList headerlist = (QStringList() << tr("Job Name") << tr("Pool") << tr("Messages") << tr("Client") << tr("Storage") << tr("Level") << tr("Type") << tr("FileSet") << tr("Catalog") << tr("Enabled") << tr("Where")); m_typeIndex = headerlist.indexOf(tr("Type")); tableWidget->setColumnCount(headerlist.count()); tableWidget->setHorizontalHeaderLabels(headerlist); tableWidget->horizontalHeader()->setHighlightSections(false); tableWidget->setRowCount(m_console->job_list.count()); tableWidget->verticalHeader()->hide(); tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); tableWidget->setSortingEnabled(false); /* rows move on insert if sorting enabled */ int row = 0; foreach (QString jobName, m_console->job_list){ job_defaults job_defs; job_defs.job_name = jobName; if (m_console->get_job_defaults(job_defs)) { int col = 0; TableItemFormatter jobsItem(*tableWidget, row); jobsItem.setTextFld(col++, jobName); jobsItem.setTextFld(col++, job_defs.pool_name); jobsItem.setTextFld(col++, job_defs.messages_name); jobsItem.setTextFld(col++, job_defs.client_name); jobsItem.setTextFld(col++, job_defs.store_name); jobsItem.setTextFld(col++, job_defs.level); jobsItem.setTextFld(col++, job_defs.type); jobsItem.setTextFld(col++, job_defs.fileset_name); jobsItem.setTextFld(col++, job_defs.catalog_name); jobsItem.setBoolFld(col++, job_defs.enabled); jobsItem.setTextFld(col++, job_defs.where); } row++; } /* set default sorting */ tableWidget->sortByColumn(headerlist.indexOf(tr("Job Name")), Qt::AscendingOrder); tableWidget->setSortingEnabled(true); /* Resize rows and columns */ tableWidget->resizeColumnsToContents(); tableWidget->resizeRowsToContents(); /* make read only */ int rcnt = tableWidget->rowCount(); int ccnt = tableWidget->columnCount(); for(int r=0; r < rcnt; r++) { for(int c=0; c < ccnt; c++) { QTableWidgetItem* item = tableWidget->item(r, c); if (item) { item->setFlags(Qt::ItemFlags(item->flags() & (~Qt::ItemIsEditable))); } } } mainWin->waitExit(); } /* * When the treeWidgetItem in the page selector tree is singleclicked, Make sure * The tree has been populated. */ void Jobs::PgSeltreeWidgetClicked() { if(!m_populated) { populateTable(); } } /* * Added to set the context menu policy based on currently active tableWidgetItem * signaled by currentItemChanged */ void Jobs::tableItemChanged(QTableWidgetItem *currentwidgetitem, QTableWidgetItem *previouswidgetitem ) { /* m_checkcurwidget checks to see if this is during a refresh, which will segfault */ if (m_checkcurwidget && currentwidgetitem) { /* The Previous item */ if (previouswidgetitem) { /* avoid a segfault if first time */ foreach(QAction* jobAction, tableWidget->actions()) { tableWidget->removeAction(jobAction); } } int currentRow = currentwidgetitem->row(); QTableWidgetItem *currentrowzeroitem = tableWidget->item(currentRow, 0); m_currentlyselected = currentrowzeroitem->text(); QTableWidgetItem *currenttypeitem = tableWidget->item(currentRow, m_typeIndex); QString type = currenttypeitem->text(); if (m_currentlyselected.length() != 0) { /* set a hold variable to the client name in case the context sensitive * menu is used */ tableWidget->addAction(actionConsoleListFiles); tableWidget->addAction(actionConsoleListVolumes); tableWidget->addAction(actionConsoleListNextVolume); tableWidget->addAction(actionConsoleEnableJob); tableWidget->addAction(actionConsoleDisableJob); tableWidget->addAction(actionConsoleCancel); tableWidget->addAction(actionJobListQuery); tableWidget->addAction(actionRunJob); } } } /* * Setup a context menu * Made separate from populate so that it would not create context menu over and * over as the table is repopulated. */ void Jobs::createContextMenu() { tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu); tableWidget->addAction(actionRefreshJobs); connect(tableWidget, SIGNAL( currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)), this, SLOT(tableItemChanged(QTableWidgetItem *, QTableWidgetItem *))); /* connect to the action specific to this pages class */ connect(actionRefreshJobs, SIGNAL(triggered()), this, SLOT(populateTable())); connect(actionConsoleListFiles, SIGNAL(triggered()), this, SLOT(consoleListFiles())); connect(actionConsoleListVolumes, SIGNAL(triggered()), this, SLOT(consoleListVolume())); connect(actionConsoleListNextVolume, SIGNAL(triggered()), this, SLOT(consoleListNextVolume())); connect(actionConsoleEnableJob, SIGNAL(triggered()), this, SLOT(consoleEnable())); connect(actionConsoleDisableJob, SIGNAL(triggered()), this, SLOT(consoleDisable())); connect(actionConsoleCancel, SIGNAL(triggered()), this, SLOT(consoleCancel())); connect(actionJobListQuery, SIGNAL(triggered()), this, SLOT(listJobs())); connect(actionRunJob, SIGNAL(triggered()), this, SLOT(runJob())); } /* * Virtual function which is called when this page is visible on the stack */ void Jobs::currentStackItem() { if(!m_populated) { /* Create the context menu for the client table */ populateTable(); } } /* * The following functions are slots responding to users clicking on the context * sensitive menu */ void Jobs::consoleListFiles() { QString cmd = "list files job=\"" + m_currentlyselected + "\""; if (mainWin->m_longList) { cmd.prepend("l"); } consoleCommand(cmd); } void Jobs::consoleListVolume() { QString cmd = "list volumes job=\"" + m_currentlyselected + "\""; if (mainWin->m_longList) { cmd.prepend("l"); } consoleCommand(cmd); } void Jobs::consoleListNextVolume() { QString cmd = "list nextvolume job=\"" + m_currentlyselected + "\""; if (mainWin->m_longList) { cmd.prepend("l"); } consoleCommand(cmd); } void Jobs::consoleEnable() { QString cmd = "enable job=\"" + m_currentlyselected + "\""; consoleCommand(cmd); } void Jobs::consoleDisable() { QString cmd = "disable job=\"" + m_currentlyselected + "\""; consoleCommand(cmd); } void Jobs::consoleCancel() { QString cmd = "cancel job=\"" + m_currentlyselected + "\""; consoleCommand(cmd); } void Jobs::listJobs() { QTreeWidgetItem *parentItem = mainWin->getFromHash(this); mainWin->createPageJobList("", "", m_currentlyselected, "", parentItem); } /* * Open a new job run page with the currently selected job * defaulted In */ void Jobs::runJob() { new runPage(m_currentlyselected); } <commit_msg>Somehow I was losing the refresh jobs action. This should keep it in.<commit_after>/* Bacula® - The Network Backup Solution Copyright (C) 2007-2009 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation and included in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Bacula® is a registered trademark of Kern Sibbald. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ /* * Version $Id$ * * Jobs Class * * Dirk Bartley, March 2007 * */ #include "bat.h" #include "jobs/jobs.h" #include "run/run.h" #include "util/fmtwidgetitem.h" Jobs::Jobs() { setupUi(this); m_name = tr("Jobs"); pgInitialize(); QTreeWidgetItem* thisitem = mainWin->getFromHash(this); thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/run.png"))); /* tableWidget, Storage Tree Tree Widget inherited from ui_client.h */ m_populated = false; m_checkcurwidget = true; m_closeable = false; /* add context sensitive menu items specific to this classto the page * selector tree. m_contextActions is QList of QActions */ m_contextActions.append(actionRefreshJobs); createContextMenu(); dockPage(); } Jobs::~Jobs() { } /* * The main meat of the class!! The function that querries the director and * creates the widgets with appropriate values. */ void Jobs::populateTable() { m_populated = true; mainWin->waitEnter(); Freeze frz(*tableWidget); /* disable updating*/ QBrush blackBrush(Qt::black); m_checkcurwidget = false; tableWidget->clear(); m_checkcurwidget = true; QStringList headerlist = (QStringList() << tr("Job Name") << tr("Pool") << tr("Messages") << tr("Client") << tr("Storage") << tr("Level") << tr("Type") << tr("FileSet") << tr("Catalog") << tr("Enabled") << tr("Where")); m_typeIndex = headerlist.indexOf(tr("Type")); tableWidget->setColumnCount(headerlist.count()); tableWidget->setHorizontalHeaderLabels(headerlist); tableWidget->horizontalHeader()->setHighlightSections(false); tableWidget->setRowCount(m_console->job_list.count()); tableWidget->verticalHeader()->hide(); tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); tableWidget->setSortingEnabled(false); /* rows move on insert if sorting enabled */ int row = 0; foreach (QString jobName, m_console->job_list){ job_defaults job_defs; job_defs.job_name = jobName; if (m_console->get_job_defaults(job_defs)) { int col = 0; TableItemFormatter jobsItem(*tableWidget, row); jobsItem.setTextFld(col++, jobName); jobsItem.setTextFld(col++, job_defs.pool_name); jobsItem.setTextFld(col++, job_defs.messages_name); jobsItem.setTextFld(col++, job_defs.client_name); jobsItem.setTextFld(col++, job_defs.store_name); jobsItem.setTextFld(col++, job_defs.level); jobsItem.setTextFld(col++, job_defs.type); jobsItem.setTextFld(col++, job_defs.fileset_name); jobsItem.setTextFld(col++, job_defs.catalog_name); jobsItem.setBoolFld(col++, job_defs.enabled); jobsItem.setTextFld(col++, job_defs.where); } row++; } /* set default sorting */ tableWidget->sortByColumn(headerlist.indexOf(tr("Job Name")), Qt::AscendingOrder); tableWidget->setSortingEnabled(true); /* Resize rows and columns */ tableWidget->resizeColumnsToContents(); tableWidget->resizeRowsToContents(); /* make read only */ int rcnt = tableWidget->rowCount(); int ccnt = tableWidget->columnCount(); for(int r=0; r < rcnt; r++) { for(int c=0; c < ccnt; c++) { QTableWidgetItem* item = tableWidget->item(r, c); if (item) { item->setFlags(Qt::ItemFlags(item->flags() & (~Qt::ItemIsEditable))); } } } mainWin->waitExit(); } /* * When the treeWidgetItem in the page selector tree is singleclicked, Make sure * The tree has been populated. */ void Jobs::PgSeltreeWidgetClicked() { if(!m_populated) { populateTable(); } } /* * Added to set the context menu policy based on currently active tableWidgetItem * signaled by currentItemChanged */ void Jobs::tableItemChanged(QTableWidgetItem *currentwidgetitem, QTableWidgetItem *previouswidgetitem ) { /* m_checkcurwidget checks to see if this is during a refresh, which will segfault */ if (m_checkcurwidget && currentwidgetitem) { /* The Previous item */ if (previouswidgetitem) { /* avoid a segfault if first time */ foreach(QAction* jobAction, tableWidget->actions()) { tableWidget->removeAction(jobAction); } } int currentRow = currentwidgetitem->row(); QTableWidgetItem *currentrowzeroitem = tableWidget->item(currentRow, 0); m_currentlyselected = currentrowzeroitem->text(); QTableWidgetItem *currenttypeitem = tableWidget->item(currentRow, m_typeIndex); QString type = currenttypeitem->text(); if (m_currentlyselected.length() != 0) { /* set a hold variable to the client name in case the context sensitive * menu is used */ tableWidget->addAction(actionRefreshJobs); tableWidget->addAction(actionConsoleListFiles); tableWidget->addAction(actionConsoleListVolumes); tableWidget->addAction(actionConsoleListNextVolume); tableWidget->addAction(actionConsoleEnableJob); tableWidget->addAction(actionConsoleDisableJob); tableWidget->addAction(actionConsoleCancel); tableWidget->addAction(actionJobListQuery); tableWidget->addAction(actionRunJob); } } } /* * Setup a context menu * Made separate from populate so that it would not create context menu over and * over as the table is repopulated. */ void Jobs::createContextMenu() { tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu); tableWidget->addAction(actionRefreshJobs); connect(tableWidget, SIGNAL( currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)), this, SLOT(tableItemChanged(QTableWidgetItem *, QTableWidgetItem *))); /* connect to the action specific to this pages class */ connect(actionRefreshJobs, SIGNAL(triggered()), this, SLOT(populateTable())); connect(actionConsoleListFiles, SIGNAL(triggered()), this, SLOT(consoleListFiles())); connect(actionConsoleListVolumes, SIGNAL(triggered()), this, SLOT(consoleListVolume())); connect(actionConsoleListNextVolume, SIGNAL(triggered()), this, SLOT(consoleListNextVolume())); connect(actionConsoleEnableJob, SIGNAL(triggered()), this, SLOT(consoleEnable())); connect(actionConsoleDisableJob, SIGNAL(triggered()), this, SLOT(consoleDisable())); connect(actionConsoleCancel, SIGNAL(triggered()), this, SLOT(consoleCancel())); connect(actionJobListQuery, SIGNAL(triggered()), this, SLOT(listJobs())); connect(actionRunJob, SIGNAL(triggered()), this, SLOT(runJob())); } /* * Virtual function which is called when this page is visible on the stack */ void Jobs::currentStackItem() { if(!m_populated) { /* Create the context menu for the client table */ populateTable(); } } /* * The following functions are slots responding to users clicking on the context * sensitive menu */ void Jobs::consoleListFiles() { QString cmd = "list files job=\"" + m_currentlyselected + "\""; if (mainWin->m_longList) { cmd.prepend("l"); } consoleCommand(cmd); } void Jobs::consoleListVolume() { QString cmd = "list volumes job=\"" + m_currentlyselected + "\""; if (mainWin->m_longList) { cmd.prepend("l"); } consoleCommand(cmd); } void Jobs::consoleListNextVolume() { QString cmd = "list nextvolume job=\"" + m_currentlyselected + "\""; if (mainWin->m_longList) { cmd.prepend("l"); } consoleCommand(cmd); } void Jobs::consoleEnable() { QString cmd = "enable job=\"" + m_currentlyselected + "\""; consoleCommand(cmd); } void Jobs::consoleDisable() { QString cmd = "disable job=\"" + m_currentlyselected + "\""; consoleCommand(cmd); } void Jobs::consoleCancel() { QString cmd = "cancel job=\"" + m_currentlyselected + "\""; consoleCommand(cmd); } void Jobs::listJobs() { QTreeWidgetItem *parentItem = mainWin->getFromHash(this); mainWin->createPageJobList("", "", m_currentlyselected, "", parentItem); } /* * Open a new job run page with the currently selected job * defaulted In */ void Jobs::runJob() { new runPage(m_currentlyselected); } <|endoftext|>
<commit_before>#include<xerus.h> #include "../../include/xerus/test/test.h" using namespace xerus; static misc::UnitTest tt_entryprod("TT", "entrywise_product", [](){ Index i,j,k; TTTensor A = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); TTTensor B = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); Tensor Af(A); Tensor Bf(B); TTOperator Ao(Af); TTOperator Bo(Bf); TTTensor C = entrywise_product(A, B); TTOperator Co = entrywise_product(Ao, Bo); Tensor Cf = entrywise_product(Af, Bf); MTEST(frob_norm(Cf - Tensor(Co))/frob_norm(Cf) < 1e-13, frob_norm(Cf - Tensor(Co))/frob_norm(Cf)); MTEST(frob_norm(Cf - Tensor(C))/frob_norm(Cf) < 1e-13, frob_norm(Cf - Tensor(C))/frob_norm(Cf)); TTTensor D1 = entrywise_product(A, A); TTOperator Do1 = entrywise_product(Ao, Ao); Tensor Df = entrywise_product(Af, Af); MTEST(approx_equal(Df, Tensor(D1), 1e-13), frob_norm(Df-Tensor(D1))); MTEST(approx_equal(Df, Tensor(Do1), 1e-13), frob_norm(Df- Tensor(Do1))); }); static misc::UnitTest tt_soft("TT", "soft_thresholding", [](){ Index i,j,k; TTTensor A = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); TTTensor B = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); Tensor Af(A); Tensor Bf(B); TTOperator Ao(Af); TTOperator Bo(Bf); TTTensor C = entrywise_product(A, B); TTOperator Co = entrywise_product(Ao, Bo); Tensor Cf = entrywise_product(Af, Bf); TEST(frob_norm(Cf - Tensor(Co))/frob_norm(Cf) < 1e-14); TEST(frob_norm(Cf - Tensor(C))/frob_norm(Cf) < 1e-14); }); <commit_msg>non-operator tt pseudo inverse as unittest<commit_after>#include<xerus.h> #include "../../include/xerus/test/test.h" using namespace xerus; static misc::UnitTest tt_entryprod("TT", "entrywise_product", [](){ Index i,j,k; TTTensor A = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); TTTensor B = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); Tensor Af(A); Tensor Bf(B); TTOperator Ao(Af); TTOperator Bo(Bf); TTTensor C = entrywise_product(A, B); TTOperator Co = entrywise_product(Ao, Bo); Tensor Cf = entrywise_product(Af, Bf); MTEST(frob_norm(Cf - Tensor(Co))/frob_norm(Cf) < 1e-13, frob_norm(Cf - Tensor(Co))/frob_norm(Cf)); MTEST(frob_norm(Cf - Tensor(C))/frob_norm(Cf) < 1e-13, frob_norm(Cf - Tensor(C))/frob_norm(Cf)); TTTensor D1 = entrywise_product(A, A); TTOperator Do1 = entrywise_product(Ao, Ao); Tensor Df = entrywise_product(Af, Af); MTEST(approx_equal(Df, Tensor(D1), 1e-13), frob_norm(Df-Tensor(D1))); MTEST(approx_equal(Df, Tensor(Do1), 1e-13), frob_norm(Df- Tensor(Do1))); }); static misc::UnitTest tt_soft("TT", "soft_thresholding", [](){ Index i,j,k; TTTensor A = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); TTTensor B = TTTensor::random(std::vector<size_t>(10,2), std::vector<size_t>(9,2)); Tensor Af(A); Tensor Bf(B); TTOperator Ao(Af); TTOperator Bo(Bf); TTTensor C = entrywise_product(A, B); TTOperator Co = entrywise_product(Ao, Bo); Tensor Cf = entrywise_product(Af, Bf); TEST(frob_norm(Cf - Tensor(Co))/frob_norm(Cf) < 1e-14); TEST(frob_norm(Cf - Tensor(C))/frob_norm(Cf) < 1e-14); }); static misc::UnitTest tt_pseudo_inv("TT", "Non-operator Pseudo Inverse", [](){ Index i,j,k,r1,r2,r3,r4; const size_t d = 2; const TTTensor op = TTTensor::random(std::vector<size_t>(2*d, 10), std::vector<size_t>(2*d-1, 4)); TTTensor tmp = op; tmp.move_core(d); auto parts = tmp.chop(d); Tensor U,S,V; (U(i,r1), S(r1,r2), V(r2,j^2)) = SVD(tmp.get_component(d)(i,j^2)); S.modify_diagonal_entries([](double &_v){ if (_v>1e-10) { _v = 1/_v; } }); TensorNetwork pInv; pInv(j, i^(d-1), k^d) = parts.first(k^d,r1) * U(r1,r2) * S(r2,r3) * V(r3,j,r4) * parts.second(r4,i^(d-1)); double error = frob_norm(pInv(i^d,r1^d)*op(r1^d,r2^d)*pInv(r2^d,j^d) - pInv(i^d,j^d)); MTEST(error < 1e-10, "A^+ A A^+ != A^+ ? " << error); error = frob_norm(op(i^d,r1^d)*pInv(r1^d,r2^d)*op(r2^d,j^d) - op(i^d,j^d)); MTEST(error < 1e-10, "A A^+ A != A ? " << error); }); <|endoftext|>
<commit_before><commit_msg>protect against NULL current SfxViewShell<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/bubble/bubble_delegate.h" #include "ui/base/animation/slide_animation.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/widget/widget.h" // The duration of the fade animation in milliseconds. static const int kHideFadeDurationMS = 200; namespace views { namespace { // Create a widget to host the bubble. Widget* CreateBubbleWidget(BubbleDelegateView* bubble, Widget* parent) { Widget* bubble_widget = new Widget(); Widget::InitParams bubble_params(Widget::InitParams::TYPE_BUBBLE); bubble_params.delegate = bubble; bubble_params.transparent = true; bubble_params.parent_widget = parent; #if defined(OS_WIN) && !defined(USE_AURA) bubble_params.type = Widget::InitParams::TYPE_WINDOW_FRAMELESS; bubble_params.transparent = false; #endif bubble_widget->Init(bubble_params); return bubble_widget; } #if defined(OS_WIN) && !defined(USE_AURA) // The border widget's delegate, needed for transparent Windows native controls. // TODO(msw): Remove this when Windows native controls are no longer needed. class VIEWS_EXPORT BubbleBorderDelegateView : public WidgetDelegateView { public: explicit BubbleBorderDelegateView(BubbleDelegateView* bubble) : bubble_(bubble) {} virtual ~BubbleBorderDelegateView() {} // WidgetDelegateView overrides: virtual bool CanActivate() const OVERRIDE; virtual NonClientFrameView* CreateNonClientFrameView() OVERRIDE; private: BubbleDelegateView* bubble_; DISALLOW_COPY_AND_ASSIGN(BubbleBorderDelegateView); }; bool BubbleBorderDelegateView::CanActivate() const { return false; } NonClientFrameView* BubbleBorderDelegateView::CreateNonClientFrameView() { return bubble_->CreateNonClientFrameView(); } // Create a widget to host the bubble's border. Widget* CreateBorderWidget(BubbleDelegateView* bubble, Widget* parent) { Widget* border_widget = new Widget(); Widget::InitParams border_params(Widget::InitParams::TYPE_BUBBLE); border_params.delegate = new BubbleBorderDelegateView(bubble); border_params.transparent = true; border_params.parent_widget = parent; if (!border_params.parent_widget) border_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; border_widget->Init(border_params); return border_widget; } #endif } // namespace BubbleDelegateView::BubbleDelegateView() : close_on_esc_(true), close_on_deactivate_(true), allow_bubble_offscreen_(false), anchor_view_(NULL), arrow_location_(BubbleBorder::TOP_LEFT), color_(SK_ColorWHITE), border_widget_(NULL), use_focusless_(false) { set_background(views::Background::CreateSolidBackground(color_)); AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, 0)); } BubbleDelegateView::BubbleDelegateView( View* anchor_view, BubbleBorder::ArrowLocation arrow_location, const SkColor& color) : close_on_esc_(true), close_on_deactivate_(true), allow_bubble_offscreen_(false), anchor_view_(anchor_view), arrow_location_(arrow_location), color_(color), original_opacity_(255), border_widget_(NULL), use_focusless_(false) { set_background(views::Background::CreateSolidBackground(color_)); AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, 0)); } BubbleDelegateView::~BubbleDelegateView() { if (border_widget_) border_widget_->Close(); } // static Widget* BubbleDelegateView::CreateBubble(BubbleDelegateView* bubble_delegate) { bubble_delegate->Init(); Widget* parent = bubble_delegate->anchor_view() ? bubble_delegate->anchor_view()->GetWidget() : NULL; Widget* bubble_widget = CreateBubbleWidget(bubble_delegate, parent); #if defined(OS_WIN) && !defined(USE_AURA) // First set the contents view to initialize view bounds for widget sizing. bubble_widget->SetContentsView(bubble_delegate->GetContentsView()); bubble_delegate->border_widget_ = CreateBorderWidget(bubble_delegate, parent); #endif bubble_delegate->SizeToContents(); bubble_widget->AddObserver(bubble_delegate); if (parent && parent->GetTopLevelWidget()) parent->GetTopLevelWidget()->DisableInactiveRendering(); return bubble_widget; } View* BubbleDelegateView::GetInitiallyFocusedView() { return this; } BubbleDelegateView* BubbleDelegateView::AsBubbleDelegate() { return this; } View* BubbleDelegateView::GetContentsView() { return this; } NonClientFrameView* BubbleDelegateView::CreateNonClientFrameView() { return new BubbleFrameView(GetArrowLocation(), GetPreferredSize(), GetColor(), allow_bubble_offscreen_); } void BubbleDelegateView::OnWidgetActivationChanged(Widget* widget, bool active) { if (close_on_deactivate() && widget == GetWidget() && !active) { GetWidget()->RemoveObserver(this); GetWidget()->Close(); } } gfx::Point BubbleDelegateView::GetAnchorPoint() { if (!anchor_view()) return gfx::Point(); BubbleBorder::ArrowLocation location = GetArrowLocation(); gfx::Point anchor(anchor_view()->bounds().CenterPoint()); // By default, pick the middle of |anchor_view_|'s edge opposite the arrow. if (BubbleBorder::is_arrow_on_horizontal(location)) { anchor.SetPoint(anchor_view()->width() / 2, BubbleBorder::is_arrow_on_top(location) ? anchor_view()->height() : 0); } else if (BubbleBorder::has_arrow(location)) { anchor.SetPoint( BubbleBorder::is_arrow_on_left(location) ? anchor_view()->width() : 0, anchor_view_->height() / 2); } View::ConvertPointToScreen(anchor_view(), &anchor); return anchor; } BubbleBorder::ArrowLocation BubbleDelegateView::GetArrowLocation() const { return arrow_location_; } SkColor BubbleDelegateView::GetColor() const { return color_; } void BubbleDelegateView::Show() { if (border_widget_) border_widget_->Show(); GetWidget()->Show(); GetFocusManager()->SetFocusedView(GetInitiallyFocusedView()); } void BubbleDelegateView::StartFade(bool fade_in) { fade_animation_.reset(new ui::SlideAnimation(this)); fade_animation_->SetSlideDuration(kHideFadeDurationMS); fade_animation_->Reset(fade_in ? 0.0 : 1.0); if (fade_in) { original_opacity_ = 0; if (border_widget_) border_widget_->SetOpacity(original_opacity_); GetWidget()->SetOpacity(original_opacity_); Show(); fade_animation_->Show(); } else { original_opacity_ = 255; fade_animation_->Hide(); } } void BubbleDelegateView::ResetFade() { fade_animation_.reset(); if (border_widget_) border_widget_->SetOpacity(original_opacity_); GetWidget()->SetOpacity(original_opacity_); } bool BubbleDelegateView::AcceleratorPressed( const ui::Accelerator& accelerator) { if (!close_on_esc() || accelerator.key_code() != ui::VKEY_ESCAPE) return false; if (fade_animation_.get()) fade_animation_->Reset(); GetWidget()->Close(); return true; } void BubbleDelegateView::AnimationEnded(const ui::Animation* animation) { if (animation != fade_animation_.get()) return; bool closed = fade_animation_->GetCurrentValue() == 0; fade_animation_->Reset(); if (closed) GetWidget()->Close(); } void BubbleDelegateView::AnimationProgressed(const ui::Animation* animation) { if (animation != fade_animation_.get()) return; DCHECK(fade_animation_->is_animating()); unsigned char opacity = fade_animation_->GetCurrentValue() * 255; #if defined(OS_WIN) && !defined(USE_AURA) // Explicitly set the content Widget's layered style and set transparency via // SetLayeredWindowAttributes. This is done because initializing the Widget as // transparent and setting opacity via UpdateLayeredWindow doesn't support // hosting child native Windows controls. const HWND hwnd = GetWidget()->GetNativeView(); const DWORD style = GetWindowLong(hwnd, GWL_EXSTYLE); if ((opacity == 255) == !!(style & WS_EX_LAYERED)) SetWindowLong(hwnd, GWL_EXSTYLE, style ^ WS_EX_LAYERED); SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA); // Update the border widget's opacity. border_widget_->SetOpacity(opacity); border_widget_->non_client_view()->SchedulePaint(); #endif GetWidget()->SetOpacity(opacity); SchedulePaint(); } void BubbleDelegateView::Init() {} void BubbleDelegateView::SizeToContents() { #if defined(OS_WIN) && !defined(USE_AURA) border_widget_->SetBounds(GetBubbleBounds()); GetWidget()->SetBounds(GetBubbleClientBounds()); #else GetWidget()->SetBounds(GetBubbleBounds()); #endif } BubbleFrameView* BubbleDelegateView::GetBubbleFrameView() const { const Widget* widget = border_widget_ ? border_widget_ : GetWidget(); return static_cast<BubbleFrameView*>(widget->non_client_view()->frame_view()); } gfx::Rect BubbleDelegateView::GetBubbleBounds() { // The argument rect has its origin at the bubble's arrow anchor point; // its size is the preferred size of the bubble's client view (this view). return GetBubbleFrameView()->GetWindowBoundsForClientBounds( gfx::Rect(GetAnchorPoint(), GetPreferredSize())); } #if defined(OS_WIN) && !defined(USE_AURA) gfx::Rect BubbleDelegateView::GetBubbleClientBounds() const { gfx::Rect client_bounds(GetBubbleFrameView()->GetBoundsForClientView()); client_bounds.Offset(border_widget_->GetWindowScreenBounds().origin()); return client_bounds; } #endif } // namespace views <commit_msg>Fix BubbleDelegateView call to DisableInactiveRendering. Currently, when bubbles pop up, Chrome renders as inactive/'unfocused'. Call DisableInactiveRendering on Widget::Show rather than Widget construction.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/bubble/bubble_delegate.h" #include "ui/base/animation/slide_animation.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/widget/widget.h" // The duration of the fade animation in milliseconds. static const int kHideFadeDurationMS = 200; namespace views { namespace { // Create a widget to host the bubble. Widget* CreateBubbleWidget(BubbleDelegateView* bubble, Widget* parent) { Widget* bubble_widget = new Widget(); Widget::InitParams bubble_params(Widget::InitParams::TYPE_BUBBLE); bubble_params.delegate = bubble; bubble_params.transparent = true; bubble_params.parent_widget = parent; #if defined(OS_WIN) && !defined(USE_AURA) bubble_params.type = Widget::InitParams::TYPE_WINDOW_FRAMELESS; bubble_params.transparent = false; #endif bubble_widget->Init(bubble_params); return bubble_widget; } #if defined(OS_WIN) && !defined(USE_AURA) // The border widget's delegate, needed for transparent Windows native controls. // TODO(msw): Remove this when Windows native controls are no longer needed. class VIEWS_EXPORT BubbleBorderDelegateView : public WidgetDelegateView { public: explicit BubbleBorderDelegateView(BubbleDelegateView* bubble) : bubble_(bubble) {} virtual ~BubbleBorderDelegateView() {} // WidgetDelegateView overrides: virtual bool CanActivate() const OVERRIDE; virtual NonClientFrameView* CreateNonClientFrameView() OVERRIDE; private: BubbleDelegateView* bubble_; DISALLOW_COPY_AND_ASSIGN(BubbleBorderDelegateView); }; bool BubbleBorderDelegateView::CanActivate() const { return false; } NonClientFrameView* BubbleBorderDelegateView::CreateNonClientFrameView() { return bubble_->CreateNonClientFrameView(); } // Create a widget to host the bubble's border. Widget* CreateBorderWidget(BubbleDelegateView* bubble, Widget* parent) { Widget* border_widget = new Widget(); Widget::InitParams border_params(Widget::InitParams::TYPE_BUBBLE); border_params.delegate = new BubbleBorderDelegateView(bubble); border_params.transparent = true; border_params.parent_widget = parent; if (!border_params.parent_widget) border_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; border_widget->Init(border_params); return border_widget; } #endif } // namespace BubbleDelegateView::BubbleDelegateView() : close_on_esc_(true), close_on_deactivate_(true), allow_bubble_offscreen_(false), anchor_view_(NULL), arrow_location_(BubbleBorder::TOP_LEFT), color_(SK_ColorWHITE), border_widget_(NULL), use_focusless_(false) { set_background(views::Background::CreateSolidBackground(color_)); AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, 0)); } BubbleDelegateView::BubbleDelegateView( View* anchor_view, BubbleBorder::ArrowLocation arrow_location, const SkColor& color) : close_on_esc_(true), close_on_deactivate_(true), allow_bubble_offscreen_(false), anchor_view_(anchor_view), arrow_location_(arrow_location), color_(color), original_opacity_(255), border_widget_(NULL), use_focusless_(false) { set_background(views::Background::CreateSolidBackground(color_)); AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, 0)); } BubbleDelegateView::~BubbleDelegateView() { if (border_widget_) border_widget_->Close(); } // static Widget* BubbleDelegateView::CreateBubble(BubbleDelegateView* bubble_delegate) { bubble_delegate->Init(); Widget* parent = bubble_delegate->anchor_view() ? bubble_delegate->anchor_view()->GetWidget() : NULL; Widget* bubble_widget = CreateBubbleWidget(bubble_delegate, parent); #if defined(OS_WIN) && !defined(USE_AURA) // First set the contents view to initialize view bounds for widget sizing. bubble_widget->SetContentsView(bubble_delegate->GetContentsView()); bubble_delegate->border_widget_ = CreateBorderWidget(bubble_delegate, parent); #endif bubble_delegate->SizeToContents(); bubble_widget->AddObserver(bubble_delegate); return bubble_widget; } View* BubbleDelegateView::GetInitiallyFocusedView() { return this; } BubbleDelegateView* BubbleDelegateView::AsBubbleDelegate() { return this; } View* BubbleDelegateView::GetContentsView() { return this; } NonClientFrameView* BubbleDelegateView::CreateNonClientFrameView() { return new BubbleFrameView(GetArrowLocation(), GetPreferredSize(), GetColor(), allow_bubble_offscreen_); } void BubbleDelegateView::OnWidgetActivationChanged(Widget* widget, bool active) { if (close_on_deactivate() && widget == GetWidget() && !active) { GetWidget()->RemoveObserver(this); GetWidget()->Close(); } } gfx::Point BubbleDelegateView::GetAnchorPoint() { if (!anchor_view()) return gfx::Point(); BubbleBorder::ArrowLocation location = GetArrowLocation(); gfx::Point anchor(anchor_view()->bounds().CenterPoint()); // By default, pick the middle of |anchor_view_|'s edge opposite the arrow. if (BubbleBorder::is_arrow_on_horizontal(location)) { anchor.SetPoint(anchor_view()->width() / 2, BubbleBorder::is_arrow_on_top(location) ? anchor_view()->height() : 0); } else if (BubbleBorder::has_arrow(location)) { anchor.SetPoint( BubbleBorder::is_arrow_on_left(location) ? anchor_view()->width() : 0, anchor_view_->height() / 2); } View::ConvertPointToScreen(anchor_view(), &anchor); return anchor; } BubbleBorder::ArrowLocation BubbleDelegateView::GetArrowLocation() const { return arrow_location_; } SkColor BubbleDelegateView::GetColor() const { return color_; } void BubbleDelegateView::Show() { if (border_widget_) border_widget_->Show(); GetWidget()->Show(); GetFocusManager()->SetFocusedView(GetInitiallyFocusedView()); if (anchor_view() && anchor_view()->GetWidget() && anchor_view()->GetWidget()->GetTopLevelWidget()) anchor_view()->GetWidget()->GetTopLevelWidget()->DisableInactiveRendering(); } void BubbleDelegateView::StartFade(bool fade_in) { fade_animation_.reset(new ui::SlideAnimation(this)); fade_animation_->SetSlideDuration(kHideFadeDurationMS); fade_animation_->Reset(fade_in ? 0.0 : 1.0); if (fade_in) { original_opacity_ = 0; if (border_widget_) border_widget_->SetOpacity(original_opacity_); GetWidget()->SetOpacity(original_opacity_); Show(); fade_animation_->Show(); } else { original_opacity_ = 255; fade_animation_->Hide(); } } void BubbleDelegateView::ResetFade() { fade_animation_.reset(); if (border_widget_) border_widget_->SetOpacity(original_opacity_); GetWidget()->SetOpacity(original_opacity_); } bool BubbleDelegateView::AcceleratorPressed( const ui::Accelerator& accelerator) { if (!close_on_esc() || accelerator.key_code() != ui::VKEY_ESCAPE) return false; if (fade_animation_.get()) fade_animation_->Reset(); GetWidget()->Close(); return true; } void BubbleDelegateView::AnimationEnded(const ui::Animation* animation) { if (animation != fade_animation_.get()) return; bool closed = fade_animation_->GetCurrentValue() == 0; fade_animation_->Reset(); if (closed) GetWidget()->Close(); } void BubbleDelegateView::AnimationProgressed(const ui::Animation* animation) { if (animation != fade_animation_.get()) return; DCHECK(fade_animation_->is_animating()); unsigned char opacity = fade_animation_->GetCurrentValue() * 255; #if defined(OS_WIN) && !defined(USE_AURA) // Explicitly set the content Widget's layered style and set transparency via // SetLayeredWindowAttributes. This is done because initializing the Widget as // transparent and setting opacity via UpdateLayeredWindow doesn't support // hosting child native Windows controls. const HWND hwnd = GetWidget()->GetNativeView(); const DWORD style = GetWindowLong(hwnd, GWL_EXSTYLE); if ((opacity == 255) == !!(style & WS_EX_LAYERED)) SetWindowLong(hwnd, GWL_EXSTYLE, style ^ WS_EX_LAYERED); SetLayeredWindowAttributes(hwnd, 0, opacity, LWA_ALPHA); // Update the border widget's opacity. border_widget_->SetOpacity(opacity); border_widget_->non_client_view()->SchedulePaint(); #endif GetWidget()->SetOpacity(opacity); SchedulePaint(); } void BubbleDelegateView::Init() {} void BubbleDelegateView::SizeToContents() { #if defined(OS_WIN) && !defined(USE_AURA) border_widget_->SetBounds(GetBubbleBounds()); GetWidget()->SetBounds(GetBubbleClientBounds()); #else GetWidget()->SetBounds(GetBubbleBounds()); #endif } BubbleFrameView* BubbleDelegateView::GetBubbleFrameView() const { const Widget* widget = border_widget_ ? border_widget_ : GetWidget(); return static_cast<BubbleFrameView*>(widget->non_client_view()->frame_view()); } gfx::Rect BubbleDelegateView::GetBubbleBounds() { // The argument rect has its origin at the bubble's arrow anchor point; // its size is the preferred size of the bubble's client view (this view). return GetBubbleFrameView()->GetWindowBoundsForClientBounds( gfx::Rect(GetAnchorPoint(), GetPreferredSize())); } #if defined(OS_WIN) && !defined(USE_AURA) gfx::Rect BubbleDelegateView::GetBubbleClientBounds() const { gfx::Rect client_bounds(GetBubbleFrameView()->GetBoundsForClientView()); client_bounds.Offset(border_widget_->GetWindowScreenBounds().origin()); return client_bounds; } #endif } // namespace views <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2013 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> # include <QDoubleValidator> # include <QLocale> # include <QMessageBox> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoDrawStyle.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoShapeHints.h> #endif #include <BRep_Tool.hxx> #include <gp_Pnt.hxx> #include <Precision.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx> #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Vertex.hxx> #include <algorithm> #include "ui_TaskSketcherValidation.h" #include "TaskSketcherValidation.h" #include <Mod/Sketcher/App/SketchObject.h> #include <Mod/Part/App/Geometry.h> #include <App/Document.h> #include <Gui/TaskView/TaskView.h> #include <Gui/Application.h> #include <Gui/ViewProvider.h> #include <Gui/WaitCursor.h> #include <Gui/Inventor/MarkerBitmaps.h> using namespace SketcherGui; using namespace Gui::TaskView; /* TRANSLATOR SketcherGui::SketcherValidation */ SketcherValidation::SketcherValidation(Sketcher::SketchObject* Obj, QWidget* parent) : QWidget(parent), ui(new Ui_TaskSketcherValidation()), sketch(Obj), sketchAnalyser(Obj), coincidenceRoot(0) { ui->setupUi(this); ui->fixButton->setEnabled(false); ui->fixConstraint->setEnabled(false); ui->swapReversed->setEnabled(false); ui->checkBoxIgnoreConstruction->setEnabled(true); double tolerances[8] = { Precision::Confusion() / 100, Precision::Confusion() / 10, Precision::Confusion(), Precision::Confusion() * 10, Precision::Confusion() * 100, Precision::Confusion() * 1000, Precision::Confusion() * 10000, Precision::Confusion() * 100000 }; for (int i=0; i<8; i++) { ui->comboBoxTolerance->addItem(QLocale::system().toString(tolerances[i]), QVariant(tolerances[i])); } ui->comboBoxTolerance->setCurrentIndex(5); ui->comboBoxTolerance->setEditable(true); ui->comboBoxTolerance->setValidator(new QDoubleValidator(0,10,10,this)); } SketcherValidation::~SketcherValidation() { hidePoints(); } void SketcherValidation::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } QWidget::changeEvent(e); } void SketcherValidation::on_findButton_clicked() { double prec = Precision::Confusion(); bool ok; double conv; conv = QLocale::system().toDouble(ui->comboBoxTolerance->currentText(),&ok); if(ok) { prec = conv; } else { QVariant v = ui->comboBoxTolerance->itemData(ui->comboBoxTolerance->currentIndex()); if (v.isValid()) { prec = v.toDouble(); } } sketchAnalyser.detectMissingPointOnPointConstraints(prec,!ui->checkBoxIgnoreConstruction->isChecked()); std::vector<Sketcher::ConstraintIds> & vertexConstraints = sketchAnalyser.getMissingPointOnPointConstraints(); std::vector<Base::Vector3d> points; points.reserve(vertexConstraints.size()); for (auto vc : vertexConstraints) { points.push_back(vc.v); } hidePoints(); if (vertexConstraints.empty()) { QMessageBox::information(this, tr("No missing coincidences"), tr("No missing coincidences found")); ui->fixButton->setEnabled(false); } else { showPoints(points); QMessageBox::warning(this, tr("Missing coincidences"), tr("%1 missing coincidences found").arg(vertexConstraints.size())); ui->fixButton->setEnabled(true); } } void SketcherValidation::on_fixButton_clicked() { // undo command open App::Document* doc = sketch->getDocument(); doc->openTransaction("add coincident constraint"); sketchAnalyser.makeMissingPointOnPointCoincident(); ui->fixButton->setEnabled(false); hidePoints(); // finish the transaction and update Gui::WaitCursor wc; doc->commitTransaction(); doc->recompute(); } void SketcherValidation::on_highlightButton_clicked() { std::vector<Base::Vector3d> points; points = sketchAnalyser.getOpenVertices(); hidePoints(); if (!points.empty()) showPoints(points); } void SketcherValidation::on_findConstraint_clicked() { if (sketch->evaluateConstraints()) { QMessageBox::information(this, tr("No invalid constraints"), tr("No invalid constraints found")); ui->fixConstraint->setEnabled(false); } else { QMessageBox::warning(this, tr("Invalid constraints"), tr("Invalid constraints found")); ui->fixConstraint->setEnabled(true); } } void SketcherValidation::on_fixConstraint_clicked() { sketch->validateConstraints(); ui->fixConstraint->setEnabled(false); } void SketcherValidation::on_findReversed_clicked() { std::vector<Base::Vector3d> points; const std::vector<Part::Geometry *>& geom = sketch->getExternalGeometry(); for (std::size_t i=0; i<geom.size(); i++) { Part::Geometry* g = geom[i]; //only arcs of circles need to be repaired. Arcs of ellipse were so broken there should be nothing to repair from. if (g->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *segm = static_cast<const Part::GeomArcOfCircle*>(g); if (segm->isReversed()) { points.push_back(segm->getStartPoint(/*emulateCCW=*/true)); points.push_back(segm->getEndPoint(/*emulateCCW=*/true)); } } } hidePoints(); if(points.size()>0){ int nc = sketch->port_reversedExternalArcs(/*justAnalyze=*/true); showPoints(points); if(nc>0){ QMessageBox::warning(this, tr("Reversed external geometry"), tr("%1 reversed external-geometry arcs were found. Their endpoints are" " encircled in 3d view.\n\n" "%2 constraints are linking to the endpoints. The constraints have" " been listed in Report view (menu View -> Panels -> Report view).\n\n" "Click \"Swap endpoints in constraints\" button to reassign endpoints." " Do this only once to sketches created in FreeCAD older than v0.15.???" ).arg(points.size()/2).arg(nc) ); ui->swapReversed->setEnabled(true); } else { QMessageBox::warning(this, tr("Reversed external geometry"), tr("%1 reversed external-geometry arcs were found. Their endpoints are " "encircled in 3d view.\n\n" "However, no constraints linking to the endpoints were found.").arg(points.size()/2)); ui->swapReversed->setEnabled(false); } } else { QMessageBox::warning(this, tr("Reversed external geometry"), tr("No reversed external-geometry arcs were found.")); } } void SketcherValidation::on_swapReversed_clicked() { App::Document* doc = sketch->getDocument(); doc->openTransaction("Sketch porting"); int n = sketch->port_reversedExternalArcs(/*justAnalyze=*/false); QMessageBox::warning(this, tr("Reversed external geometry"), tr("%1 changes were made to constraints linking to endpoints of reversed arcs.").arg(n)); hidePoints(); ui->swapReversed->setEnabled(false); doc->commitTransaction(); } void SketcherValidation::on_orientLockEnable_clicked() { App::Document* doc = sketch->getDocument(); doc->openTransaction("Constraint orientation lock"); int n = sketch->changeConstraintsLocking(/*bLock=*/true); QMessageBox::warning(this, tr("Constraint orientation locking"), tr("Orientation locking was enabled and recomputed for %1 constraints. The" " constraints have been listed in Report view (menu View -> Panels ->" " Report view).").arg(n)); doc->commitTransaction(); } void SketcherValidation::on_orientLockDisable_clicked() { App::Document* doc = sketch->getDocument(); doc->openTransaction("Constraint orientation unlock"); int n = sketch->changeConstraintsLocking(/*bLock=*/false); QMessageBox::warning(this, tr("Constraint orientation locking"), tr("Orientation locking was disabled for %1 constraints. The" " constraints have been listed in Report view (menu View -> Panels ->" " Report view). Note that for all future constraints, the locking still" " defaults to ON.").arg(n)); doc->commitTransaction(); } void SketcherValidation::on_delConstrExtr_clicked() { int reply; reply = QMessageBox::question(this, tr("Delete constraints to external geom."), tr("You are about to delete ALL constraints that deal with external geometry. This is useful to rescue a sketch with broken/changed links to external geometry. Are you sure you want to delete the constraints?"), QMessageBox::No|QMessageBox::Yes,QMessageBox::No); if(reply!=QMessageBox::Yes) return; App::Document* doc = sketch->getDocument(); doc->openTransaction("Delete constraints"); sketch->delConstraintsToExternal(); doc->commitTransaction(); QMessageBox::warning(this, tr("Delete constraints to external geom."), tr("All constraints that deal with external geometry were deleted.")); } void SketcherValidation::showPoints(const std::vector<Base::Vector3d>& pts) { SoCoordinate3 * coords = new SoCoordinate3(); SoDrawStyle * drawStyle = new SoDrawStyle(); drawStyle->pointSize = 6; SoPointSet* pcPoints = new SoPointSet(); coincidenceRoot = new SoGroup(); coincidenceRoot->addChild(drawStyle); SoSeparator* pointsep = new SoSeparator(); SoBaseColor * basecol = new SoBaseColor(); basecol->rgb.setValue(1.0f, 0.5f, 0.0f); pointsep->addChild(basecol); pointsep->addChild(coords); pointsep->addChild(pcPoints); coincidenceRoot->addChild(pointsep); // Draw markers SoBaseColor * markcol = new SoBaseColor(); markcol->rgb.setValue(1.0f, 1.0f, 0.0f); SoMarkerSet* marker = new SoMarkerSet(); marker->markerIndex=Gui::Inventor::MarkerBitmaps::getMarkerIndex("PLUS", App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")->GetInt("MarkerSize", 9)); pointsep->addChild(markcol); pointsep->addChild(marker); int pts_size = (int)pts.size(); coords->point.setNum(pts_size); SbVec3f* c = coords->point.startEditing(); for (int i = 0; i < pts_size; i++) { const Base::Vector3d& v = pts[i]; c[i].setValue((float)v.x,(float)v.y,(float)v.z); } coords->point.finishEditing(); Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(sketch); vp->getRoot()->addChild(coincidenceRoot); } void SketcherValidation::hidePoints() { if (coincidenceRoot) { Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(sketch); vp->getRoot()->removeChild(coincidenceRoot); coincidenceRoot = 0; } } // ----------------------------------------------- TaskSketcherValidation::TaskSketcherValidation(Sketcher::SketchObject* Obj) { QWidget* widget = new SketcherValidation(Obj); Gui::TaskView::TaskBox* taskbox = new Gui::TaskView::TaskBox( QPixmap(), widget->windowTitle(), true, 0); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } TaskSketcherValidation::~TaskSketcherValidation() { } #include "moc_TaskSketcherValidation.cpp" <commit_msg>Crowdin: Sketcher/Gui/TaskSketcherValidation.cpp fixed obsolete punct.<commit_after>/*************************************************************************** * Copyright (c) 2013 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> # include <QDoubleValidator> # include <QLocale> # include <QMessageBox> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoDrawStyle.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoShapeHints.h> #endif #include <BRep_Tool.hxx> #include <gp_Pnt.hxx> #include <Precision.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx> #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Vertex.hxx> #include <algorithm> #include "ui_TaskSketcherValidation.h" #include "TaskSketcherValidation.h" #include <Mod/Sketcher/App/SketchObject.h> #include <Mod/Part/App/Geometry.h> #include <App/Document.h> #include <Gui/TaskView/TaskView.h> #include <Gui/Application.h> #include <Gui/ViewProvider.h> #include <Gui/WaitCursor.h> #include <Gui/Inventor/MarkerBitmaps.h> using namespace SketcherGui; using namespace Gui::TaskView; /* TRANSLATOR SketcherGui::SketcherValidation */ SketcherValidation::SketcherValidation(Sketcher::SketchObject* Obj, QWidget* parent) : QWidget(parent), ui(new Ui_TaskSketcherValidation()), sketch(Obj), sketchAnalyser(Obj), coincidenceRoot(0) { ui->setupUi(this); ui->fixButton->setEnabled(false); ui->fixConstraint->setEnabled(false); ui->swapReversed->setEnabled(false); ui->checkBoxIgnoreConstruction->setEnabled(true); double tolerances[8] = { Precision::Confusion() / 100, Precision::Confusion() / 10, Precision::Confusion(), Precision::Confusion() * 10, Precision::Confusion() * 100, Precision::Confusion() * 1000, Precision::Confusion() * 10000, Precision::Confusion() * 100000 }; for (int i=0; i<8; i++) { ui->comboBoxTolerance->addItem(QLocale::system().toString(tolerances[i]), QVariant(tolerances[i])); } ui->comboBoxTolerance->setCurrentIndex(5); ui->comboBoxTolerance->setEditable(true); ui->comboBoxTolerance->setValidator(new QDoubleValidator(0,10,10,this)); } SketcherValidation::~SketcherValidation() { hidePoints(); } void SketcherValidation::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } QWidget::changeEvent(e); } void SketcherValidation::on_findButton_clicked() { double prec = Precision::Confusion(); bool ok; double conv; conv = QLocale::system().toDouble(ui->comboBoxTolerance->currentText(),&ok); if(ok) { prec = conv; } else { QVariant v = ui->comboBoxTolerance->itemData(ui->comboBoxTolerance->currentIndex()); if (v.isValid()) { prec = v.toDouble(); } } sketchAnalyser.detectMissingPointOnPointConstraints(prec,!ui->checkBoxIgnoreConstruction->isChecked()); std::vector<Sketcher::ConstraintIds> & vertexConstraints = sketchAnalyser.getMissingPointOnPointConstraints(); std::vector<Base::Vector3d> points; points.reserve(vertexConstraints.size()); for (auto vc : vertexConstraints) { points.push_back(vc.v); } hidePoints(); if (vertexConstraints.empty()) { QMessageBox::information(this, tr("No missing coincidences"), tr("No missing coincidences found")); ui->fixButton->setEnabled(false); } else { showPoints(points); QMessageBox::warning(this, tr("Missing coincidences"), tr("%1 missing coincidences found").arg(vertexConstraints.size())); ui->fixButton->setEnabled(true); } } void SketcherValidation::on_fixButton_clicked() { // undo command open App::Document* doc = sketch->getDocument(); doc->openTransaction("add coincident constraint"); sketchAnalyser.makeMissingPointOnPointCoincident(); ui->fixButton->setEnabled(false); hidePoints(); // finish the transaction and update Gui::WaitCursor wc; doc->commitTransaction(); doc->recompute(); } void SketcherValidation::on_highlightButton_clicked() { std::vector<Base::Vector3d> points; points = sketchAnalyser.getOpenVertices(); hidePoints(); if (!points.empty()) showPoints(points); } void SketcherValidation::on_findConstraint_clicked() { if (sketch->evaluateConstraints()) { QMessageBox::information(this, tr("No invalid constraints"), tr("No invalid constraints found")); ui->fixConstraint->setEnabled(false); } else { QMessageBox::warning(this, tr("Invalid constraints"), tr("Invalid constraints found")); ui->fixConstraint->setEnabled(true); } } void SketcherValidation::on_fixConstraint_clicked() { sketch->validateConstraints(); ui->fixConstraint->setEnabled(false); } void SketcherValidation::on_findReversed_clicked() { std::vector<Base::Vector3d> points; const std::vector<Part::Geometry *>& geom = sketch->getExternalGeometry(); for (std::size_t i=0; i<geom.size(); i++) { Part::Geometry* g = geom[i]; //only arcs of circles need to be repaired. Arcs of ellipse were so broken there should be nothing to repair from. if (g->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *segm = static_cast<const Part::GeomArcOfCircle*>(g); if (segm->isReversed()) { points.push_back(segm->getStartPoint(/*emulateCCW=*/true)); points.push_back(segm->getEndPoint(/*emulateCCW=*/true)); } } } hidePoints(); if(points.size()>0){ int nc = sketch->port_reversedExternalArcs(/*justAnalyze=*/true); showPoints(points); if(nc>0){ QMessageBox::warning(this, tr("Reversed external geometry"), tr("%1 reversed external-geometry arcs were found. Their endpoints are" " encircled in 3d view.\n\n" "%2 constraints are linking to the endpoints. The constraints have" " been listed in Report view (menu View -> Panels -> Report view).\n\n" "Click \"Swap endpoints in constraints\" button to reassign endpoints." " Do this only once to sketches created in FreeCAD older than v0.15" ).arg(points.size()/2).arg(nc) ); ui->swapReversed->setEnabled(true); } else { QMessageBox::warning(this, tr("Reversed external geometry"), tr("%1 reversed external-geometry arcs were found. Their endpoints are " "encircled in 3d view.\n\n" "However, no constraints linking to the endpoints were found.").arg(points.size()/2)); ui->swapReversed->setEnabled(false); } } else { QMessageBox::warning(this, tr("Reversed external geometry"), tr("No reversed external-geometry arcs were found.")); } } void SketcherValidation::on_swapReversed_clicked() { App::Document* doc = sketch->getDocument(); doc->openTransaction("Sketch porting"); int n = sketch->port_reversedExternalArcs(/*justAnalyze=*/false); QMessageBox::warning(this, tr("Reversed external geometry"), tr("%1 changes were made to constraints linking to endpoints of reversed arcs.").arg(n)); hidePoints(); ui->swapReversed->setEnabled(false); doc->commitTransaction(); } void SketcherValidation::on_orientLockEnable_clicked() { App::Document* doc = sketch->getDocument(); doc->openTransaction("Constraint orientation lock"); int n = sketch->changeConstraintsLocking(/*bLock=*/true); QMessageBox::warning(this, tr("Constraint orientation locking"), tr("Orientation locking was enabled and recomputed for %1 constraints. The" " constraints have been listed in Report view (menu View -> Panels ->" " Report view).").arg(n)); doc->commitTransaction(); } void SketcherValidation::on_orientLockDisable_clicked() { App::Document* doc = sketch->getDocument(); doc->openTransaction("Constraint orientation unlock"); int n = sketch->changeConstraintsLocking(/*bLock=*/false); QMessageBox::warning(this, tr("Constraint orientation locking"), tr("Orientation locking was disabled for %1 constraints. The" " constraints have been listed in Report view (menu View -> Panels ->" " Report view). Note that for all future constraints, the locking still" " defaults to ON.").arg(n)); doc->commitTransaction(); } void SketcherValidation::on_delConstrExtr_clicked() { int reply; reply = QMessageBox::question(this, tr("Delete constraints to external geom."), tr("You are about to delete ALL constraints that deal with external geometry. This is useful to rescue a sketch with broken/changed links to external geometry. Are you sure you want to delete the constraints?"), QMessageBox::No|QMessageBox::Yes,QMessageBox::No); if(reply!=QMessageBox::Yes) return; App::Document* doc = sketch->getDocument(); doc->openTransaction("Delete constraints"); sketch->delConstraintsToExternal(); doc->commitTransaction(); QMessageBox::warning(this, tr("Delete constraints to external geom."), tr("All constraints that deal with external geometry were deleted.")); } void SketcherValidation::showPoints(const std::vector<Base::Vector3d>& pts) { SoCoordinate3 * coords = new SoCoordinate3(); SoDrawStyle * drawStyle = new SoDrawStyle(); drawStyle->pointSize = 6; SoPointSet* pcPoints = new SoPointSet(); coincidenceRoot = new SoGroup(); coincidenceRoot->addChild(drawStyle); SoSeparator* pointsep = new SoSeparator(); SoBaseColor * basecol = new SoBaseColor(); basecol->rgb.setValue(1.0f, 0.5f, 0.0f); pointsep->addChild(basecol); pointsep->addChild(coords); pointsep->addChild(pcPoints); coincidenceRoot->addChild(pointsep); // Draw markers SoBaseColor * markcol = new SoBaseColor(); markcol->rgb.setValue(1.0f, 1.0f, 0.0f); SoMarkerSet* marker = new SoMarkerSet(); marker->markerIndex=Gui::Inventor::MarkerBitmaps::getMarkerIndex("PLUS", App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")->GetInt("MarkerSize", 9)); pointsep->addChild(markcol); pointsep->addChild(marker); int pts_size = (int)pts.size(); coords->point.setNum(pts_size); SbVec3f* c = coords->point.startEditing(); for (int i = 0; i < pts_size; i++) { const Base::Vector3d& v = pts[i]; c[i].setValue((float)v.x,(float)v.y,(float)v.z); } coords->point.finishEditing(); Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(sketch); vp->getRoot()->addChild(coincidenceRoot); } void SketcherValidation::hidePoints() { if (coincidenceRoot) { Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(sketch); vp->getRoot()->removeChild(coincidenceRoot); coincidenceRoot = 0; } } // ----------------------------------------------- TaskSketcherValidation::TaskSketcherValidation(Sketcher::SketchObject* Obj) { QWidget* widget = new SketcherValidation(Obj); Gui::TaskView::TaskBox* taskbox = new Gui::TaskView::TaskBox( QPixmap(), widget->windowTitle(), true, 0); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } TaskSketcherValidation::~TaskSketcherValidation() { } #include "moc_TaskSketcherValidation.cpp" <|endoftext|>
<commit_before>#include "ngraph.h" #include <PCU.h> #include "agi.h" namespace agi { void writePoints(Ngraph* g,FILE* f) { fprintf(f,"<Points>\n"); fprintf(f,"<DataArray NumberOfComponents=\"3\""); fprintf(f," type=\"Float64\" format=\"ascii\" Name=\"Points\">\n"); //Write the position of each vertex agi::GraphVertex* v; agi::VertexIterator* vitr = g->begin(); while ((v=g->iterate(vitr))) { const coord_t& c = g->coord(v); fprintf(f," %f %f %f\n",c[0],c[1],c[2]); } //Gather the coordinates of ghost vertices coord_t* ghost_cs = new coord_t[g->numGhostVtxs()]; GhostIterator* g_itr = g->beginGhosts(); PCU_Comm_Begin(); while ((v = g->iterate(g_itr))) { part_t owner = g->owner(v); gid_t gid = g->globalID(v); PCU_COMM_PACK(owner,gid); } PCU_Comm_Send(); std::vector<std::pair<gid_t,part_t> > requests; while (PCU_Comm_Receive()) { gid_t gid; PCU_COMM_UNPACK(gid); requests.push_back(std::make_pair(gid,PCU_Comm_Sender())); } PCU_Comm_Begin(); for (size_t i=0;i<requests.size();i++) { agi::GraphVertex* my_v = g->findGID(requests[i].first); double vals[3]; const coord_t& c = g->coord(my_v); for (int i=0;i<3;i++) { vals[i] = c[i]; } PCU_COMM_PACK(requests[i].second,requests[i].first); PCU_Comm_Pack(requests[i].second,vals,sizeof(double)*3); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t gid; PCU_COMM_UNPACK(gid); double vals[3]; PCU_Comm_Unpack(vals,sizeof(double)*3); agi::GraphVertex* my_v = g->findGID(gid); assert(g->owner(my_v)!=PCU_Comm_Self()); lid_t lid = g->localID(my_v)-g->numLocalVtxs(); for (int i=0;i<3;i++) ghost_cs[lid][i] = vals[i]; } //Write the position of each edge agi::GraphEdge* e; agi::EdgeIterator* eitr = g->begin(0); while ((e=g->iterate(eitr))) { coord_t c = {0,0,0}; agi::PinIterator* pitr = g->pins(e); int ghosts=0; while ((v = g->iterate(pitr))) { if (g->owner(v)!=PCU_Comm_Self()){ lid_t lid = g->localID(v)-g->numLocalVtxs(); for (int i=0;i<3;i++) c[i]+=ghost_cs[lid][i]; } else { const coord_t& cv = g->coord(v); c[0]+=cv[0];c[1]+=cv[1];c[2]+=cv[2]; } } g->destroy(pitr); lid_t deg = g->degree(e)-ghosts; for (int i=0;i<3;i++) { c[i]/=deg; } fprintf(f," %f %f %f\n",c[0],c[1],c[2]); } g->destroy(eitr); fprintf(f,"\n</DataArray>\n</Points>\n"); } void writeCells(Ngraph* g, FILE* f) { fprintf(f,"<Cells>\n"); fprintf(f,"<DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"); GraphEdge* e; EdgeIterator* eitr = g->begin(0); while ((e = g->iterate(eitr))) { GraphVertex* v; PinIterator* pitr = g->pins(e); while ((v = g->iterate(pitr))) { if (g->owner(v)==PCU_Comm_Self()) fprintf(f,"%ld %ld\n",g->localID(e)+g->numLocalVtxs(),g->localID(v)); } } g->destroy(eitr); int off=0; fprintf(f,"\n</DataArray>\n<DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"); eitr = g->begin(0); while ((e = g->iterate(eitr))) { GraphVertex* v; PinIterator* pitr = g->pins(e); while ((v = g->iterate(pitr))) { if (g->owner(v)==PCU_Comm_Self()) fprintf(f," %d\n",off+=2); } } g->destroy(eitr); fprintf(f,"\n</DataArray>\n<DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"); eitr = g->begin(0); while ((e = g->iterate(eitr))) { GraphVertex* v; PinIterator* pitr = g->pins(e); while ((v = g->iterate(pitr))) { if (g->owner(v)==PCU_Comm_Self()) fprintf(f," %d\n",3); } } g->destroy(eitr); fprintf(f,"\n</DataArray>\n</Cells>\n"); } void writePointData(Ngraph* g, FILE* f, GraphTag* tag,etype t) { fprintf(f,"<PointData>\n"); fprintf(f,"<DataArray type=\"Int32\" Name=\"Part\" NumberOfComponents=\"1\" format=\"ascii\">\n"); agi::GraphVertex* v; agi::VertexIterator* vitr = g->begin(); while ((v=g->iterate(vitr))) { fprintf(f,"%d\n",PCU_Comm_Self()); } agi::GraphEdge* e; agi::EdgeIterator* eitr = g->begin(0); while ((e=g->iterate(eitr))) { fprintf(f,"%d\n",PCU_Comm_Self()); } g->destroy(eitr); fprintf(f,"</DataArray>\n"); fprintf(f,"<DataArray type=\"Int32\" Name=\"VorE\" NumberOfComponents=\"1\" format=\"ascii\">\n"); vitr = g->begin(); while ((v=g->iterate(vitr))) { fprintf(f,"0\n"); } eitr = g->begin(0); while ((e=g->iterate(eitr))) { fprintf(f,"1\n"); } g->destroy(eitr); fprintf(f,"</DataArray>\n"); if (tag!=NULL&&t!=NO_TYPE) { fprintf(f,"<DataArray type=\"Int32\" Name=\"Tag\" NumberOfComponents=\"1\" format=\"ascii\">\n"); agi::GraphVertex* v; agi::VertexIterator* vitr = g->begin(); while ((v=g->iterate(vitr))) { if (t==VTX_TYPE) fprintf(f,"%d\n",g->getIntTag(tag,v)); else fprintf(f,"-1\n"); } agi::GraphEdge* e; agi::EdgeIterator* eitr = g->begin(0); while ((e=g->iterate(eitr))) { if (t==0) fprintf(f,"%d\n",g->getIntTag(tag,e)); else fprintf(f,"-1\n"); } g->destroy(eitr); fprintf(f,"</DataArray>\n"); } fprintf(f,"</PointData>\n"); } gid_t getNumCells(Ngraph* g) { gid_t total = 0; EdgeIterator* eitr = g->begin(0); GraphEdge* edge; while ((edge = g->iterate(eitr))) { PinIterator* pitr = g->pins(edge); GraphVertex* v; while ((v = g->iterate(pitr))) { total+=(g->owner(v)==PCU_Comm_Self()); } } return total; } void writeVTK(Ngraph* g, const char* prefix,GraphTag* tag,etype t) { char filename[256]; sprintf(filename,"%s%d.vtu",prefix,PCU_Comm_Self()); FILE* f = fopen(filename,"w"); fprintf(f,"<VTKFile type=\"UnstructuredGrid\">\n"); fprintf(f,"<UnstructuredGrid>\n"); gid_t numCells = getNumCells(g); fprintf(f,"<Piece NumberOfPoints=\"%ld\" NumberOfCells=\"%ld\">\n", g->numLocalVtxs()+g->numLocalEdges(),numCells); writePoints(g,f); writeCells(g,f); writePointData(g,f,tag,t); fprintf(f,"</Piece>\n"); fprintf(f,"</UnstructuredGrid>\n"); fprintf(f,"</VTKFile>\n"); fclose(f); } } <commit_msg>Fix memory leaks in vtk writing<commit_after>#include "ngraph.h" #include <PCU.h> #include "agi.h" namespace agi { void writePoints(Ngraph* g,FILE* f) { fprintf(f,"<Points>\n"); fprintf(f,"<DataArray NumberOfComponents=\"3\""); fprintf(f," type=\"Float64\" format=\"ascii\" Name=\"Points\">\n"); //Write the position of each vertex agi::GraphVertex* v; agi::VertexIterator* vitr = g->begin(); while ((v=g->iterate(vitr))) { const coord_t& c = g->coord(v); fprintf(f," %f %f %f\n",c[0],c[1],c[2]); } //Gather the coordinates of ghost vertices coord_t* ghost_cs = new coord_t[g->numGhostVtxs()]; GhostIterator* g_itr = g->beginGhosts(); PCU_Comm_Begin(); while ((v = g->iterate(g_itr))) { part_t owner = g->owner(v); gid_t gid = g->globalID(v); PCU_COMM_PACK(owner,gid); } PCU_Comm_Send(); std::vector<std::pair<gid_t,part_t> > requests; while (PCU_Comm_Receive()) { gid_t gid; PCU_COMM_UNPACK(gid); requests.push_back(std::make_pair(gid,PCU_Comm_Sender())); } PCU_Comm_Begin(); for (size_t i=0;i<requests.size();i++) { agi::GraphVertex* my_v = g->findGID(requests[i].first); double vals[3]; const coord_t& c = g->coord(my_v); for (int i=0;i<3;i++) { vals[i] = c[i]; } PCU_COMM_PACK(requests[i].second,requests[i].first); PCU_Comm_Pack(requests[i].second,vals,sizeof(double)*3); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t gid; PCU_COMM_UNPACK(gid); double vals[3]; PCU_Comm_Unpack(vals,sizeof(double)*3); agi::GraphVertex* my_v = g->findGID(gid); assert(g->owner(my_v)!=PCU_Comm_Self()); lid_t lid = g->localID(my_v)-g->numLocalVtxs(); for (int i=0;i<3;i++) ghost_cs[lid][i] = vals[i]; } //Write the position of each edge agi::GraphEdge* e; agi::EdgeIterator* eitr = g->begin(0); while ((e=g->iterate(eitr))) { coord_t c = {0,0,0}; agi::PinIterator* pitr = g->pins(e); int ghosts=0; while ((v = g->iterate(pitr))) { if (g->owner(v)!=PCU_Comm_Self()){ lid_t lid = g->localID(v)-g->numLocalVtxs(); for (int i=0;i<3;i++) c[i]+=ghost_cs[lid][i]; } else { const coord_t& cv = g->coord(v); c[0]+=cv[0];c[1]+=cv[1];c[2]+=cv[2]; } } g->destroy(pitr); lid_t deg = g->degree(e)-ghosts; for (int i=0;i<3;i++) { c[i]/=deg; } fprintf(f," %f %f %f\n",c[0],c[1],c[2]); } g->destroy(eitr); fprintf(f,"\n</DataArray>\n</Points>\n"); } void writeCells(Ngraph* g, FILE* f) { fprintf(f,"<Cells>\n"); fprintf(f,"<DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"); GraphEdge* e; EdgeIterator* eitr = g->begin(0); while ((e = g->iterate(eitr))) { GraphVertex* v; PinIterator* pitr = g->pins(e); while ((v = g->iterate(pitr))) { if (g->owner(v)==PCU_Comm_Self()) fprintf(f,"%ld %ld\n",g->localID(e)+g->numLocalVtxs(),g->localID(v)); } g->destroy(pitr); } g->destroy(eitr); int off=0; fprintf(f,"\n</DataArray>\n<DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"); eitr = g->begin(0); while ((e = g->iterate(eitr))) { GraphVertex* v; PinIterator* pitr = g->pins(e); while ((v = g->iterate(pitr))) { if (g->owner(v)==PCU_Comm_Self()) fprintf(f," %d\n",off+=2); } g->destroy(pitr); } g->destroy(eitr); fprintf(f,"\n</DataArray>\n<DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"); eitr = g->begin(0); while ((e = g->iterate(eitr))) { GraphVertex* v; PinIterator* pitr = g->pins(e); while ((v = g->iterate(pitr))) { if (g->owner(v)==PCU_Comm_Self()) fprintf(f," %d\n",3); } g->destroy(pitr); } g->destroy(eitr); fprintf(f,"\n</DataArray>\n</Cells>\n"); } void writePointData(Ngraph* g, FILE* f, GraphTag* tag,etype t) { fprintf(f,"<PointData>\n"); fprintf(f,"<DataArray type=\"Int32\" Name=\"Part\" NumberOfComponents=\"1\" format=\"ascii\">\n"); agi::GraphVertex* v; agi::VertexIterator* vitr = g->begin(); while ((v=g->iterate(vitr))) { fprintf(f,"%d\n",PCU_Comm_Self()); } agi::GraphEdge* e; agi::EdgeIterator* eitr = g->begin(0); while ((e=g->iterate(eitr))) { fprintf(f,"%d\n",PCU_Comm_Self()); } g->destroy(eitr); fprintf(f,"</DataArray>\n"); fprintf(f,"<DataArray type=\"Int32\" Name=\"VorE\" NumberOfComponents=\"1\" format=\"ascii\">\n"); vitr = g->begin(); while ((v=g->iterate(vitr))) { fprintf(f,"0\n"); } eitr = g->begin(0); while ((e=g->iterate(eitr))) { fprintf(f,"1\n"); } g->destroy(eitr); fprintf(f,"</DataArray>\n"); if (tag!=NULL&&t!=NO_TYPE) { fprintf(f,"<DataArray type=\"Int32\" Name=\"Tag\" NumberOfComponents=\"1\" format=\"ascii\">\n"); agi::GraphVertex* v; agi::VertexIterator* vitr = g->begin(); while ((v=g->iterate(vitr))) { if (t==VTX_TYPE) fprintf(f,"%d\n",g->getIntTag(tag,v)); else fprintf(f,"-1\n"); } agi::GraphEdge* e; agi::EdgeIterator* eitr = g->begin(0); while ((e=g->iterate(eitr))) { if (t==0) fprintf(f,"%d\n",g->getIntTag(tag,e)); else fprintf(f,"-1\n"); } g->destroy(eitr); fprintf(f,"</DataArray>\n"); } fprintf(f,"</PointData>\n"); } gid_t getNumCells(Ngraph* g) { gid_t total = 0; EdgeIterator* eitr = g->begin(0); GraphEdge* edge; while ((edge = g->iterate(eitr))) { PinIterator* pitr = g->pins(edge); GraphVertex* v; while ((v = g->iterate(pitr))) { total+=(g->owner(v)==PCU_Comm_Self()); } g->destroy(pitr); } g->destroy(eitr); return total; } void writeVTK(Ngraph* g, const char* prefix,GraphTag* tag,etype t) { char filename[256]; sprintf(filename,"%s%d.vtu",prefix,PCU_Comm_Self()); FILE* f = fopen(filename,"w"); fprintf(f,"<VTKFile type=\"UnstructuredGrid\">\n"); fprintf(f,"<UnstructuredGrid>\n"); gid_t numCells = getNumCells(g); fprintf(f,"<Piece NumberOfPoints=\"%ld\" NumberOfCells=\"%ld\">\n", g->numLocalVtxs()+g->numLocalEdges(),numCells); writePoints(g,f); writeCells(g,f); writePointData(g,f,tag,t); fprintf(f,"</Piece>\n"); fprintf(f,"</UnstructuredGrid>\n"); fprintf(f,"</VTKFile>\n"); fclose(f); } } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief NES Emulator ハンドラー @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "emu/log.h" #include "emu/nes/nes.h" #include "emu/nes/nesinput.h" #include "emu/nes/nesstate.h" #include "emu/nes/nes_pal.h" #include "chip/FAMIPAD.hpp" // #include "emu/nsf/nsfplay.hpp" extern "C" { uint8_t get_fami_pad(); uint16_t sci_length(void); char sci_getch(void); } namespace emu { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief NESエミュレーション・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class nesemu { static const int nes_width_ = 256; static const int nes_height_ = 240; static const int sample_rate_ = 22050; static const int sample_bits_ = 16; static const int audio_len_ = sample_rate_ / 60; uint16_t audio_buf_[audio_len_ + 16]; // emu::nsfplay nsfplay_; bool nesrom_; uint32_t delay_; nesinput_t inp_[2]; public: //-----------------------------------------------------------------// /*! @brief コンストラクタ */ //-----------------------------------------------------------------// nesemu() noexcept : nesrom_(false), delay_(120) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] オーディオをサポートしない場合「false」 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool start(bool audio_ena = true) { log_init(); nes_create(sample_rate_, sample_bits_); inp_[0].type = INP_JOYPAD0; inp_[0].data = 0; input_register(&inp_[0]); inp_[1].type = INP_JOYPAD1; inp_[1].data = 0; input_register(&inp_[1]); return true; } //-----------------------------------------------------------------// /*! @brief エミュレーター・ファイルを開く @param[in] filename ファイル名 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool open(const char* filename) { nesrom_ = false; if(nes_insertcart(filename) == 0) { nesrom_ = true; } // } else if(nsfplay_.open(filename)) { // nesrom_ = true; // } return nesrom_; } //-----------------------------------------------------------------// /*! @brief サービス @param[in] org フレームバッファのアドレス @param[in] xs フレームバッファのX幅 @param[in] ys フレームバッファのY幅 */ //-----------------------------------------------------------------// void service(void* org, uint32_t xs, uint32_t ys) { if(delay_ > 0) { --delay_; if(delay_ == 0) { // open("GALAXIAN.NES"); open("GRADIUS.nes"); // open("DragonQuest_J_fix.nes"); // open("Dragon_Quest2_fix.nes"); // open("Solstice_J.nes"); // open("Zombie.nes"); } } auto nes = nes_getcontext(); bitmap_t* v = nes->vidbuf; const rgb_t* lut = get_palette(); if(v == nullptr || lut == nullptr) { return; } { inp_[0].data = 0; inp_[1].data = 0; uint8_t pad = get_fami_pad(); if(chip::on(pad, chip::FAMIPAD_ST::A)) { inp_[0].data |= INP_PAD_A; } if(chip::on(pad, chip::FAMIPAD_ST::B)) { inp_[0].data |= INP_PAD_B; } if(chip::on(pad, chip::FAMIPAD_ST::SELECT)) { inp_[0].data |= INP_PAD_SELECT; } if(chip::on(pad, chip::FAMIPAD_ST::START)) { inp_[0].data |= INP_PAD_START; } if(chip::on(pad, chip::FAMIPAD_ST::UP)) { inp_[0].data |= INP_PAD_UP; } if(chip::on(pad, chip::FAMIPAD_ST::DOWN)) { inp_[0].data |= INP_PAD_DOWN; } if(chip::on(pad, chip::FAMIPAD_ST::LEFT)) { inp_[0].data |= INP_PAD_LEFT; } if(chip::on(pad, chip::FAMIPAD_ST::RIGHT)) { inp_[0].data |= INP_PAD_RIGHT; } } uint16_t luttmp[256]; for(uint32_t i = 0; i < 64; ++i) { uint16_t r = lut[i].r; // R uint16_t g = lut[i].g; // G uint16_t b = lut[i].b; // B // R(5), G(6), B(5) luttmp[i] = ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3); luttmp[i+128+64] = luttmp[i+128] = luttmp[i+64] = luttmp[i]; } uint16_t* dst = static_cast<uint16_t*>(org); dst += ((ys - (nes_height_ - 16)) / 2) * xs; const uint8_t* src = v->data; src += v->pitch * 16; for(int h = 0; h < (nes_height_ - 16); ++h) { uint16_t* tmp = dst; tmp += (xs - nes_width_) / 2; for(int w = 0; w < nes_width_ / 16; ++w) { *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; } src += v->pitch - nes_width_; dst += xs; } if(nesrom_) { apu_process(audio_buf_, audio_len_); nes_emulate(1); } } //-----------------------------------------------------------------// /*! @brief オーディオ・バッファの長さを取得 @return オーディオ・バッファの長さ */ //-----------------------------------------------------------------// uint32_t get_audio_len() const noexcept { return audio_len_; } //-----------------------------------------------------------------// /*! @brief オーディオ・バッファを取得 @return オーディオ・バッファのポインター */ //-----------------------------------------------------------------// const uint16_t* get_audio_buf() const noexcept { return audio_buf_; } }; } <commit_msg>update: cleanup<commit_after>#pragma once //=====================================================================// /*! @file @brief NES Emulator ハンドラー @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "emu/log.h" #include "emu/nes/nes.h" #include "emu/nes/nesinput.h" #include "emu/nes/nesstate.h" #include "emu/nes/nes_pal.h" #include "chip/FAMIPAD.hpp" // #include "emu/nsf/nsfplay.hpp" extern "C" { uint8_t get_fami_pad(); uint16_t sci_length(void); char sci_getch(void); } namespace emu { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief NESエミュレーション・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class nesemu { static const int nes_width_ = 256; static const int nes_height_ = 240; static const int sample_rate_ = 22050; static const int sample_bits_ = 16; static const int audio_len_ = sample_rate_ / 60; uint16_t audio_buf_[audio_len_ + 16]; // emu::nsfplay nsfplay_; bool nesrom_; uint32_t delay_; nesinput_t inp_[2]; public: //-----------------------------------------------------------------// /*! @brief コンストラクタ */ //-----------------------------------------------------------------// nesemu() noexcept : nesrom_(false), delay_(120) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] オーディオをサポートしない場合「false」 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool start(bool audio_ena = true) { log_init(); nes_create(sample_rate_, sample_bits_); inp_[0].type = INP_JOYPAD0; inp_[0].data = 0; input_register(&inp_[0]); inp_[1].type = INP_JOYPAD1; inp_[1].data = 0; input_register(&inp_[1]); return true; } //-----------------------------------------------------------------// /*! @brief エミュレーター・ファイルを開く @param[in] filename ファイル名 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool open(const char* filename) { nesrom_ = false; if(nes_insertcart(filename) == 0) { nesrom_ = true; } // } else if(nsfplay_.open(filename)) { // nesrom_ = true; // } return nesrom_; } //-----------------------------------------------------------------// /*! @brief サービス @param[in] org フレームバッファのアドレス @param[in] xs フレームバッファのX幅 @param[in] ys フレームバッファのY幅 */ //-----------------------------------------------------------------// void service(void* org, uint32_t xs, uint32_t ys) { if(delay_ > 0) { --delay_; if(delay_ == 0) { // open("GALAXIAN.NES"); // open("GRADIUS.nes"); // open("DragonQuest_J_fix.nes"); // open("High_Speed_E.nes"); open("Dragon_Quest2_fix.nes"); // open("Solstice_J.nes"); // open("Zombie.nes"); } } auto nes = nes_getcontext(); bitmap_t* v = nes->vidbuf; const rgb_t* lut = get_palette(); if(v == nullptr || lut == nullptr) { return; } { inp_[0].data = 0; inp_[1].data = 0; uint8_t pad = get_fami_pad(); if(chip::on(pad, chip::FAMIPAD_ST::A)) { inp_[0].data |= INP_PAD_A; } if(chip::on(pad, chip::FAMIPAD_ST::B)) { inp_[0].data |= INP_PAD_B; } if(chip::on(pad, chip::FAMIPAD_ST::SELECT)) { inp_[0].data |= INP_PAD_SELECT; } if(chip::on(pad, chip::FAMIPAD_ST::START)) { inp_[0].data |= INP_PAD_START; } if(chip::on(pad, chip::FAMIPAD_ST::UP)) { inp_[0].data |= INP_PAD_UP; } if(chip::on(pad, chip::FAMIPAD_ST::DOWN)) { inp_[0].data |= INP_PAD_DOWN; } if(chip::on(pad, chip::FAMIPAD_ST::LEFT)) { inp_[0].data |= INP_PAD_LEFT; } if(chip::on(pad, chip::FAMIPAD_ST::RIGHT)) { inp_[0].data |= INP_PAD_RIGHT; } } uint16_t luttmp[256]; for(uint32_t i = 0; i < 64; ++i) { uint16_t r = lut[i].r; // R uint16_t g = lut[i].g; // G uint16_t b = lut[i].b; // B // R(5), G(6), B(5) luttmp[i] = ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3); luttmp[i+128+64] = luttmp[i+128] = luttmp[i+64] = luttmp[i]; } uint16_t* dst = static_cast<uint16_t*>(org); dst += ((ys - (nes_height_ - 16)) / 2) * xs; const uint8_t* src = v->data; src += v->pitch * 16; for(int h = 0; h < (nes_height_ - 16); ++h) { uint16_t* tmp = dst; tmp += (xs - nes_width_) / 2; for(int w = 0; w < nes_width_ / 16; ++w) { *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++]; } src += v->pitch - nes_width_; dst += xs; } if(nesrom_) { apu_process(audio_buf_, audio_len_); nes_emulate(1); } } //-----------------------------------------------------------------// /*! @brief オーディオ・バッファの長さを取得 @return オーディオ・バッファの長さ */ //-----------------------------------------------------------------// uint32_t get_audio_len() const noexcept { return audio_len_; } //-----------------------------------------------------------------// /*! @brief オーディオ・バッファを取得 @return オーディオ・バッファのポインター */ //-----------------------------------------------------------------// const uint16_t* get_audio_buf() const noexcept { return audio_buf_; } }; } <|endoftext|>
<commit_before>/* Copyright (C) 2013 Samsung Electronics This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "eweb_view.h" #include "selection_controller_efl.h" #include "selection_handle_efl.h" #include "selection_box_efl.h" #include "selection_magnifier_efl.h" namespace content { static bool IsRectEmpty(const gfx::Rect& rect) { if (rect.x() == 0 && rect.y() == 0 && rect.height() == 0 && rect.width() == 0) { LOG(INFO) << "SelectionControllerEfl:IsRectEmpty : true"; return true; } return false; } SelectionControllerEfl::SelectionControllerEfl(EWebView* parent_view) : parent_view_(parent_view), mouse_press_(false), long_mouse_press_(false), scrolling_(false), selection_data_(new SelectionBoxEfl(parent_view)), start_handle_(new SelectionHandleEfl(this, SelectionHandleEfl::HANDLE_TYPE_LEFT, parent_view->evas_object())), end_handle_(new SelectionHandleEfl(this, SelectionHandleEfl::HANDLE_TYPE_RIGHT, parent_view->evas_object())), input_handle_(new SelectionHandleEfl(this, SelectionHandleEfl::HANDLE_TYPE_INPUT, parent_view->evas_object())), magnifier_(new SelectionMagnifierEfl(this)) { evas_object_event_callback_add(parent_view_->evas_object(), EVAS_CALLBACK_MOVE, &EvasParentViewMoveCallback, this); } void SelectionControllerEfl::SetSelectionStatus(bool enable) { LOG(INFO) << "SelectionControllerEfl::SetSelectionStatus " << enable; selection_data_->SetStatus(enable); } bool SelectionControllerEfl::GetSelectionStatus() const { LOG(INFO) << "SelectionControllerEfl::GetSelectionStatus " << selection_data_->GetStatus(); return selection_data_->GetStatus(); } void SelectionControllerEfl::SetSelectionEditable(bool enable) { LOG(INFO) << "SelectionControllerEfl::SetSelectionEditable" << enable; selection_data_->SetEditable(enable); } bool SelectionControllerEfl::GetSelectionEditable() const { LOG(INFO) << "SelectionControllerEfl::GetSelectionEditable " << selection_data_->GetEditable(); return selection_data_->GetEditable(); } void SelectionControllerEfl::SetCaretSelectionStatus(const bool enable) { LOG(INFO) << "SelectionControllerEfl::SetCaretSelectionStatus : " << enable; selection_data_->SetCaretSelectionStatus(enable); } bool SelectionControllerEfl::GetCaretSelectionStatus() const { LOG(INFO) << "SelectionControllerEfl::GetCaretSelectionStatus : " << selection_data_->GetCaretSelectionStatus(); return selection_data_->GetCaretSelectionStatus(); } void SelectionControllerEfl::SetScrollStatus(const bool enable) { LOG(INFO) << __PRETTY_FUNCTION__ << " enable : " << enable; scrolling_ = enable; if (enable) Clear(); else ShowHandleAndContextMenuIfRequired(); } bool SelectionControllerEfl::GetScrollStatus() { LOG(INFO) << __PRETTY_FUNCTION__ << " " << scrolling_; return scrolling_; } void SelectionControllerEfl::UpdateSelectionData(const base::string16& text) { selection_data_->UpdateSelectStringData(text); } void SelectionControllerEfl::UpdateMagnifierScreen(Evas_Object* img) { magnifier_->UpdateScreen(img); } void SelectionControllerEfl::UpdateSelectionDataAndShow(const gfx::Rect& left_rect, const gfx::Rect& right_rect, bool is_anchor_first) { LOG(INFO) << __PRETTY_FUNCTION__; selection_data_->UpdateRectData(left_rect, right_rect, is_anchor_first); if (!IsSelectionValid(left_rect, right_rect)) { Clear(); return; } // Do not show the context menu and handlers untill long mouse press is released if (long_mouse_press_) return; // Do not show the context menu and handlers while page is scrolling if (scrolling_) return; ShowHandleAndContextMenuIfRequired(); } void SelectionControllerEfl::ShowHandleAndContextMenuIfRequired() { LOG(INFO) << __PRETTY_FUNCTION__; if (!selection_data_->GetStatus()) return; Clear(); // Is in edit field and no text is selected. show only single handle if (selection_data_->IsInEditField() && GetCaretSelectionStatus()) { gfx::Rect left = selection_data_->GetLeftRect(); input_handle_->SetBasePosition(gfx::Point(left.x(), left.y())); input_handle_->SetCursorHandlerStatus(true); input_handle_->Move(gfx::Point(left.x(), left.y() + left.height())); input_handle_->Show(); return; } // FIXME : Check the text Direction later gfx::Rect left = selection_data_->GetLeftRect(); // The base position of start_handle should be set to the middle of the left rectangle. // Otherwise the start_handle may be shifted up when the right_handle is moving start_handle_->SetBasePosition(gfx::Point(left.x(), left.y() + (left.height() / 2))); start_handle_->Move(gfx::Point(left.x(), left.y() + left.height())); start_handle_->Show(); gfx::Rect right = selection_data_->GetRightRect(); // The base position of end_handle should be set to the middle of the right rectangle. // Otherwise the end_handle may be shifted up when the left_handle is moving end_handle_->SetBasePosition(gfx::Point(right.x(), right.y() + (right.height() / 2))); end_handle_->Move(gfx::Point(right.x() + right.width(), right.y() + right.height())); end_handle_->Show(); // Do not show the context menu during selection extend if (!mouse_press_) parent_view_->ShowContextMenu(*(selection_data_->GetContextMenuParams()), MENU_TYPE_SELECTION); parent_view_->QuerySelectionStyle(); } void SelectionControllerEfl::HideHandle() { SetCaretSelectionStatus(false); Clear(); } void SelectionControllerEfl::HideHandleAndContextMenu() { parent_view_->CancelContextMenu(0); HideHandle(); } void SelectionControllerEfl::Clear() { start_handle_->Hide(); end_handle_->Hide(); input_handle_->Hide(); } void SelectionControllerEfl::OnMouseDown(const gfx::Point& touch_point) { // Hide context menu on mouse down parent_view_->CancelContextMenu(0); mouse_press_ = true; magnifier_->UpdateLocation(touch_point); magnifier_->Move(touch_point); magnifier_->Show(); } void SelectionControllerEfl::OnMouseMove(const gfx::Point& touch_point, bool on_curson_handle) { // FIXME : Check the text Direction later magnifier_->UpdateLocation(touch_point); magnifier_->Move(touch_point); if (!on_curson_handle) parent_view_->SelectRange(start_handle_->GetBasePosition(), end_handle_->GetBasePosition()); else parent_view_->MoveCaret(input_handle_->GetBasePosition()); } void SelectionControllerEfl::OnMouseUp(const gfx::Point& touch_point) { selection_data_->UpdateHandleData(); mouse_press_ = false; magnifier_->Hide(); parent_view_->ShowContextMenu(*(selection_data_->GetContextMenuParams()), MENU_TYPE_SELECTION); } void SelectionControllerEfl::GetSelectionBounds(gfx::Rect* left, gfx::Rect* right) { if (left) *left = selection_data_->GetLeftRect(); if (right) *right = selection_data_->GetRightRect(); } void SelectionControllerEfl::HandleLongPressEvent(const gfx::Point& touch_point) { long_mouse_press_ = true; magnifier_->HandleLongPress(touch_point); } void SelectionControllerEfl::HandleLongPressMoveEvent(const gfx::Point& touch_point) { parent_view_->SelectClosestWord(touch_point); if (selection_data_->GetCaretSelectionStatus()) { parent_view_->MoveCaret(touch_point); SetSelectionStatus(true); ShowHandleAndContextMenuIfRequired(); } else{ parent_view_->SelectClosestWord(touch_point); } } void SelectionControllerEfl::HandleLongPressEndEvent() { long_mouse_press_ = false; if (selection_data_->GetCaretSelectionStatus()) { SetSelectionStatus(true); SetSelectionEditable(true); } ShowHandleAndContextMenuIfRequired(); } bool SelectionControllerEfl::IsSelectionValid(const gfx::Rect& left_rect, const gfx::Rect& right_rect) { LOG(INFO) << __PRETTY_FUNCTION__ << " l_x = " << left_rect.x() << " l_y = " << left_rect.y() << " r_x = " << right_rect.x() << " r_y = " << right_rect.y(); // For all normal cases the widht will be 0 and we want to check empty which Implies // x, y, h w all to be 0 if ((IsRectEmpty(left_rect) || IsRectEmpty(right_rect))) { SetSelectionStatus(false); return false; } // The most of sites return width of each rects as 0 when text is selected. // However, some websites that have viewport attributes on meta tag v // return width 0 right after they are loaded, even though text is not selected. // Thus the width is not sufficient for checking selection condition. // Further invesitigation showed left_rect and right_rect always have the same x,y values // for such cases. So, the equality for x and y rather than width should be tested. if (left_rect.x()==right_rect.x() && left_rect.y()==right_rect.y() && !selection_data_->IsInEditField() && !mouse_press_) { SetSelectionStatus(false); return false; } LOG(INFO) << "SelectionControllerEfl::IsSelectionValid true"; if (!GetSelectionStatus()) SetSelectionStatus(true); if (left_rect.x() != right_rect.x() || left_rect.y() != right_rect.y() && selection_data_->IsInEditField() && GetCaretSelectionStatus()) { if (!long_mouse_press_) SetCaretSelectionStatus(false); } LOG(INFO) << "SelectionControllerEfl::IsSelectionValid true"; return true; } void SelectionControllerEfl::ClearSelection() { LOG(INFO) << __PRETTY_FUNCTION__; Clear(); selection_data_->SetStatus(false); SetSelectionEditable(false); SetCaretSelectionStatus(false); } void SelectionControllerEfl::OnParentParentViewMove() { LOG(INFO) << __PRETTY_FUNCTION__; parent_view_->CancelContextMenu(0); start_handle_->Move(start_handle_->GetBasePosition()); end_handle_->Move(end_handle_->GetBasePosition()); } gfx::Rect SelectionControllerEfl::GetLeftRect() { return selection_data_->GetLeftRect(); } gfx::Rect SelectionControllerEfl::GetRightRect() { return selection_data_->GetRightRect(); } } <commit_msg>Adjust handle's direction when text selection changes<commit_after>/* Copyright (C) 2013 Samsung Electronics This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "eweb_view.h" #include "selection_controller_efl.h" #include "selection_handle_efl.h" #include "selection_box_efl.h" #include "selection_magnifier_efl.h" namespace content { static bool IsRectEmpty(const gfx::Rect& rect) { if (rect.x() == 0 && rect.y() == 0 && rect.height() == 0 && rect.width() == 0) { LOG(INFO) << "SelectionControllerEfl:IsRectEmpty : true"; return true; } return false; } SelectionControllerEfl::SelectionControllerEfl(EWebView* parent_view) : parent_view_(parent_view), mouse_press_(false), long_mouse_press_(false), scrolling_(false), selection_data_(new SelectionBoxEfl(parent_view)), start_handle_(new SelectionHandleEfl(this, SelectionHandleEfl::HANDLE_TYPE_LEFT, parent_view->evas_object())), end_handle_(new SelectionHandleEfl(this, SelectionHandleEfl::HANDLE_TYPE_RIGHT, parent_view->evas_object())), input_handle_(new SelectionHandleEfl(this, SelectionHandleEfl::HANDLE_TYPE_INPUT, parent_view->evas_object())), magnifier_(new SelectionMagnifierEfl(this)) { evas_object_event_callback_add(parent_view_->evas_object(), EVAS_CALLBACK_MOVE, &EvasParentViewMoveCallback, this); } void SelectionControllerEfl::SetSelectionStatus(bool enable) { LOG(INFO) << "SelectionControllerEfl::SetSelectionStatus " << enable; selection_data_->SetStatus(enable); } bool SelectionControllerEfl::GetSelectionStatus() const { LOG(INFO) << "SelectionControllerEfl::GetSelectionStatus " << selection_data_->GetStatus(); return selection_data_->GetStatus(); } void SelectionControllerEfl::SetSelectionEditable(bool enable) { LOG(INFO) << "SelectionControllerEfl::SetSelectionEditable" << enable; selection_data_->SetEditable(enable); } bool SelectionControllerEfl::GetSelectionEditable() const { LOG(INFO) << "SelectionControllerEfl::GetSelectionEditable " << selection_data_->GetEditable(); return selection_data_->GetEditable(); } void SelectionControllerEfl::SetCaretSelectionStatus(const bool enable) { LOG(INFO) << "SelectionControllerEfl::SetCaretSelectionStatus : " << enable; selection_data_->SetCaretSelectionStatus(enable); } bool SelectionControllerEfl::GetCaretSelectionStatus() const { LOG(INFO) << "SelectionControllerEfl::GetCaretSelectionStatus : " << selection_data_->GetCaretSelectionStatus(); return selection_data_->GetCaretSelectionStatus(); } void SelectionControllerEfl::SetScrollStatus(const bool enable) { LOG(INFO) << __PRETTY_FUNCTION__ << " enable : " << enable; scrolling_ = enable; if (enable) Clear(); else ShowHandleAndContextMenuIfRequired(); } bool SelectionControllerEfl::GetScrollStatus() { LOG(INFO) << __PRETTY_FUNCTION__ << " " << scrolling_; return scrolling_; } void SelectionControllerEfl::UpdateSelectionData(const base::string16& text) { selection_data_->UpdateSelectStringData(text); } void SelectionControllerEfl::UpdateMagnifierScreen(Evas_Object* img) { magnifier_->UpdateScreen(img); } void SelectionControllerEfl::UpdateSelectionDataAndShow(const gfx::Rect& left_rect, const gfx::Rect& right_rect, bool is_anchor_first) { LOG(INFO) << __PRETTY_FUNCTION__; selection_data_->UpdateRectData(left_rect, right_rect, is_anchor_first); if (!IsSelectionValid(left_rect, right_rect)) { Clear(); return; } // Do not show the context menu and handlers untill long mouse press is released if (long_mouse_press_) return; // Do not show the context menu and handlers while page is scrolling if (scrolling_) return; ShowHandleAndContextMenuIfRequired(); } void SelectionControllerEfl::ShowHandleAndContextMenuIfRequired() { LOG(INFO) << __PRETTY_FUNCTION__; if (!selection_data_->GetStatus()) return; Clear(); // Is in edit field and no text is selected. show only single handle if (selection_data_->IsInEditField() && GetCaretSelectionStatus()) { gfx::Rect left = selection_data_->GetLeftRect(); input_handle_->SetBasePosition(gfx::Point(left.x(), left.y())); input_handle_->SetCursorHandlerStatus(true); input_handle_->Move(gfx::Point(left.x(), left.y() + left.height())); input_handle_->Show(); if (!mouse_press_) parent_view_->ShowContextMenu(*(selection_data_->GetContextMenuParams()), MENU_TYPE_SELECTION); return; } // FIXME : Check the text Direction later gfx::Rect left = selection_data_->GetLeftRect(); // The base position of start_handle should be set to the middle of the left rectangle. // Otherwise the start_handle may be shifted up when the right_handle is moving start_handle_->SetBasePosition(gfx::Point(left.x(), left.y() + (left.height() / 2))); start_handle_->Move(gfx::Point(left.x(), left.y() + left.height())); start_handle_->Show(); gfx::Rect right = selection_data_->GetRightRect(); // The base position of end_handle should be set to the middle of the right rectangle. // Otherwise the end_handle may be shifted up when the left_handle is moving end_handle_->SetBasePosition(gfx::Point(right.x(), right.y() + (right.height() / 2))); end_handle_->Move(gfx::Point(right.x() + right.width(), right.y() + right.height())); end_handle_->Show(); // Do not show the context menu during selection extend if (!mouse_press_) parent_view_->ShowContextMenu(*(selection_data_->GetContextMenuParams()), MENU_TYPE_SELECTION); parent_view_->QuerySelectionStyle(); } void SelectionControllerEfl::HideHandle() { SetCaretSelectionStatus(false); Clear(); } void SelectionControllerEfl::HideHandleAndContextMenu() { parent_view_->CancelContextMenu(0); HideHandle(); } void SelectionControllerEfl::Clear() { start_handle_->Hide(); end_handle_->Hide(); input_handle_->Hide(); } void SelectionControllerEfl::OnMouseDown(const gfx::Point& touch_point) { // Hide context menu on mouse down parent_view_->CancelContextMenu(0); mouse_press_ = true; magnifier_->UpdateLocation(touch_point); magnifier_->Move(touch_point); ShowHandleAndContextMenuIfRequired(); } void SelectionControllerEfl::OnMouseMove(const gfx::Point& touch_point, bool on_curson_handle) { // FIXME : Check the text Direction later magnifier_->UpdateLocation(touch_point); magnifier_->Move(touch_point); if (!on_curson_handle) parent_view_->SelectRange(start_handle_->GetBasePosition(), end_handle_->GetBasePosition()); else parent_view_->MoveCaret(input_handle_->GetBasePosition()); } void SelectionControllerEfl::OnMouseUp(const gfx::Point& touch_point) { selection_data_->UpdateHandleData(); mouse_press_ = false; magnifier_->Hide(); parent_view_->ShowContextMenu(*(selection_data_->GetContextMenuParams()), MENU_TYPE_SELECTION); } void SelectionControllerEfl::GetSelectionBounds(gfx::Rect* left, gfx::Rect* right) { if (left) *left = selection_data_->GetLeftRect(); if (right) *right = selection_data_->GetRightRect(); } void SelectionControllerEfl::HandleLongPressEvent(const gfx::Point& touch_point) { long_mouse_press_ = true; magnifier_->HandleLongPress(touch_point); } void SelectionControllerEfl::HandleLongPressMoveEvent(const gfx::Point& touch_point) { parent_view_->SelectClosestWord(touch_point); if (selection_data_->GetCaretSelectionStatus()) { parent_view_->MoveCaret(touch_point); SetSelectionStatus(true); ShowHandleAndContextMenuIfRequired(); } else{ parent_view_->SelectClosestWord(touch_point); } } void SelectionControllerEfl::HandleLongPressEndEvent() { long_mouse_press_ = false; if (selection_data_->GetCaretSelectionStatus()) { SetSelectionStatus(true); SetSelectionEditable(true); } ShowHandleAndContextMenuIfRequired(); } bool SelectionControllerEfl::IsSelectionValid(const gfx::Rect& left_rect, const gfx::Rect& right_rect) { LOG(INFO) << __PRETTY_FUNCTION__ << " l_x = " << left_rect.x() << " l_y = " << left_rect.y() << " r_x = " << right_rect.x() << " r_y = " << right_rect.y(); // For all normal cases the widht will be 0 and we want to check empty which Implies // x, y, h w all to be 0 if ((IsRectEmpty(left_rect) || IsRectEmpty(right_rect))) { SetSelectionStatus(false); return false; } // The most of sites return width of each rects as 0 when text is selected. // However, some websites that have viewport attributes on meta tag v // return width 0 right after they are loaded, even though text is not selected. // Thus the width is not sufficient for checking selection condition. // Further invesitigation showed left_rect and right_rect always have the same x,y values // for such cases. So, the equality for x and y rather than width should be tested. if (left_rect.x()==right_rect.x() && left_rect.y()==right_rect.y() && !selection_data_->IsInEditField() && !mouse_press_) { SetSelectionStatus(false); return false; } LOG(INFO) << "SelectionControllerEfl::IsSelectionValid true"; if (!GetSelectionStatus()) SetSelectionStatus(true); if (left_rect.x() != right_rect.x() || left_rect.y() != right_rect.y() && selection_data_->IsInEditField() && GetCaretSelectionStatus()) { if (!long_mouse_press_) SetCaretSelectionStatus(false); } LOG(INFO) << "SelectionControllerEfl::IsSelectionValid true"; return true; } void SelectionControllerEfl::ClearSelection() { LOG(INFO) << __PRETTY_FUNCTION__; Clear(); selection_data_->SetStatus(false); SetSelectionEditable(false); SetCaretSelectionStatus(false); } void SelectionControllerEfl::OnParentParentViewMove() { LOG(INFO) << __PRETTY_FUNCTION__; parent_view_->CancelContextMenu(0); start_handle_->Move(start_handle_->GetBasePosition()); end_handle_->Move(end_handle_->GetBasePosition()); } gfx::Rect SelectionControllerEfl::GetLeftRect() { return selection_data_->GetLeftRect(); } gfx::Rect SelectionControllerEfl::GetRightRect() { return selection_data_->GetRightRect(); } } <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> using namespace boost::python; using namespace libtorrent; std::string get_buffer(read_piece_alert const& rpa) { return rpa.buffer ? std::string(rpa.buffer.get(), rpa.size) : std::string(); } void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", no_init) .def("message", &alert::message) .def("what", &alert::what) .def("category", &alert::category) #ifndef TORRENT_NO_DEPRECATE .def("severity", &alert::severity) #endif .def("__str__", &alert::message) ; #ifndef TORRENT_NO_DEPRECATE enum_<alert::severity_t>("severity_levels") .value("debug", alert::debug) .value("info", alert::info) .value("warning", alert::warning) .value("critical", alert::critical) .value("fatal", alert::fatal) .value("none", alert::none) ; #endif enum_<alert::category_t>("category_t") .value("error_notification", alert::error_notification) .value("peer_notification", alert::peer_notification) .value("port_mapping_notification", alert::port_mapping_notification) .value("storage_notification", alert::storage_notification) .value("tracker_notification", alert::tracker_notification) .value("debug_notification", alert::debug_notification) .value("status_notification", alert::status_notification) .value("progress_notification", alert::progress_notification) .value("ip_block_notification", alert::ip_block_notification) .value("performance_warning", alert::performance_warning) .value("all_categories", alert::all_categories) ; } class_<torrent_alert, bases<alert>, noncopyable>( "torrent_alert", no_init ) .def_readonly("handle", &torrent_alert::handle) ; class_<tracker_alert, bases<torrent_alert>, noncopyable>( "tracker_alert", no_init ) .def_readonly("url", &tracker_alert::url) ; class_<read_piece_alert, bases<torrent_alert>, noncopyable>( "read_piece_alert", 0, no_init ) .add_property("buffer", get_buffer) .def_readonly("piece", &read_piece_alert::piece) .def_readonly("size", &read_piece_alert::size) ; class_<peer_alert, bases<torrent_alert>, noncopyable>( "peer_alert", no_init ) .def_readonly("ip", &peer_alert::ip) .def_readonly("pid", &peer_alert::pid) ; class_<tracker_error_alert, bases<tracker_alert>, noncopyable>( "tracker_error_alert", no_init ) .def_readonly("msg", &tracker_error_alert::msg) .def_readonly("times_in_row", &tracker_error_alert::times_in_row) .def_readonly("status_code", &tracker_error_alert::status_code) ; class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>( "tracker_warning_alert", no_init ); class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>( "tracker_reply_alert", no_init ) .def_readonly("num_peers", &tracker_reply_alert::num_peers) ; class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>( "tracker_announce_alert", no_init ); class_<hash_failed_alert, bases<torrent_alert>, noncopyable>( "hash_failed_alert", no_init ) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<peer_alert>, noncopyable>( "peer_ban_alert", no_init ); class_<peer_error_alert, bases<peer_alert>, noncopyable>( "peer_error_alert", no_init ); class_<invalid_request_alert, bases<peer_alert>, noncopyable>( "invalid_request_alert", no_init ) .def_readonly("request", &invalid_request_alert::request) ; class_<peer_request>("peer_request") .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>( "torrent_finished_alert", no_init ); class_<piece_finished_alert, bases<torrent_alert>, noncopyable>( "piece_finished_alert", no_init ) .def_readonly("piece_index", &piece_finished_alert::piece_index) ; class_<block_finished_alert, bases<peer_alert>, noncopyable>( "block_finished_alert", no_init ) .def_readonly("block_index", &block_finished_alert::block_index) .def_readonly("piece_index", &block_finished_alert::piece_index) ; class_<block_downloading_alert, bases<peer_alert>, noncopyable>( "block_downloading_alert", no_init ) .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg) .def_readonly("block_index", &block_downloading_alert::block_index) .def_readonly("piece_index", &block_downloading_alert::piece_index) ; class_<storage_moved_alert, bases<torrent_alert>, noncopyable>( "storage_moved_alert", no_init ); class_<storage_moved_failed_alert, bases<torrent_alert>, noncopyable>( "storage_moved_failed_alert", no_init ) .def_readonly("error", &storage_moved_failed_alert::error) ; class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>( "torrent_deleted_alert", no_init ); class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>( "torrent_paused_alert", no_init ); class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>( "torrent_checked_alert", no_init ); class_<url_seed_alert, bases<torrent_alert>, noncopyable>( "url_seed_alert", no_init ) .def_readonly("url", &url_seed_alert::url) ; class_<file_error_alert, bases<torrent_alert>, noncopyable>( "file_error_alert", no_init ) .def_readonly("file", &file_error_alert::file) ; class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>( "metadata_failed_alert", no_init ); class_<metadata_received_alert, bases<torrent_alert>, noncopyable>( "metadata_received_alert", no_init ); class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", no_init ); class_<listen_succeeded_alert, bases<alert>, noncopyable>( "listen_succeeded_alert", no_init ) .def_readonly("endpoint", &listen_succeeded_alert::endpoint) ; class_<portmap_error_alert, bases<alert>, noncopyable>( "portmap_error_alert", no_init ) .def_readonly("mapping", &portmap_error_alert::mapping) .def_readonly("type", &portmap_error_alert::type) ; class_<portmap_alert, bases<alert>, noncopyable>( "portmap_alert", no_init ) .def_readonly("mapping", &portmap_alert::mapping) .def_readonly("external_port", &portmap_alert::external_port) .def_readonly("type", &portmap_alert::type) ; class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>( "fastresume_rejected_alert", no_init ); class_<peer_blocked_alert, bases<alert>, noncopyable>( "peer_blocked_alert", no_init ) .def_readonly("ip", &peer_blocked_alert::ip) ; class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>( "scrape_reply_alert", no_init ) .def_readonly("incomplete", &scrape_reply_alert::incomplete) .def_readonly("complete", &scrape_reply_alert::complete) ; class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>( "scrape_failed_alert", no_init ); class_<udp_error_alert, bases<alert>, noncopyable>( "udp_error_alert", no_init ) .def_readonly("endpoint", &udp_error_alert::endpoint) ; class_<external_ip_alert, bases<alert>, noncopyable>( "external_ip_alert", no_init ) .def_readonly("external_address", &external_ip_alert::external_address) ; class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_alert", no_init ) .def_readonly("resume_data", &save_resume_data_alert::resume_data) ; class_<file_renamed_alert, bases<torrent_alert>, noncopyable>( "file_renamed_alert", no_init ) .def_readonly("index", &file_renamed_alert::index) .def_readonly("name", &file_renamed_alert::name) ; class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>( "file_rename_failed_alert", no_init ) .def_readonly("index", &file_rename_failed_alert::index) .def_readonly("error", &file_rename_failed_alert::error) ; class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>( "torrent_resumed_alert", no_init ); class_<state_changed_alert, bases<torrent_alert>, noncopyable>( "state_changed_alert", no_init ) .def_readonly("state", &state_changed_alert::state) ; class_<dht_reply_alert, bases<tracker_alert>, noncopyable>( "dht_reply_alert", no_init ) .def_readonly("num_peers", &dht_reply_alert::num_peers) ; class_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>( "peer_unsnubbed_alert", no_init ); class_<peer_snubbed_alert, bases<peer_alert>, noncopyable>( "peer_snubbed_alert", no_init ); class_<peer_connect_alert, bases<peer_alert>, noncopyable>( "peer_connect_alert", no_init ); class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>( "peer_disconnected_alert", no_init ); class_<request_dropped_alert, bases<peer_alert>, noncopyable>( "request_dropped_alert", no_init ) .def_readonly("block_index", &request_dropped_alert::block_index) .def_readonly("piece_index", &request_dropped_alert::piece_index) ; class_<block_timeout_alert, bases<peer_alert>, noncopyable>( "block_timeout_alert", no_init ) .def_readonly("block_index", &block_timeout_alert::block_index) .def_readonly("piece_index", &block_timeout_alert::piece_index) ; class_<unwanted_block_alert, bases<peer_alert>, noncopyable>( "unwanted_block_alert", no_init ) .def_readonly("block_index", &unwanted_block_alert::block_index) .def_readonly("piece_index", &unwanted_block_alert::piece_index) ; class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>( "torrent_delete_failed_alert", no_init ); class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_failed_alert", no_init ); class_<performance_alert, bases<torrent_alert>, noncopyable>( "performance_alert", no_init ) .def_readonly("warning_code", &performance_alert::warning_code) ; enum_<performance_alert::performance_warning_t>("performance_warning_t") .value("outstanding_disk_buffer_limit_reached", performance_alert::outstanding_disk_buffer_limit_reached) .value("outstanding_request_limit_reached", performance_alert::outstanding_request_limit_reached) ; } <commit_msg>Add some missing alerts and properties<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> using namespace boost::python; using namespace libtorrent; std::string get_buffer(read_piece_alert const& rpa) { return rpa.buffer ? std::string(rpa.buffer.get(), rpa.size) : std::string(); } void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", no_init) .def("message", &alert::message) .def("what", &alert::what) .def("category", &alert::category) #ifndef TORRENT_NO_DEPRECATE .def("severity", &alert::severity) #endif .def("__str__", &alert::message) ; #ifndef TORRENT_NO_DEPRECATE enum_<alert::severity_t>("severity_levels") .value("debug", alert::debug) .value("info", alert::info) .value("warning", alert::warning) .value("critical", alert::critical) .value("fatal", alert::fatal) .value("none", alert::none) ; #endif enum_<alert::category_t>("category_t") .value("error_notification", alert::error_notification) .value("peer_notification", alert::peer_notification) .value("port_mapping_notification", alert::port_mapping_notification) .value("storage_notification", alert::storage_notification) .value("tracker_notification", alert::tracker_notification) .value("debug_notification", alert::debug_notification) .value("status_notification", alert::status_notification) .value("progress_notification", alert::progress_notification) .value("ip_block_notification", alert::ip_block_notification) .value("performance_warning", alert::performance_warning) .value("all_categories", alert::all_categories) ; } class_<torrent_alert, bases<alert>, noncopyable>( "torrent_alert", no_init ) .def_readonly("handle", &torrent_alert::handle) ; class_<tracker_alert, bases<torrent_alert>, noncopyable>( "tracker_alert", no_init ) .def_readonly("url", &tracker_alert::url) ; class_<read_piece_alert, bases<torrent_alert>, noncopyable>( "read_piece_alert", 0, no_init ) .add_property("buffer", get_buffer) .def_readonly("piece", &read_piece_alert::piece) .def_readonly("size", &read_piece_alert::size) ; class_<peer_alert, bases<torrent_alert>, noncopyable>( "peer_alert", no_init ) .def_readonly("ip", &peer_alert::ip) .def_readonly("pid", &peer_alert::pid) ; class_<tracker_error_alert, bases<tracker_alert>, noncopyable>( "tracker_error_alert", no_init ) .def_readonly("msg", &tracker_error_alert::msg) .def_readonly("times_in_row", &tracker_error_alert::times_in_row) .def_readonly("status_code", &tracker_error_alert::status_code) ; class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>( "tracker_warning_alert", no_init ); class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>( "tracker_reply_alert", no_init ) .def_readonly("num_peers", &tracker_reply_alert::num_peers) ; class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>( "tracker_announce_alert", no_init ) .def_readonly("event", &tracker_reply_alert::event) ; class_<hash_failed_alert, bases<torrent_alert>, noncopyable>( "hash_failed_alert", no_init ) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<peer_alert>, noncopyable>( "peer_ban_alert", no_init ); class_<peer_error_alert, bases<peer_alert>, noncopyable>( "peer_error_alert", no_init ); class_<invalid_request_alert, bases<peer_alert>, noncopyable>( "invalid_request_alert", no_init ) .def_readonly("request", &invalid_request_alert::request) ; class_<peer_request>("peer_request") .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>( "torrent_finished_alert", no_init ); class_<piece_finished_alert, bases<torrent_alert>, noncopyable>( "piece_finished_alert", no_init ) .def_readonly("piece_index", &piece_finished_alert::piece_index) ; class_<block_finished_alert, bases<peer_alert>, noncopyable>( "block_finished_alert", no_init ) .def_readonly("block_index", &block_finished_alert::block_index) .def_readonly("piece_index", &block_finished_alert::piece_index) ; class_<block_downloading_alert, bases<peer_alert>, noncopyable>( "block_downloading_alert", no_init ) .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg) .def_readonly("block_index", &block_downloading_alert::block_index) .def_readonly("piece_index", &block_downloading_alert::piece_index) ; class_<storage_moved_alert, bases<torrent_alert>, noncopyable>( "storage_moved_alert", no_init ) .def_readonly("path", &storaged_moved_alert::path) ; class_<storage_moved_failed_alert, bases<torrent_alert>, noncopyable>( "storage_moved_failed_alert", no_init ) .def_readonly("error", &storage_moved_failed_alert::error) ; class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>( "torrent_deleted_alert", no_init ); class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>( "torrent_paused_alert", no_init ); class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>( "torrent_checked_alert", no_init ); class_<url_seed_alert, bases<torrent_alert>, noncopyable>( "url_seed_alert", no_init ) .def_readonly("url", &url_seed_alert::url) .def_readonly("msg", &url_seed_alert::msg) ; class_<file_error_alert, bases<torrent_alert>, noncopyable>( "file_error_alert", no_init ) .def_readonly("file", &file_error_alert::file) .def_readonly("msg", &file_error_alert::msg) ; class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>( "metadata_failed_alert", no_init ); class_<metadata_received_alert, bases<torrent_alert>, noncopyable>( "metadata_received_alert", no_init ); class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", no_init ) .def_readonly("endpoint", &listen_failed_alert::endpoint) .def_readonly("error", &listen_failed_alert::error) ; class_<listen_succeeded_alert, bases<alert>, noncopyable>( "listen_succeeded_alert", no_init ) .def_readonly("endpoint", &listen_succeeded_alert::endpoint) ; class_<portmap_error_alert, bases<alert>, noncopyable>( "portmap_error_alert", no_init ) .def_readonly("mapping", &portmap_error_alert::mapping) .def_readonly("type", &portmap_error_alert::type) .def_readonly("msg", &portmap_error_alert::msg) ; class_<portmap_alert, bases<alert>, noncopyable>( "portmap_alert", no_init ) .def_readonly("mapping", &portmap_alert::mapping) .def_readonly("external_port", &portmap_alert::external_port) .def_readonly("type", &portmap_alert::type) ; class_<portmap_log_alert, bases<alert>, noncopyable>( "portmap_log_alert", no_init ) .def_readonly("type", &portmap_log_alert::type) .def_readonly("msg", &portmap_log_alert::msg) ; class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>( "fastresume_rejected_alert", no_init ) .def_readonly("msg", &fastresume_rejected_alert::msg) ; class_<peer_blocked_alert, bases<alert>, noncopyable>( "peer_blocked_alert", no_init ) .def_readonly("ip", &peer_blocked_alert::ip) ; class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>( "scrape_reply_alert", no_init ) .def_readonly("incomplete", &scrape_reply_alert::incomplete) .def_readonly("complete", &scrape_reply_alert::complete) ; class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>( "scrape_failed_alert", no_init ); class_<udp_error_alert, bases<alert>, noncopyable>( "udp_error_alert", no_init ) .def_readonly("endpoint", &udp_error_alert::endpoint) .def_readonly("error", &udp_error_alert::error) ; class_<external_ip_alert, bases<alert>, noncopyable>( "external_ip_alert", no_init ) .def_readonly("external_address", &external_ip_alert::external_address) ; class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_alert", no_init ) .def_readonly("resume_data", &save_resume_data_alert::resume_data) ; class_<file_renamed_alert, bases<torrent_alert>, noncopyable>( "file_renamed_alert", no_init ) .def_readonly("index", &file_renamed_alert::index) .def_readonly("name", &file_renamed_alert::name) ; class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>( "file_rename_failed_alert", no_init ) .def_readonly("index", &file_rename_failed_alert::index) .def_readonly("error", &file_rename_failed_alert::error) ; class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>( "torrent_resumed_alert", no_init ); class_<state_changed_alert, bases<torrent_alert>, noncopyable>( "state_changed_alert", no_init ) .def_readonly("state", &state_changed_alert::state) .def_readonly("prev_state", &state_changed_alert::prev_state) ; class_<dht_reply_alert, bases<tracker_alert>, noncopyable>( "dht_reply_alert", no_init ) .def_readonly("num_peers", &dht_reply_alert::num_peers) ; class_<dht_announce_alert, bases<alert>, noncopyable>( "dht_announce_alert", no_init ) .def_readonly("ip" &dht_announce_alert::ip) .def_readonly("port", &dht_announce_alert::port) .def_readonly("info_hash", &dht_announce_alert::info_hash) ; class_<dht_get_peers_alert, bases<alert>, noncopyable>( "dht_get_peers_alert", no_init ) .def_readonly("info_hash", &dht_get_peers_alert::info_hash) ; class_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>( "peer_unsnubbed_alert", no_init ); class_<peer_snubbed_alert, bases<peer_alert>, noncopyable>( "peer_snubbed_alert", no_init ); class_<peer_connect_alert, bases<peer_alert>, noncopyable>( "peer_connect_alert", no_init ); class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>( "peer_disconnected_alert", no_init ) .def_readonly("msg", &peer_disconnected_alert::msg) ; class_<request_dropped_alert, bases<peer_alert>, noncopyable>( "request_dropped_alert", no_init ) .def_readonly("block_index", &request_dropped_alert::block_index) .def_readonly("piece_index", &request_dropped_alert::piece_index) ; class_<block_timeout_alert, bases<peer_alert>, noncopyable>( "block_timeout_alert", no_init ) .def_readonly("block_index", &block_timeout_alert::block_index) .def_readonly("piece_index", &block_timeout_alert::piece_index) ; class_<unwanted_block_alert, bases<peer_alert>, noncopyable>( "unwanted_block_alert", no_init ) .def_readonly("block_index", &unwanted_block_alert::block_index) .def_readonly("piece_index", &unwanted_block_alert::piece_index) ; class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>( "torrent_delete_failed_alert", no_init ) .def_readonly("msg", &torrent_delete_failed_alert::msg) ; class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_failed_alert", no_init ) .def_readonly("msg", &save_resume_data_failed_alert::msg) ; class_<performance_alert, bases<torrent_alert>, noncopyable>( "performance_alert", no_init ) .def_readonly("warning_code", &performance_alert::warning_code) ; enum_<performance_alert::performance_warning_t>("performance_warning_t") .value("outstanding_disk_buffer_limit_reached", performance_alert::outstanding_disk_buffer_limit_reached) .value("outstanding_request_limit_reached", performance_alert::outstanding_request_limit_reached) .value("upload_limit_too_low", performance_alert::upload_limit_too_low) .value("download_limit_too_low", performance_alert::download_limit_too_low) ; } <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; extern char const* alert_doc; extern char const* alert_msg_doc; extern char const* alert_severity_doc; extern char const* torrent_alert_doc; extern char const* tracker_alert_doc; extern char const* tracker_error_alert_doc; extern char const* tracker_warning_alert_doc; extern char const* tracker_reply_alert_doc; extern char const* tracker_announce_alert_doc; extern char const* hash_failed_alert_doc; extern char const* peer_ban_alert_doc; extern char const* peer_error_alert_doc; extern char const* invalid_request_alert_doc; extern char const* peer_request_doc; extern char const* torrent_finished_alert_doc; extern char const* piece_finished_alert_doc; extern char const* block_finished_alert_doc; extern char const* block_downloading_alert_doc; extern char const* storage_moved_alert_doc; extern char const* torrent_deleted_alert_doc; extern char const* torrent_paused_alert_doc; extern char const* torrent_checked_alert_doc; extern char const* url_seed_alert_doc; extern char const* file_error_alert_doc; extern char const* metadata_failed_alert_doc; extern char const* metadata_received_alert_doc; extern char const* listen_failed_alert_doc; extern char const* listen_succeeded_alert_doc; extern char const* portmap_error_alert_doc; extern char const* portmap_alert_doc; extern char const* fastresume_rejected_alert_doc; extern char const* peer_blocked_alert_doc; extern char const* scrape_reply_alert_doc; extern char const* scrape_failed_alert_doc; extern char const* udp_error_alert_doc; extern char const* external_ip_alert_doc; extern char const* save_resume_data_alert_doc; void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init) .def("message", &alert::message, alert_msg_doc) .def("what", &alert::what) .def("category", &alert::category) .def("severity", &alert::severity, alert_severity_doc) .def("__str__", &alert::message, alert_msg_doc) ; enum_<alert::severity_t>("severity_levels") .value("debug", alert::debug) .value("info", alert::info) .value("warning", alert::warning) .value("critical", alert::critical) .value("fatal", alert::fatal) .value("none", alert::none) ; enum_<alert::category_t>("category_t") .value("error_notification", alert::error_notification) .value("peer_notification", alert::peer_notification) .value("port_mapping_notification", alert::port_mapping_notification) .value("storage_notification", alert::storage_notification) .value("tracker_notification", alert::tracker_notification) .value("debug_notification", alert::debug_notification) .value("status_notification", alert::status_notification) .value("progress_notification", alert::progress_notification) .value("ip_block_notification", alert::ip_block_notification) .value("all_categories", alert::all_categories) ; } class_<torrent_alert, bases<alert>, noncopyable>( "torrent_alert", torrent_alert_doc, no_init ) .def_readonly("handle", &torrent_alert::handle) ; class_<tracker_alert, bases<torrent_alert>, noncopyable>( "tracker_alert", tracker_alert_doc, no_init ) .def_readonly("url", &tracker_alert::url) ; class_<peer_alert, bases<torrent_alert>, noncopyable>( "peer_alert", no_init ) .def_readonly("ip", &peer_alert::ip) .def_readonly("pid", &peer_alert::pid) ; class_<tracker_error_alert, bases<tracker_alert>, noncopyable>( "tracker_error_alert", tracker_error_alert_doc, no_init ) .def_readonly("times_in_row", &tracker_error_alert::times_in_row) .def_readonly("status_code", &tracker_error_alert::status_code) ; class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>( "tracker_warning_alert", tracker_warning_alert_doc, no_init ); class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>( "tracker_reply_alert", tracker_reply_alert_doc, no_init ) .def_readonly("num_peers", &tracker_reply_alert::num_peers) ; class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>( "tracker_announce_alert", tracker_announce_alert_doc, no_init ); class_<hash_failed_alert, bases<torrent_alert>, noncopyable>( "hash_failed_alert", hash_failed_alert_doc, no_init ) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<peer_alert>, noncopyable>( "peer_ban_alert", peer_ban_alert_doc, no_init ); class_<peer_error_alert, bases<peer_alert>, noncopyable>( "peer_error_alert", peer_error_alert_doc, no_init ); class_<invalid_request_alert, bases<peer_alert>, noncopyable>( "invalid_request_alert", invalid_request_alert_doc, no_init ) .def_readonly("request", &invalid_request_alert::request) ; class_<peer_request>("peer_request", peer_request_doc) .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>( "torrent_finished_alert", torrent_finished_alert_doc, no_init ); class_<piece_finished_alert, bases<torrent_alert>, noncopyable>( "piece_finished_alert", piece_finished_alert_doc, no_init ) .def_readonly("piece_index", &piece_finished_alert::piece_index) ; class_<block_finished_alert, bases<peer_alert>, noncopyable>( "block_finished_alert", block_finished_alert_doc, no_init ) .def_readonly("block_index", &block_finished_alert::block_index) .def_readonly("piece_index", &block_finished_alert::piece_index) ; class_<block_downloading_alert, bases<peer_alert>, noncopyable>( "block_downloading_alert", block_downloading_alert_doc, no_init ) .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg) .def_readonly("block_index", &block_downloading_alert::block_index) .def_readonly("piece_index", &block_downloading_alert::piece_index) ; class_<storage_moved_alert, bases<torrent_alert>, noncopyable>( "storage_moved_alert", storage_moved_alert_doc, no_init ); class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>( "torrent_deleted_alert", torrent_deleted_alert_doc, no_init ); class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>( "torrent_paused_alert", torrent_paused_alert_doc, no_init ); class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>( "torrent_checked_alert", torrent_checked_alert_doc, no_init ); class_<url_seed_alert, bases<torrent_alert>, noncopyable>( "url_seed_alert", url_seed_alert_doc, no_init ) .def_readonly("url", &url_seed_alert::url) ; class_<file_error_alert, bases<torrent_alert>, noncopyable>( "file_error_alert", file_error_alert_doc, no_init ) .def_readonly("file", &file_error_alert::file) ; class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>( "metadata_failed_alert", metadata_failed_alert_doc, no_init ); class_<metadata_received_alert, bases<torrent_alert>, noncopyable>( "metadata_received_alert", metadata_received_alert_doc, no_init ); class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", listen_failed_alert_doc, no_init ); class_<listen_succeeded_alert, bases<alert>, noncopyable>( "listen_succeeded_alert", listen_succeeded_alert_doc, no_init ) .def_readonly("endpoint", &listen_succeeded_alert::endpoint) ; class_<portmap_error_alert, bases<alert>, noncopyable>( "portmap_error_alert", portmap_error_alert_doc, no_init ) .def_readonly("mapping", &portmap_error_alert::mapping) .def_readonly("type", &portmap_error_alert::type) ; class_<portmap_alert, bases<alert>, noncopyable>( "portmap_alert", portmap_alert_doc, no_init ) .def_readonly("mapping", &portmap_alert::mapping) .def_readonly("external_port", &portmap_alert::external_port) .def_readonly("type", &portmap_alert::type) ; class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>( "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init ); class_<peer_blocked_alert, bases<alert>, noncopyable>( "peer_blocked_alert", peer_blocked_alert_doc, no_init ) .def_readonly("ip", &peer_blocked_alert::ip) ; class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>( "scrape_reply_alert", scrape_reply_alert_doc, no_init ) .def_readonly("incomplete", &scrape_reply_alert::incomplete) .def_readonly("complete", &scrape_reply_alert::complete) ; class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>( "scrape_failed_alert", scrape_failed_alert_doc, no_init ); class_<udp_error_alert, bases<alert>, noncopyable>( "udp_error_alert", udp_error_alert_doc, no_init ) .def_readonly("endpoint", &udp_error_alert::endpoint) ; class_<external_ip_alert, bases<alert>, noncopyable>( "external_ip_alert", external_ip_alert_doc, no_init ) .def_readonly("external_address", &external_ip_alert::external_address) ; class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_alert", save_resume_data_alert_doc, no_init ) .def_readonly("resume_data", &save_resume_data_alert::resume_data) ; class_<file_renamed_alert, bases<torrent_alert>, noncopyable>( "file_renamed_alert", no_init ) .def_readonly("name", &file_renamed_alert::name) ; class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>( "file_rename_failed_alert", no_init ) .def_readonly("index", &file_rename_failed_alert::index) ; class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>( "torrent_resumed_alert", no_init ); class_<state_changed_alert, bases<torrent_alert>, noncopyable>( "state_changed_alert", no_init ) .def_readonly("state", &state_changed_alert::state) ; class_<dht_reply_alert, bases<tracker_alert>, noncopyable>( "dht_reply_alert", no_init ) .def_readonly("num_peers", &dht_reply_alert::num_peers) ; class_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>( "peer_unsnubbed_alert", no_init ); class_<peer_snubbed_alert, bases<peer_alert>, noncopyable>( "peer_snubbed_alert", no_init ); class_<peer_connect_alert, bases<peer_alert>, noncopyable>( "peer_connect_alert", no_init ); class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>( "peer_disconnected_alert", no_init ); class_<request_dropped_alert, bases<peer_alert>, noncopyable>( "request_dropped_alert", no_init ) .def_readonly("block_index", &request_dropped_alert::block_index) .def_readonly("piece_index", &request_dropped_alert::piece_index) ; class_<block_timeout_alert, bases<peer_alert>, noncopyable>( "block_timeout_alert", no_init ) .def_readonly("block_index", &block_timeout_alert::block_index) .def_readonly("piece_index", &block_timeout_alert::piece_index) ; class_<unwanted_block_alert, bases<peer_alert>, noncopyable>( "unwanted_block_alert", no_init ) .def_readonly("block_index", &unwanted_block_alert::block_index) .def_readonly("piece_index", &unwanted_block_alert::piece_index) ; class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>( "torrent_delete_failed_alert", no_init ); class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_failed_alert", no_init ); } <commit_msg>add tracker_error_alert::msg to bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; extern char const* alert_doc; extern char const* alert_msg_doc; extern char const* alert_severity_doc; extern char const* torrent_alert_doc; extern char const* tracker_alert_doc; extern char const* tracker_error_alert_doc; extern char const* tracker_warning_alert_doc; extern char const* tracker_reply_alert_doc; extern char const* tracker_announce_alert_doc; extern char const* hash_failed_alert_doc; extern char const* peer_ban_alert_doc; extern char const* peer_error_alert_doc; extern char const* invalid_request_alert_doc; extern char const* peer_request_doc; extern char const* torrent_finished_alert_doc; extern char const* piece_finished_alert_doc; extern char const* block_finished_alert_doc; extern char const* block_downloading_alert_doc; extern char const* storage_moved_alert_doc; extern char const* torrent_deleted_alert_doc; extern char const* torrent_paused_alert_doc; extern char const* torrent_checked_alert_doc; extern char const* url_seed_alert_doc; extern char const* file_error_alert_doc; extern char const* metadata_failed_alert_doc; extern char const* metadata_received_alert_doc; extern char const* listen_failed_alert_doc; extern char const* listen_succeeded_alert_doc; extern char const* portmap_error_alert_doc; extern char const* portmap_alert_doc; extern char const* fastresume_rejected_alert_doc; extern char const* peer_blocked_alert_doc; extern char const* scrape_reply_alert_doc; extern char const* scrape_failed_alert_doc; extern char const* udp_error_alert_doc; extern char const* external_ip_alert_doc; extern char const* save_resume_data_alert_doc; void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init) .def("message", &alert::message, alert_msg_doc) .def("what", &alert::what) .def("category", &alert::category) .def("severity", &alert::severity, alert_severity_doc) .def("__str__", &alert::message, alert_msg_doc) ; enum_<alert::severity_t>("severity_levels") .value("debug", alert::debug) .value("info", alert::info) .value("warning", alert::warning) .value("critical", alert::critical) .value("fatal", alert::fatal) .value("none", alert::none) ; enum_<alert::category_t>("category_t") .value("error_notification", alert::error_notification) .value("peer_notification", alert::peer_notification) .value("port_mapping_notification", alert::port_mapping_notification) .value("storage_notification", alert::storage_notification) .value("tracker_notification", alert::tracker_notification) .value("debug_notification", alert::debug_notification) .value("status_notification", alert::status_notification) .value("progress_notification", alert::progress_notification) .value("ip_block_notification", alert::ip_block_notification) .value("all_categories", alert::all_categories) ; } class_<torrent_alert, bases<alert>, noncopyable>( "torrent_alert", torrent_alert_doc, no_init ) .def_readonly("handle", &torrent_alert::handle) ; class_<tracker_alert, bases<torrent_alert>, noncopyable>( "tracker_alert", tracker_alert_doc, no_init ) .def_readonly("url", &tracker_alert::url) ; class_<peer_alert, bases<torrent_alert>, noncopyable>( "peer_alert", no_init ) .def_readonly("ip", &peer_alert::ip) .def_readonly("pid", &peer_alert::pid) ; class_<tracker_error_alert, bases<tracker_alert>, noncopyable>( "tracker_error_alert", tracker_error_alert_doc, no_init ) .def_readonly("msg", &tracker_error_alert::msg) .def_readonly("times_in_row", &tracker_error_alert::times_in_row) .def_readonly("status_code", &tracker_error_alert::status_code) ; class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>( "tracker_warning_alert", tracker_warning_alert_doc, no_init ); class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>( "tracker_reply_alert", tracker_reply_alert_doc, no_init ) .def_readonly("num_peers", &tracker_reply_alert::num_peers) ; class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>( "tracker_announce_alert", tracker_announce_alert_doc, no_init ); class_<hash_failed_alert, bases<torrent_alert>, noncopyable>( "hash_failed_alert", hash_failed_alert_doc, no_init ) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<peer_alert>, noncopyable>( "peer_ban_alert", peer_ban_alert_doc, no_init ); class_<peer_error_alert, bases<peer_alert>, noncopyable>( "peer_error_alert", peer_error_alert_doc, no_init ); class_<invalid_request_alert, bases<peer_alert>, noncopyable>( "invalid_request_alert", invalid_request_alert_doc, no_init ) .def_readonly("request", &invalid_request_alert::request) ; class_<peer_request>("peer_request", peer_request_doc) .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>( "torrent_finished_alert", torrent_finished_alert_doc, no_init ); class_<piece_finished_alert, bases<torrent_alert>, noncopyable>( "piece_finished_alert", piece_finished_alert_doc, no_init ) .def_readonly("piece_index", &piece_finished_alert::piece_index) ; class_<block_finished_alert, bases<peer_alert>, noncopyable>( "block_finished_alert", block_finished_alert_doc, no_init ) .def_readonly("block_index", &block_finished_alert::block_index) .def_readonly("piece_index", &block_finished_alert::piece_index) ; class_<block_downloading_alert, bases<peer_alert>, noncopyable>( "block_downloading_alert", block_downloading_alert_doc, no_init ) .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg) .def_readonly("block_index", &block_downloading_alert::block_index) .def_readonly("piece_index", &block_downloading_alert::piece_index) ; class_<storage_moved_alert, bases<torrent_alert>, noncopyable>( "storage_moved_alert", storage_moved_alert_doc, no_init ); class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>( "torrent_deleted_alert", torrent_deleted_alert_doc, no_init ); class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>( "torrent_paused_alert", torrent_paused_alert_doc, no_init ); class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>( "torrent_checked_alert", torrent_checked_alert_doc, no_init ); class_<url_seed_alert, bases<torrent_alert>, noncopyable>( "url_seed_alert", url_seed_alert_doc, no_init ) .def_readonly("url", &url_seed_alert::url) ; class_<file_error_alert, bases<torrent_alert>, noncopyable>( "file_error_alert", file_error_alert_doc, no_init ) .def_readonly("file", &file_error_alert::file) ; class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>( "metadata_failed_alert", metadata_failed_alert_doc, no_init ); class_<metadata_received_alert, bases<torrent_alert>, noncopyable>( "metadata_received_alert", metadata_received_alert_doc, no_init ); class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", listen_failed_alert_doc, no_init ); class_<listen_succeeded_alert, bases<alert>, noncopyable>( "listen_succeeded_alert", listen_succeeded_alert_doc, no_init ) .def_readonly("endpoint", &listen_succeeded_alert::endpoint) ; class_<portmap_error_alert, bases<alert>, noncopyable>( "portmap_error_alert", portmap_error_alert_doc, no_init ) .def_readonly("mapping", &portmap_error_alert::mapping) .def_readonly("type", &portmap_error_alert::type) ; class_<portmap_alert, bases<alert>, noncopyable>( "portmap_alert", portmap_alert_doc, no_init ) .def_readonly("mapping", &portmap_alert::mapping) .def_readonly("external_port", &portmap_alert::external_port) .def_readonly("type", &portmap_alert::type) ; class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>( "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init ); class_<peer_blocked_alert, bases<alert>, noncopyable>( "peer_blocked_alert", peer_blocked_alert_doc, no_init ) .def_readonly("ip", &peer_blocked_alert::ip) ; class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>( "scrape_reply_alert", scrape_reply_alert_doc, no_init ) .def_readonly("incomplete", &scrape_reply_alert::incomplete) .def_readonly("complete", &scrape_reply_alert::complete) ; class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>( "scrape_failed_alert", scrape_failed_alert_doc, no_init ); class_<udp_error_alert, bases<alert>, noncopyable>( "udp_error_alert", udp_error_alert_doc, no_init ) .def_readonly("endpoint", &udp_error_alert::endpoint) ; class_<external_ip_alert, bases<alert>, noncopyable>( "external_ip_alert", external_ip_alert_doc, no_init ) .def_readonly("external_address", &external_ip_alert::external_address) ; class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_alert", save_resume_data_alert_doc, no_init ) .def_readonly("resume_data", &save_resume_data_alert::resume_data) ; class_<file_renamed_alert, bases<torrent_alert>, noncopyable>( "file_renamed_alert", no_init ) .def_readonly("name", &file_renamed_alert::name) ; class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>( "file_rename_failed_alert", no_init ) .def_readonly("index", &file_rename_failed_alert::index) ; class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>( "torrent_resumed_alert", no_init ); class_<state_changed_alert, bases<torrent_alert>, noncopyable>( "state_changed_alert", no_init ) .def_readonly("state", &state_changed_alert::state) ; class_<dht_reply_alert, bases<tracker_alert>, noncopyable>( "dht_reply_alert", no_init ) .def_readonly("num_peers", &dht_reply_alert::num_peers) ; class_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>( "peer_unsnubbed_alert", no_init ); class_<peer_snubbed_alert, bases<peer_alert>, noncopyable>( "peer_snubbed_alert", no_init ); class_<peer_connect_alert, bases<peer_alert>, noncopyable>( "peer_connect_alert", no_init ); class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>( "peer_disconnected_alert", no_init ); class_<request_dropped_alert, bases<peer_alert>, noncopyable>( "request_dropped_alert", no_init ) .def_readonly("block_index", &request_dropped_alert::block_index) .def_readonly("piece_index", &request_dropped_alert::piece_index) ; class_<block_timeout_alert, bases<peer_alert>, noncopyable>( "block_timeout_alert", no_init ) .def_readonly("block_index", &block_timeout_alert::block_index) .def_readonly("piece_index", &block_timeout_alert::piece_index) ; class_<unwanted_block_alert, bases<peer_alert>, noncopyable>( "unwanted_block_alert", no_init ) .def_readonly("block_index", &unwanted_block_alert::block_index) .def_readonly("piece_index", &unwanted_block_alert::piece_index) ; class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>( "torrent_delete_failed_alert", no_init ); class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_failed_alert", no_init ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b3dvector.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 08:08:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basegfx.hxx" #ifndef _BGFX_VECTOR_B3DVECTOR_HXX #include <basegfx/vector/b3dvector.hxx> #endif #ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX #include <basegfx/matrix/b3dhommatrix.hxx> #endif namespace basegfx { B3DVector& B3DVector::normalize() { double fLen(scalar(*this)); if(!::basegfx::fTools::equalZero(fLen)) { const double fOne(1.0); if(!::basegfx::fTools::equal(fOne, fLen)) { fLen = sqrt(fLen); if(!::basegfx::fTools::equalZero(fLen)) { mfX /= fLen; mfY /= fLen; mfZ /= fLen; } } } return *this; } B3DVector B3DVector::getPerpendicular(const B3DVector& rNormalizedVec) const { B3DVector aNew(*this); aNew = cross(aNew, rNormalizedVec); aNew.normalize(); return aNew; } B3DVector B3DVector::getProjectionOnPlane(const B3DVector& rNormalizedPlane) const { B3DVector aNew(*this); aNew = cross(aNew, rNormalizedPlane); aNew = cross(aNew, rNormalizedPlane); aNew.mfX = mfX - aNew.mfX; aNew.mfY = mfY - aNew.mfY; aNew.mfZ = mfZ - aNew.mfZ; return aNew; } B3DVector& B3DVector::operator*=( const ::basegfx::B3DHomMatrix& rMat ) { const double fTempX( rMat.get(0,0)*mfX + rMat.get(0,1)*mfY + rMat.get(0,2)*mfZ ); const double fTempY( rMat.get(1,0)*mfX + rMat.get(1,1)*mfY + rMat.get(1,2)*mfZ ); const double fTempZ( rMat.get(2,0)*mfX + rMat.get(2,1)*mfY + rMat.get(2,2)*mfZ ); mfX = fTempX; mfY = fTempY; mfZ = fTempZ; return *this; } B3DVector operator*( const ::basegfx::B3DHomMatrix& rMat, const B3DVector& rVec ) { B3DVector aRes( rVec ); return aRes*=rMat; } } // end of namespace basegfx // eof <commit_msg>INTEGRATION: CWS changefileheader (1.7.60); FILE MERGED 2008/04/01 10:48:16 thb 1.7.60.2: #i85898# Stripping all external header guards 2008/03/28 16:05:58 rt 1.7.60.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b3dvector.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basegfx.hxx" #include <basegfx/vector/b3dvector.hxx> #include <basegfx/matrix/b3dhommatrix.hxx> namespace basegfx { B3DVector& B3DVector::normalize() { double fLen(scalar(*this)); if(!::basegfx::fTools::equalZero(fLen)) { const double fOne(1.0); if(!::basegfx::fTools::equal(fOne, fLen)) { fLen = sqrt(fLen); if(!::basegfx::fTools::equalZero(fLen)) { mfX /= fLen; mfY /= fLen; mfZ /= fLen; } } } return *this; } B3DVector B3DVector::getPerpendicular(const B3DVector& rNormalizedVec) const { B3DVector aNew(*this); aNew = cross(aNew, rNormalizedVec); aNew.normalize(); return aNew; } B3DVector B3DVector::getProjectionOnPlane(const B3DVector& rNormalizedPlane) const { B3DVector aNew(*this); aNew = cross(aNew, rNormalizedPlane); aNew = cross(aNew, rNormalizedPlane); aNew.mfX = mfX - aNew.mfX; aNew.mfY = mfY - aNew.mfY; aNew.mfZ = mfZ - aNew.mfZ; return aNew; } B3DVector& B3DVector::operator*=( const ::basegfx::B3DHomMatrix& rMat ) { const double fTempX( rMat.get(0,0)*mfX + rMat.get(0,1)*mfY + rMat.get(0,2)*mfZ ); const double fTempY( rMat.get(1,0)*mfX + rMat.get(1,1)*mfY + rMat.get(1,2)*mfZ ); const double fTempZ( rMat.get(2,0)*mfX + rMat.get(2,1)*mfY + rMat.get(2,2)*mfZ ); mfX = fTempX; mfY = fTempY; mfZ = fTempZ; return *this; } B3DVector operator*( const ::basegfx::B3DHomMatrix& rMat, const B3DVector& rVec ) { B3DVector aRes( rVec ); return aRes*=rMat; } } // end of namespace basegfx // eof <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; extern char const* alert_doc; extern char const* alert_msg_doc; extern char const* alert_severity_doc; extern char const* listen_failed_alert_doc; extern char const* file_error_alert_doc; extern char const* tracker_announce_alert_doc; extern char const* tracker_alert_doc; extern char const* tracker_reply_alert_doc; extern char const* tracker_warning_alert_doc; extern char const* url_seed_alert_doc; extern char const* hash_failed_alert_doc; extern char const* peer_ban_alert_doc; extern char const* peer_error_alert_doc; extern char const* invalid_request_alert_doc; extern char const* peer_request_doc; extern char const* torrent_finished_alert_doc; extern char const* metadata_failed_alert_doc; extern char const* metadata_received_alert_doc; extern char const* fastresume_rejected_alert_doc; void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init) .def( "msg", &alert::msg, return_value_policy<copy_const_reference>() , alert_msg_doc ) .def("severity", &alert::severity, alert_severity_doc) .def( "__str__", &alert::msg, return_value_policy<copy_const_reference>() , alert_msg_doc ) ; enum_<alert::severity_t>("severity_levels") .value("debug", alert::severity_t::debug) .value("info", alert::severity_t::info) .value("warning", alert::severity_t::warning) .value("critical", alert::severity_t::critical) .value("fatal", alert::severity_t::fatal) .value("none", alert::severity_t::none) ; } class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", listen_failed_alert_doc, no_init ); class_<file_error_alert, bases<alert>, noncopyable>( "file_error_alert", file_error_alert_doc, no_init ) .def_readonly("handle", &file_error_alert::handle) ; class_<tracker_announce_alert, bases<alert>, noncopyable>( "tracker_announce_alert", tracker_announce_alert_doc, no_init ) .def_readonly("handle", &tracker_announce_alert::handle) ; class_<tracker_alert, bases<alert>, noncopyable>( "tracker_alert", tracker_alert_doc, no_init ) .def_readonly("handle", &tracker_alert::handle) .def_readonly("times_in_row", &tracker_alert::times_in_row) .def_readonly("status_code", &tracker_alert::status_code) ; class_<tracker_reply_alert, bases<alert>, noncopyable>( "tracker_reply_alert", tracker_reply_alert_doc, no_init ) .def_readonly("handle", &tracker_reply_alert::handle) ; class_<tracker_warning_alert, bases<alert>, noncopyable>( "tracker_warning_alert", tracker_warning_alert_doc, no_init ) .def_readonly("handle", &tracker_warning_alert::handle) ; class_<url_seed_alert, bases<alert>, noncopyable>( "url_seed_alert", url_seed_alert_doc, no_init ) .def_readonly("url", &url_seed_alert::url) ; class_<hash_failed_alert, bases<alert>, noncopyable>( "hash_failed_alert", hash_failed_alert_doc, no_init ) .def_readonly("handle", &hash_failed_alert::handle) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<alert>, noncopyable>( "peer_ban_alert", peer_ban_alert_doc, no_init ) .def_readonly("ip", &peer_ban_alert::ip) .def_readonly("handle", &peer_ban_alert::handle) ; class_<peer_error_alert, bases<alert>, noncopyable>( "peer_error_alert", peer_error_alert_doc, no_init ) .def_readonly("ip", &peer_error_alert::ip) .def_readonly("pid", &peer_error_alert::pid) ; class_<invalid_request_alert, bases<alert>, noncopyable>( "invalid_request_alert", invalid_request_alert_doc, no_init ) .def_readonly("handle", &invalid_request_alert::handle) .def_readonly("ip", &invalid_request_alert::ip) .def_readonly("request", &invalid_request_alert::request) .def_readonly("pid", &invalid_request_alert::pid) ; class_<peer_request>("peer_request", peer_request_doc) .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<alert>, noncopyable>( "torrent_finished_alert", torrent_finished_alert_doc, no_init ) .def_readonly("handle", &torrent_finished_alert::handle) ; class_<metadata_failed_alert, bases<alert>, noncopyable>( "metadata_failed_alert", metadata_failed_alert_doc, no_init ) .def_readonly("handle", &metadata_failed_alert::handle) ; class_<metadata_received_alert, bases<alert>, noncopyable>( "metadata_received_alert", metadata_received_alert_doc, no_init ) .def_readonly("handle", &metadata_received_alert::handle) ; class_<fastresume_rejected_alert, bases<alert>, noncopyable>( "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init ) .def_readonly("handle", &fastresume_rejected_alert::handle) ; } <commit_msg>fixed typo<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; extern char const* alert_doc; extern char const* alert_msg_doc; extern char const* alert_severity_doc; extern char const* listen_failed_alert_doc; extern char const* file_error_alert_doc; extern char const* tracker_announce_alert_doc; extern char const* tracker_alert_doc; extern char const* tracker_reply_alert_doc; extern char const* tracker_warning_alert_doc; extern char const* url_seed_alert_doc; extern char const* hash_failed_alert_doc; extern char const* peer_ban_alert_doc; extern char const* peer_error_alert_doc; extern char const* invalid_request_alert_doc; extern char const* peer_request_doc; extern char const* torrent_finished_alert_doc; extern char const* metadata_failed_alert_doc; extern char const* metadata_received_alert_doc; extern char const* fastresume_rejected_alert_doc; void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init) .def( "msg", &alert::msg, return_value_policy<copy_const_reference>() , alert_msg_doc ) .def("severity", &alert::severity, alert_severity_doc) .def( "__str__", &alert::msg, return_value_policy<copy_const_reference>() , alert_msg_doc ) ; enum_<alert::severity_t>("severity_levels") .value("debug", alert::debug) .value("info", alert::info) .value("warning", alert::warning) .value("critical", alert::critical) .value("fatal", alert::fatal) .value("none", alert::none) ; } class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", listen_failed_alert_doc, no_init ); class_<file_error_alert, bases<alert>, noncopyable>( "file_error_alert", file_error_alert_doc, no_init ) .def_readonly("handle", &file_error_alert::handle) ; class_<tracker_announce_alert, bases<alert>, noncopyable>( "tracker_announce_alert", tracker_announce_alert_doc, no_init ) .def_readonly("handle", &tracker_announce_alert::handle) ; class_<tracker_alert, bases<alert>, noncopyable>( "tracker_alert", tracker_alert_doc, no_init ) .def_readonly("handle", &tracker_alert::handle) .def_readonly("times_in_row", &tracker_alert::times_in_row) .def_readonly("status_code", &tracker_alert::status_code) ; class_<tracker_reply_alert, bases<alert>, noncopyable>( "tracker_reply_alert", tracker_reply_alert_doc, no_init ) .def_readonly("handle", &tracker_reply_alert::handle) ; class_<tracker_warning_alert, bases<alert>, noncopyable>( "tracker_warning_alert", tracker_warning_alert_doc, no_init ) .def_readonly("handle", &tracker_warning_alert::handle) ; class_<url_seed_alert, bases<alert>, noncopyable>( "url_seed_alert", url_seed_alert_doc, no_init ) .def_readonly("url", &url_seed_alert::url) ; class_<hash_failed_alert, bases<alert>, noncopyable>( "hash_failed_alert", hash_failed_alert_doc, no_init ) .def_readonly("handle", &hash_failed_alert::handle) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<alert>, noncopyable>( "peer_ban_alert", peer_ban_alert_doc, no_init ) .def_readonly("ip", &peer_ban_alert::ip) .def_readonly("handle", &peer_ban_alert::handle) ; class_<peer_error_alert, bases<alert>, noncopyable>( "peer_error_alert", peer_error_alert_doc, no_init ) .def_readonly("ip", &peer_error_alert::ip) .def_readonly("pid", &peer_error_alert::pid) ; class_<invalid_request_alert, bases<alert>, noncopyable>( "invalid_request_alert", invalid_request_alert_doc, no_init ) .def_readonly("handle", &invalid_request_alert::handle) .def_readonly("ip", &invalid_request_alert::ip) .def_readonly("request", &invalid_request_alert::request) .def_readonly("pid", &invalid_request_alert::pid) ; class_<peer_request>("peer_request", peer_request_doc) .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<alert>, noncopyable>( "torrent_finished_alert", torrent_finished_alert_doc, no_init ) .def_readonly("handle", &torrent_finished_alert::handle) ; class_<metadata_failed_alert, bases<alert>, noncopyable>( "metadata_failed_alert", metadata_failed_alert_doc, no_init ) .def_readonly("handle", &metadata_failed_alert::handle) ; class_<metadata_received_alert, bases<alert>, noncopyable>( "metadata_received_alert", metadata_received_alert_doc, no_init ) .def_readonly("handle", &metadata_received_alert::handle) ; class_<fastresume_rejected_alert, bases<alert>, noncopyable>( "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init ) .def_readonly("handle", &fastresume_rejected_alert::handle) ; } <|endoftext|>
<commit_before>#include "Halide.h" using namespace Halide; int main(int argc, char* argv[]) { ImageParam in(UInt(8), 3, "input"); float a0 = 0.7; float a1 = 0.2; float a2 = 0.1; Func rec_filter{"rec_filter"}; Var x("x"), y("y"), c("c"); RDom r(2, in.width()-3, 0, in.height()-1); rec_filter(x, y, c) = in(x, y, c); rec_filter(r.x, r.y, c) = cast<uint8_t>(a0*rec_filter(r.x, r.y, c) + a1*rec_filter(r.x-1, r.y, c) + a2*rec_filter(r.x-2, r.y, c)); rec_filter.parallel(y).parallel(c).vectorize(x, 8). rec_filter.update(0).parallel(r.y).parallel(c); rec_filter.compile_to_object("build/generated_fct_recfilter_ref.o", {in}, "recfilter_ref"); rec_filter.compile_to_lowered_stmt("build/generated_fct_recfilter_ref.txt", {in}, Text); return 0; } <commit_msg>Fix recfilter<commit_after>#include "Halide.h" using namespace Halide; int main(int argc, char* argv[]) { ImageParam in(UInt(8), 3, "input"); float a0 = 0.7; float a1 = 0.2; float a2 = 0.1; Func rec_filter{"rec_filter"}; Var x("x"), y("y"), c("c"); RDom r(2, in.width()-3, 0, in.height()-1); rec_filter(x, y, c) = in(x, y, c); rec_filter(r.x, r.y, c) = cast<uint8_t>(a0*rec_filter(r.x, r.y, c) + a1*rec_filter(r.x-1, r.y, c) + a2*rec_filter(r.x-2, r.y, c)); rec_filter.parallel(y).parallel(c).vectorize(x, 8); rec_filter.update(0).parallel(r.y).parallel(c); rec_filter.compile_to_object("build/generated_fct_recfilter_ref.o", {in}, "recfilter_ref"); rec_filter.compile_to_lowered_stmt("build/generated_fct_recfilter_ref.txt", {in}, Text); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "customToolButton.h" #include <QPainter> #include <QStyle> #include <QStyleOptionToolButton> customToolButton::customToolButton(QWidget* parent) : QToolButton(parent) { setMinimumSize(QSize(20, 18)); } void customToolButton::paintEvent(QPaintEvent* event) { Q_UNUSED(event); QPainter painter(this); QStyleOptionToolButton panel; initStyleOption(&panel); style()->drawPrimitive(QStyle::PE_PanelButtonTool, &panel, &painter, this); QRect r = rect(); QFont font; painter.setFont(font); painter.setPen(Qt::gray); QRect rectSize(0, 0, sizeHint().width(), sizeHint().height()); rectSize.moveCenter(r.center()); r = rectSize; r.adjust(0, 0, -1, -1); painter.setPen(Qt::black); painter.setBrush(Qt::black); r.moveLeft(r.left() + 3); font.setBold(true); painter.setFont(font); painter.drawText(r, Qt::AlignVCenter|Qt::TextSingleLine, text()); QImage image(":/icons/resource/downArrow.png"); QRect rectDelta(0, 0, 7, 4); rectDelta.moveRight(r.right() - 4); rectDelta.moveCenter(QPoint(rectDelta.center().x(), r.center().y())); painter.drawImage(rectDelta, image); } QSize customToolButton::sizeHint() const { QFont font; font.setBold(true); QFontMetrics fm(font); int width = fm.width(text()); if(width <= (160 - 8 - 9)) return QSize(width+8+9, 18); else return QSize(160, 18); } <commit_msg>looks fix on linux<commit_after>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "customToolButton.h" #include <QPainter> #include <QStyle> #include <QStyleOptionToolButton> customToolButton::customToolButton(QWidget* parent) : QToolButton(parent) { setMinimumSize(QSize(20, 18)); } void customToolButton::paintEvent(QPaintEvent* event) { Q_UNUSED(event); QPainter painter(this); if(underMouse()) { QStyleOptionToolButton panel; initStyleOption(&panel); style()->drawPrimitive(QStyle::PE_PanelButtonTool, &panel, &painter, this); } QRect r = rect(); QFont font; painter.setFont(font); painter.setPen(Qt::gray); QRect rectSize(0, 0, sizeHint().width(), sizeHint().height()); rectSize.moveCenter(r.center()); r = rectSize; r.adjust(0, 0, -1, -1); painter.setPen(Qt::black); painter.setBrush(Qt::black); r.moveLeft(r.left() + 3); font.setBold(true); painter.setFont(font); painter.drawText(r, Qt::AlignVCenter|Qt::TextSingleLine, text()); QImage image(":/icons/resource/downArrow.png"); QRect rectDelta(0, 0, 7, 4); rectDelta.moveRight(r.right() - 4); rectDelta.moveCenter(QPoint(rectDelta.center().x(), r.center().y())); painter.drawImage(rectDelta, image); } QSize customToolButton::sizeHint() const { QFont font; font.setBold(true); QFontMetrics fm(font); int width = fm.width(text()); if(width <= (160 - 8 - 9)) return QSize(width+8+9, 18); else return QSize(160, 18); } <|endoftext|>
<commit_before>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** v4l2compress_jpeg.cpp ** ** Read YUYC from a V4L2 capture -> compress in JPEG using libjpeg -> write to a V4L2 output device ** ** -------------------------------------------------------------------------*/ #include <unistd.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <linux/videodev2.h> #include <sys/ioctl.h> #include <stdint.h> #include <signal.h> #include <fstream> #include "logger.h" #include "V4l2Device.h" #include "V4l2Capture.h" #include "V4l2Output.h" #include <jpeglib.h> int stop=0; /* --------------------------------------------------------------------------- ** SIGINT handler ** -------------------------------------------------------------------------*/ void sighandler(int) { printf("SIGINT\n"); stop =1; } void jpeg_setsubsampling(struct jpeg_compress_struct& cinfo, unsigned int subsampling) { if (subsampling == 0) { cinfo.comp_info[0].h_samp_factor = 1; cinfo.comp_info[0].v_samp_factor = 1; } else if (subsampling == 1) { cinfo.comp_info[0].h_samp_factor = 2; cinfo.comp_info[0].v_samp_factor = 1; } else if (subsampling == 2) { cinfo.comp_info[0].h_samp_factor = 2; cinfo.comp_info[0].v_samp_factor = 2; } cinfo.comp_info[1].h_samp_factor = 1; cinfo.comp_info[1].v_samp_factor = 1; cinfo.comp_info[2].h_samp_factor = 1; cinfo.comp_info[2].v_samp_factor = 1; } /* --------------------------------------------------------------------------- ** convert yuyv -> jpeg ** -------------------------------------------------------------------------*/ unsigned long yuyv2jpeg(char* image_buffer, unsigned int width, unsigned int height, unsigned int quality, unsigned int subsampling) { struct jpeg_error_mgr jerr; struct jpeg_compress_struct cinfo; jpeg_create_compress(&cinfo); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.err = jpeg_std_error(&jerr); unsigned char* dest = NULL; unsigned long destsize = 0; jpeg_mem_dest(&cinfo, &dest, &destsize); jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_setsubsampling(cinfo,subsampling); jpeg_start_compress(&cinfo, TRUE); unsigned char bufline[cinfo.image_width * 3]; while (cinfo.next_scanline < cinfo.image_height) { // convert line from YUYV -> YUV for (unsigned int i = 0; i < cinfo.image_width; i += 2) { unsigned int base = cinfo.next_scanline*cinfo.image_width * 2 ; bufline[i*3 ] = image_buffer[base + i*2 ]; bufline[i*3+1] = image_buffer[base + i*2+1]; bufline[i*3+2] = image_buffer[base + i*2+3]; bufline[i*3+3] = image_buffer[base + i*2+2]; bufline[i*3+4] = image_buffer[base + i*2+1]; bufline[i*3+5] = image_buffer[base + i*2+3]; } JSAMPROW row = bufline; jpeg_write_scanlines(&cinfo, &row, 1); } jpeg_finish_compress(&cinfo); if (dest != NULL) { if (destsize < width*height*2) { memcpy(image_buffer, dest, destsize); } else { LOG(WARN) << "Buffer to small size:" << width*height*2 << " " << destsize; } free(dest); } jpeg_destroy_compress(&cinfo); return destsize; } /* --------------------------------------------------------------------------- ** main ** -------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { int verbose=0; const char *in_devname = "/dev/video0"; const char *out_devname = "/dev/video1"; int width = 640; int height = 480; int fps = 10; int quality = 99; int subsampling = 1; V4l2Access::IoType ioTypeIn = V4l2Access::IOTYPE_MMAP; V4l2Access::IoType ioTypeOut = V4l2Access::IOTYPE_MMAP; int c = 0; while ((c = getopt (argc, argv, "h" "W:H:F:" "rw" "q:s:")) != -1) { switch (c) { case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; // capture options case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'F': fps = atoi(optarg); break; case 'r': ioTypeIn = V4l2Access::IOTYPE_READWRITE; break; // output options case 'w': ioTypeOut = V4l2Access::IOTYPE_READWRITE; break; // JPEG options case 'q': quality = atoi(optarg); break; case 's': subsampling = atoi(optarg); break; case 'h': { std::cout << argv[0] << " [-v[v]] [-W width] [-H height] source_device dest_device" << std::endl; std::cout << "\t -v : verbose " << std::endl; std::cout << "\t -vv : very verbose " << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; std::cout << "\t -w : V4L2 capture using write interface (default use memory mapped buffers)" << std::endl; std::cout << "\tcompressor options" << std::endl; std::cout << "\t -q <quality> : JPEG quality" << std::endl; std::cout << "\t -s <subsampling> : JPEG sumsampling (0->JPEG 4:4:4 0->JPEG 4:2:2 0->JPEG 4:2:0)" << std::endl; std::cout << "\t source_device : V4L2 capture device (default "<< in_devname << ")" << std::endl; std::cout << "\t dest_device : V4L2 output device (default "<< out_devname << ")" << std::endl; exit(0); } } } if (optind<argc) { in_devname = argv[optind]; optind++; } if (optind<argc) { out_devname = argv[optind]; optind++; } // initialize log4cpp initLogger(verbose); // init V4L2 capture interface V4L2DeviceParameters param(in_devname,V4L2_PIX_FMT_YUYV,width,height,fps,verbose); V4l2Capture* videoCapture = V4l2Capture::create(param, ioTypeIn); if (videoCapture == NULL) { LOG(WARN) << "Cannot create V4L2 capture interface for device:" << in_devname; } else { // init V4L2 output interface V4L2DeviceParameters outparam(out_devname, V4L2_PIX_FMT_JPEG, videoCapture->getWidth(), videoCapture->getHeight(), 0, verbose); V4l2Output* videoOutput = V4l2Output::create(outparam, ioTypeOut); if (videoOutput == NULL) { LOG(WARN) << "Cannot create V4L2 output interface for device:" << out_devname; } else { timeval tv; LOG(NOTICE) << "Start Compressing " << in_devname << " to " << out_devname; signal(SIGINT,sighandler); while (!stop) { tv.tv_sec=1; tv.tv_usec=0; int ret = videoCapture->isReadable(&tv); if (ret == 1) { char buffer[videoCapture->getBufferSize()]; int rsize = videoCapture->read(buffer, sizeof(buffer)); if (rsize == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } else { // compress rsize = yuyv2jpeg(buffer, width, height, quality, subsampling); int wsize = videoOutput->write(buffer, rsize); LOG(DEBUG) << "Copied " << rsize << " " << wsize; } } else if (ret == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } } delete videoOutput; } delete videoCapture; } return 0; } <commit_msg>fix jpeg compressor setting YUV colorspace<commit_after>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** v4l2compress_jpeg.cpp ** ** Read YUYC from a V4L2 capture -> compress in JPEG using libjpeg -> write to a V4L2 output device ** ** -------------------------------------------------------------------------*/ #include <unistd.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <linux/videodev2.h> #include <sys/ioctl.h> #include <stdint.h> #include <signal.h> #include <fstream> #include "logger.h" #include "V4l2Device.h" #include "V4l2Capture.h" #include "V4l2Output.h" #include <jpeglib.h> int stop=0; /* --------------------------------------------------------------------------- ** SIGINT handler ** -------------------------------------------------------------------------*/ void sighandler(int) { printf("SIGINT\n"); stop =1; } /* --------------------------------------------------------------------------- ** convert yuyv -> jpeg ** -------------------------------------------------------------------------*/ unsigned long yuyv2jpeg(char* image_buffer, unsigned int width, unsigned int height, unsigned int quality) { struct jpeg_error_mgr jerr; struct jpeg_compress_struct cinfo; jpeg_create_compress(&cinfo); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_YCbCr; cinfo.err = jpeg_std_error(&jerr); unsigned char* dest = NULL; unsigned long destsize = 0; jpeg_mem_dest(&cinfo, &dest, &destsize); jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char bufline[cinfo.image_width * 3]; while (cinfo.next_scanline < cinfo.image_height) { // convert line from YUYV -> YUV for (unsigned int i = 0; i < cinfo.image_width; i += 2) { unsigned int base = cinfo.next_scanline*cinfo.image_width * 2 ; bufline[i*3 ] = image_buffer[base + i*2 ]; bufline[i*3+1] = image_buffer[base + i*2+1]; bufline[i*3+2] = image_buffer[base + i*2+3]; bufline[i*3+3] = image_buffer[base + i*2+2]; bufline[i*3+4] = image_buffer[base + i*2+1]; bufline[i*3+5] = image_buffer[base + i*2+3]; } JSAMPROW row = bufline; jpeg_write_scanlines(&cinfo, &row, 1); } jpeg_finish_compress(&cinfo); if (dest != NULL) { if (destsize < width*height*2) { memcpy(image_buffer, dest, destsize); } else { LOG(WARN) << "Buffer to small size:" << width*height*2 << " " << destsize; } free(dest); } jpeg_destroy_compress(&cinfo); return destsize; } /* --------------------------------------------------------------------------- ** main ** -------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { int verbose=0; const char *in_devname = "/dev/video0"; const char *out_devname = "/dev/video1"; int width = 640; int height = 480; int fps = 25; int quality = 99; V4l2Access::IoType ioTypeIn = V4l2Access::IOTYPE_MMAP; V4l2Access::IoType ioTypeOut = V4l2Access::IOTYPE_MMAP; int c = 0; while ((c = getopt (argc, argv, "h" "W:H:F:" "rw" "q:")) != -1) { switch (c) { case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; // capture options case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'F': fps = atoi(optarg); break; case 'r': ioTypeIn = V4l2Access::IOTYPE_READWRITE; break; // output options case 'w': ioTypeOut = V4l2Access::IOTYPE_READWRITE; break; // JPEG options case 'q': quality = atoi(optarg); break; case 'h': { std::cout << argv[0] << " [-v[v]] [-W width] [-H height] source_device dest_device" << std::endl; std::cout << "\t -v : verbose " << std::endl; std::cout << "\t -vv : very verbose " << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; std::cout << "\t -w : V4L2 capture using write interface (default use memory mapped buffers)" << std::endl; std::cout << "\tcompressor options" << std::endl; std::cout << "\t -q <quality> : JPEG quality" << std::endl; std::cout << "\t source_device : V4L2 capture device (default "<< in_devname << ")" << std::endl; std::cout << "\t dest_device : V4L2 output device (default "<< out_devname << ")" << std::endl; exit(0); } } } if (optind<argc) { in_devname = argv[optind]; optind++; } if (optind<argc) { out_devname = argv[optind]; optind++; } // initialize log4cpp initLogger(verbose); // init V4L2 capture interface V4L2DeviceParameters param(in_devname,V4L2_PIX_FMT_YUYV,width,height,fps,verbose); V4l2Capture* videoCapture = V4l2Capture::create(param, ioTypeIn); if (videoCapture == NULL) { LOG(WARN) << "Cannot create V4L2 capture interface for device:" << in_devname; } else { // init V4L2 output interface V4L2DeviceParameters outparam(out_devname, V4L2_PIX_FMT_JPEG, videoCapture->getWidth(), videoCapture->getHeight(), 0, verbose); V4l2Output* videoOutput = V4l2Output::create(outparam, ioTypeOut); if (videoOutput == NULL) { LOG(WARN) << "Cannot create V4L2 output interface for device:" << out_devname; } else { timeval tv; LOG(NOTICE) << "Start Compressing " << in_devname << " to " << out_devname; signal(SIGINT,sighandler); while (!stop) { tv.tv_sec=1; tv.tv_usec=0; int ret = videoCapture->isReadable(&tv); if (ret == 1) { char buffer[videoCapture->getBufferSize()]; int rsize = videoCapture->read(buffer, sizeof(buffer)); if (rsize == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } else { // compress rsize = yuyv2jpeg(buffer, videoOutput->getWidth(), videoOutput->getHeight(), quality); int wsize = videoOutput->write(buffer, rsize); LOG(DEBUG) << "Copied " << rsize << " " << wsize; } } else if (ret == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } } delete videoOutput; } delete videoCapture; } return 0; } <|endoftext|>
<commit_before>#include <ffigen/process/code_entity/fundamental_type.hpp> #include <ffigen/utility/logger.hpp> #include <unordered_map> namespace ffigen { using namespace utility::logs; typedef std::unordered_map<std::string, std::string> ffi_type_map; static ffi_type_map clang_type_to_ffi_types; static ffi_type_map & get_clang_to_ffi_mapping() { if (clang_type_to_ffi_types.empty()) { clang_type_to_ffi_types["unsigned char"] = "uchar"; clang_type_to_ffi_types["char"] = "char"; clang_type_to_ffi_types["signed char"] = "char"; clang_type_to_ffi_types["short"] = "short"; clang_type_to_ffi_types["unsigned short"] = "ushort"; clang_type_to_ffi_types["int"] = "int"; clang_type_to_ffi_types["unsigned int"] = "uint"; clang_type_to_ffi_types["long"] = "long"; clang_type_to_ffi_types["unsigned long"] = "ulong"; clang_type_to_ffi_types["long long"] = "longlong"; clang_type_to_ffi_types["unsigned long long"] = "ulonglong"; clang_type_to_ffi_types["size_t"] = "size_t"; clang_type_to_ffi_types["ptrdiff_t"] = "size_t"; clang_type_to_ffi_types["int8_t"] = "int8"; clang_type_to_ffi_types["uint8_t"] = "uint8"; clang_type_to_ffi_types["int16_t"] = "int16"; clang_type_to_ffi_types["uint16_t"] = "uint16"; clang_type_to_ffi_types["int32_t"] = "int32"; clang_type_to_ffi_types["uint32_t"] = "uint32"; clang_type_to_ffi_types["int64_t"] = "int64"; clang_type_to_ffi_types["uint64_t"] = "uint64"; clang_type_to_ffi_types["float"] = "float"; clang_type_to_ffi_types["double"] = "double"; clang_type_to_ffi_types["void"] = "void"; // whitelist variadic arg types to void TODO: bit of a hack, not sure how to handle this case // in generic manner clang_type_to_ffi_types["va_list"] = "void"; clang_type_to_ffi_types["__builtin_va_list"] = "void"; clang_type_to_ffi_types["__gnuc_va_list"] = "void"; } return clang_type_to_ffi_types; } fundamental_type_entity::fundamental_type_entity(std::string const& c_type) : fundamental_type_entity::base_type(c_type, "") { ffi_type_map & types = get_clang_to_ffi_mapping(); ffi_type = "'" + types[c_type] + "'"; } bool fundamental_type_entity::is_supported(std::string const& c_type) { ffi_type_map & types = get_clang_to_ffi_mapping(); return types.find(c_type) != types.end(); } fundamental_type_entity fundamental_type_entity::make_int_from_size(int64_t size) { switch (size) { case 1: return fundamental_type_entity("int8_t"); case 2: return fundamental_type_entity("int16_t"); case 4: return fundamental_type_entity("int32_t"); case 8: return fundamental_type_entity("int64_t"); default: warning() << "WARNING: Unknown integer size '" << size << "' found in fundamental_type_entity::make_int_from_size()." << std::endl; return fundamental_type_entity("int"); } } }<commit_msg>Add long double type. Don't know if correct for node-ffi.<commit_after>#include <ffigen/process/code_entity/fundamental_type.hpp> #include <ffigen/utility/logger.hpp> #include <unordered_map> namespace ffigen { using namespace utility::logs; typedef std::unordered_map<std::string, std::string> ffi_type_map; static ffi_type_map clang_type_to_ffi_types; static ffi_type_map & get_clang_to_ffi_mapping() { if (clang_type_to_ffi_types.empty()) { clang_type_to_ffi_types["unsigned char"] = "uchar"; clang_type_to_ffi_types["char"] = "char"; clang_type_to_ffi_types["signed char"] = "char"; clang_type_to_ffi_types["short"] = "short"; clang_type_to_ffi_types["unsigned short"] = "ushort"; clang_type_to_ffi_types["int"] = "int"; clang_type_to_ffi_types["unsigned int"] = "uint"; clang_type_to_ffi_types["long"] = "long"; clang_type_to_ffi_types["unsigned long"] = "ulong"; clang_type_to_ffi_types["long long"] = "longlong"; clang_type_to_ffi_types["unsigned long long"] = "ulonglong"; clang_type_to_ffi_types["long double"] = "longdouble"; clang_type_to_ffi_types["size_t"] = "size_t"; clang_type_to_ffi_types["ptrdiff_t"] = "size_t"; clang_type_to_ffi_types["int8_t"] = "int8"; clang_type_to_ffi_types["uint8_t"] = "uint8"; clang_type_to_ffi_types["int16_t"] = "int16"; clang_type_to_ffi_types["uint16_t"] = "uint16"; clang_type_to_ffi_types["int32_t"] = "int32"; clang_type_to_ffi_types["uint32_t"] = "uint32"; clang_type_to_ffi_types["int64_t"] = "int64"; clang_type_to_ffi_types["uint64_t"] = "uint64"; clang_type_to_ffi_types["float"] = "float"; clang_type_to_ffi_types["double"] = "double"; clang_type_to_ffi_types["void"] = "void"; // whitelist variadic arg types to void TODO: bit of a hack, not sure how to handle this case // in generic manner clang_type_to_ffi_types["va_list"] = "void"; clang_type_to_ffi_types["__builtin_va_list"] = "void"; clang_type_to_ffi_types["__gnuc_va_list"] = "void"; } return clang_type_to_ffi_types; } fundamental_type_entity::fundamental_type_entity(std::string const& c_type) : fundamental_type_entity::base_type(c_type, "") { ffi_type_map & types = get_clang_to_ffi_mapping(); ffi_type = "'" + types[c_type] + "'"; } bool fundamental_type_entity::is_supported(std::string const& c_type) { ffi_type_map & types = get_clang_to_ffi_mapping(); return types.find(c_type) != types.end(); } fundamental_type_entity fundamental_type_entity::make_int_from_size(int64_t size) { switch (size) { case 1: return fundamental_type_entity("int8_t"); case 2: return fundamental_type_entity("int16_t"); case 4: return fundamental_type_entity("int32_t"); case 8: return fundamental_type_entity("int64_t"); default: warning() << "WARNING: Unknown integer size '" << size << "' found in fundamental_type_entity::make_int_from_size()." << std::endl; return fundamental_type_entity("int"); } } }<|endoftext|>