answer
stringlengths
15
1.25M
module WCAPI class SruSearchResponse include WCAPI::XPath attr_accessor :header, :records, :raw def initialize(doc) #super doc @raw = doc parse_marcxml(doc) end def parse_marcxml(xml) @header = {} _title = "" #this is an array _author = Array.new() _link = "" _id = "" _citation = "" _summary = "" _xml = xml _rechash = {} _records = Array.new() _x = 0 xml = xml.gsub('<?xml-stylesheet type="text/xsl" href="/webservices/catalog/xsl/<API key>.xsl"?>', "") begin require 'rexml/document' doc = REXML::Document.new(xml) rescue #likely some kind of xml error end @header["numberOfRecords"] = xpath_get_text(xpath_first(doc, "//numberOfRecords")) @header["recordSchema"] = xpath_get_text(xpath_first(doc, "//recordSchema")) @header["nextRecordPosition"] = xpath_get_text(xpath_first(doc, "//nextRecordPosition")) @header["maxiumumRecords"] = xpath_get_text(xpath_first(doc, "//maximumRecords")) @header["startRecord"] = xpath_get_text(xpath_first(doc, "//startRecord")) nodes = xpath_all(doc, "//records/record/recordData/record") nodes.each { |item | _title = xpath_get_text(xpath_first(item, "datafield[@tag='245']/subfield[@code='a']")) if xpath_first(item, "datafield[@tag='100']") != nil xpath_all(item, "datafield[@tag='100']/subfield[@code='a']").each { |i| _author.push(xpath_get_text(i)) } end if xpath_first(item, "datafield[@tag='700']" ) != nil xpath_all(item, "datafield[@tag='700']/subfield[@code='a']").each { |i| _author.push(xpath_get_text(i)) } end if xpath_first(item, "controlfield[@tag='001']") != nil _id = xpath_get_text(xpath_first(item, "controlfield[@tag='001']")) _link = 'http: end if xpath_first(item, "datafield[@tag='520']") != nil _summary = xpath_get_text(xpath_first(item, "datafield[@tag='520']/subfield[@code='a']")) else if xpath_first(item, "datafield[@tag='500']") != nil _summary = xpath_get_text(xpath_first(item, "datafield[@tag='500']/subfield[@code='a']")) end end _rechash = {:title => _title, :author => _author, :link => _link, :id => _id, :citation => _citation, :summary => _summary, :xml => item.to_s} _records.push(_rechash) } @records = _records end end end
// <API key>.h // ASCircularMenuDemo #import <UIKit/UIKit.h> #import "ASCircularMenu.h" @interface <API key> : UIViewController<<API key>> @property (nonatomic,strong) IBOutlet UIStepper *stepper; @property (nonatomic,strong) IBOutlet UIImageView *backgroundImageView; @property (nonatomic,strong) ASCircularMenu *menu; - (IBAction)<API key>:(UISwitch *)sender; - (IBAction)<API key>:(UISwitch *)sender; - (IBAction)stepperValueChanged:(UIStepper *)sender; @end
#include <esd.h> #include "qemu-common.h" #include "audio.h" #include <signal.h> #define AUDIO_CAP "esd" #include "audio_int.h" #include "audio_pt_int.h" typedef struct { HWVoiceOut hw; int done; int live; int decr; int rpos; void *pcm_buf; int fd; struct audio_pt pt; } ESDVoiceOut; typedef struct { HWVoiceIn hw; int done; int dead; int incr; int wpos; void *pcm_buf; int fd; struct audio_pt pt; } ESDVoiceIn; static struct { int samples; int divisor; char *dac_host; char *adc_host; } conf = { .samples = 1024, .divisor = 2, }; static void GCC_FMT_ATTR (2, 3) qesd_logerr (int err, const char *fmt, ...) { va_list ap; va_start (ap, fmt); AUD_vlog (AUDIO_CAP, fmt, ap); va_end (ap); AUD_log (AUDIO_CAP, "Reason: %s\n", strerror (err)); } /* playback */ static void *qesd_thread_out (void *arg) { ESDVoiceOut *esd = arg; HWVoiceOut *hw = &esd->hw; int threshold; threshold = conf.divisor ? hw->samples / conf.divisor : 0; if (audio_pt_lock (&esd->pt, AUDIO_FUNC)) { return NULL; } for (;;) { int decr, to_mix, rpos; for (;;) { if (esd->done) { goto exit; } if (esd->live > threshold) { break; } if (audio_pt_wait (&esd->pt, AUDIO_FUNC)) { goto exit; } } decr = to_mix = esd->live; rpos = hw->rpos; if (audio_pt_unlock (&esd->pt, AUDIO_FUNC)) { return NULL; } while (to_mix) { ssize_t written; int chunk = audio_MIN (to_mix, hw->samples - rpos); struct st_sample *src = hw->mix_buf + rpos; hw->clip (esd->pcm_buf, src, chunk); again: written = write (esd->fd, esd->pcm_buf, chunk << hw->info.shift); if (written == -1) { if (errno == EINTR || errno == EAGAIN) { goto again; } qesd_logerr (errno, "write failed\n"); return NULL; } if (written != chunk << hw->info.shift) { int wsamples = written >> hw->info.shift; int wbytes = wsamples << hw->info.shift; if (wbytes != written) { dolog ("warning: Misaligned write %d (requested %d), " "alignment %d\n", wbytes, written, hw->info.align + 1); } to_mix -= wsamples; rpos = (rpos + wsamples) % hw->samples; break; } rpos = (rpos + chunk) % hw->samples; to_mix -= chunk; } if (audio_pt_lock (&esd->pt, AUDIO_FUNC)) { return NULL; } esd->rpos = rpos; esd->live -= decr; esd->decr += decr; } exit: audio_pt_unlock (&esd->pt, AUDIO_FUNC); return NULL; } static int qesd_run_out (HWVoiceOut *hw) { int live, decr; ESDVoiceOut *esd = (ESDVoiceOut *) hw; if (audio_pt_lock (&esd->pt, AUDIO_FUNC)) { return 0; } live = <API key> (hw); decr = audio_MIN (live, esd->decr); esd->decr -= decr; esd->live = live - decr; hw->rpos = esd->rpos; if (esd->live > 0) { <API key> (&esd->pt, AUDIO_FUNC); } else { audio_pt_unlock (&esd->pt, AUDIO_FUNC); } return decr; } static int qesd_write (SWVoiceOut *sw, void *buf, int len) { return audio_pcm_sw_write (sw, buf, len); } static int qesd_init_out (HWVoiceOut *hw, struct audsettings *as) { ESDVoiceOut *esd = (ESDVoiceOut *) hw; struct audsettings obt_as = *as; int esdfmt = ESD_STREAM | ESD_PLAY; int err; sigset_t set, old_set; sigfillset (&set); esdfmt |= (as->nchannels == 2) ? ESD_STEREO : ESD_MONO; switch (as->fmt) { case AUD_FMT_S8: case AUD_FMT_U8: esdfmt |= ESD_BITS8; obt_as.fmt = AUD_FMT_U8; break; case AUD_FMT_S32: case AUD_FMT_U32: dolog ("Will use 16 instead of 32 bit samples\n"); case AUD_FMT_S16: case AUD_FMT_U16: deffmt: esdfmt |= ESD_BITS16; obt_as.fmt = AUD_FMT_S16; break; default: dolog ("Internal logic error: Bad audio format %d\n", as->fmt); goto deffmt; } obt_as.endianness = <API key>; audio_pcm_init_info (&hw->info, &obt_as); hw->samples = conf.samples; esd->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift); if (!esd->pcm_buf) { dolog ("Could not allocate buffer (%d bytes)\n", hw->samples << hw->info.shift); return -1; } esd->fd = -1; err = pthread_sigmask (SIG_BLOCK, &set, &old_set); if (err) { qesd_logerr (err, "pthread_sigmask failed\n"); goto fail1; } esd->fd = esd_play_stream (esdfmt, as->freq, conf.dac_host, NULL); if (esd->fd < 0) { qesd_logerr (errno, "esd_play_stream failed\n"); goto fail2; } if (audio_pt_init (&esd->pt, qesd_thread_out, esd, AUDIO_CAP, AUDIO_FUNC)) { goto fail3; } err = pthread_sigmask (SIG_SETMASK, &old_set, NULL); if (err) { qesd_logerr (err, "pthread_sigmask(restore) failed\n"); } return 0; fail3: if (close (esd->fd)) { qesd_logerr (errno, "%s: close on esd socket(%d) failed\n", AUDIO_FUNC, esd->fd); } esd->fd = -1; fail2: err = pthread_sigmask (SIG_SETMASK, &old_set, NULL); if (err) { qesd_logerr (err, "pthread_sigmask(restore) failed\n"); } fail1: qemu_free (esd->pcm_buf); esd->pcm_buf = NULL; return -1; } static void qesd_fini_out (HWVoiceOut *hw) { void *ret; ESDVoiceOut *esd = (ESDVoiceOut *) hw; audio_pt_lock (&esd->pt, AUDIO_FUNC); esd->done = 1; <API key> (&esd->pt, AUDIO_FUNC); audio_pt_join (&esd->pt, &ret, AUDIO_FUNC); if (esd->fd >= 0) { if (close (esd->fd)) { qesd_logerr (errno, "failed to close esd socket\n"); } esd->fd = -1; } audio_pt_fini (&esd->pt, AUDIO_FUNC); qemu_free (esd->pcm_buf); esd->pcm_buf = NULL; } static int qesd_ctl_out (HWVoiceOut *hw, int cmd, ...) { (void) hw; (void) cmd; return 0; } /* capture */ static void *qesd_thread_in (void *arg) { ESDVoiceIn *esd = arg; HWVoiceIn *hw = &esd->hw; int threshold; threshold = conf.divisor ? hw->samples / conf.divisor : 0; if (audio_pt_lock (&esd->pt, AUDIO_FUNC)) { return NULL; } for (;;) { int incr, to_grab, wpos; for (;;) { if (esd->done) { goto exit; } if (esd->dead > threshold) { break; } if (audio_pt_wait (&esd->pt, AUDIO_FUNC)) { goto exit; } } incr = to_grab = esd->dead; wpos = hw->wpos; if (audio_pt_unlock (&esd->pt, AUDIO_FUNC)) { return NULL; } while (to_grab) { ssize_t nread; int chunk = audio_MIN (to_grab, hw->samples - wpos); void *buf = advance (esd->pcm_buf, wpos); again: nread = read (esd->fd, buf, chunk << hw->info.shift); if (nread == -1) { if (errno == EINTR || errno == EAGAIN) { goto again; } qesd_logerr (errno, "read failed\n"); return NULL; } if (nread != chunk << hw->info.shift) { int rsamples = nread >> hw->info.shift; int rbytes = rsamples << hw->info.shift; if (rbytes != nread) { dolog ("warning: Misaligned write %d (requested %d), " "alignment %d\n", rbytes, nread, hw->info.align + 1); } to_grab -= rsamples; wpos = (wpos + rsamples) % hw->samples; break; } hw->conv (hw->conv_buf + wpos, buf, nread >> hw->info.shift, &nominal_volume); wpos = (wpos + chunk) % hw->samples; to_grab -= chunk; } if (audio_pt_lock (&esd->pt, AUDIO_FUNC)) { return NULL; } esd->wpos = wpos; esd->dead -= incr; esd->incr += incr; } exit: audio_pt_unlock (&esd->pt, AUDIO_FUNC); return NULL; } static int qesd_run_in (HWVoiceIn *hw) { int live, incr, dead; ESDVoiceIn *esd = (ESDVoiceIn *) hw; if (audio_pt_lock (&esd->pt, AUDIO_FUNC)) { return 0; } live = <API key> (hw); dead = hw->samples - live; incr = audio_MIN (dead, esd->incr); esd->incr -= incr; esd->dead = dead - incr; hw->wpos = esd->wpos; if (esd->dead > 0) { <API key> (&esd->pt, AUDIO_FUNC); } else { audio_pt_unlock (&esd->pt, AUDIO_FUNC); } return incr; } static int qesd_read (SWVoiceIn *sw, void *buf, int len) { return audio_pcm_sw_read (sw, buf, len); } static int qesd_init_in (HWVoiceIn *hw, struct audsettings *as) { ESDVoiceIn *esd = (ESDVoiceIn *) hw; struct audsettings obt_as = *as; int esdfmt = ESD_STREAM | ESD_RECORD; int err; sigset_t set, old_set; sigfillset (&set); esdfmt |= (as->nchannels == 2) ? ESD_STEREO : ESD_MONO; switch (as->fmt) { case AUD_FMT_S8: case AUD_FMT_U8: esdfmt |= ESD_BITS8; obt_as.fmt = AUD_FMT_U8; break; case AUD_FMT_S16: case AUD_FMT_U16: esdfmt |= ESD_BITS16; obt_as.fmt = AUD_FMT_S16; break; case AUD_FMT_S32: case AUD_FMT_U32: dolog ("Will use 16 instead of 32 bit samples\n"); esdfmt |= ESD_BITS16; obt_as.fmt = AUD_FMT_S16; break; } obt_as.endianness = <API key>; audio_pcm_init_info (&hw->info, &obt_as); hw->samples = conf.samples; esd->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift); if (!esd->pcm_buf) { dolog ("Could not allocate buffer (%d bytes)\n", hw->samples << hw->info.shift); return -1; } esd->fd = -1; err = pthread_sigmask (SIG_BLOCK, &set, &old_set); if (err) { qesd_logerr (err, "pthread_sigmask failed\n"); goto fail1; } esd->fd = esd_record_stream (esdfmt, as->freq, conf.adc_host, NULL); if (esd->fd < 0) { qesd_logerr (errno, "esd_record_stream failed\n"); goto fail2; } if (audio_pt_init (&esd->pt, qesd_thread_in, esd, AUDIO_CAP, AUDIO_FUNC)) { goto fail3; } err = pthread_sigmask (SIG_SETMASK, &old_set, NULL); if (err) { qesd_logerr (err, "pthread_sigmask(restore) failed\n"); } return 0; fail3: if (close (esd->fd)) { qesd_logerr (errno, "%s: close on esd socket(%d) failed\n", AUDIO_FUNC, esd->fd); } esd->fd = -1; fail2: err = pthread_sigmask (SIG_SETMASK, &old_set, NULL); if (err) { qesd_logerr (err, "pthread_sigmask(restore) failed\n"); } fail1: qemu_free (esd->pcm_buf); esd->pcm_buf = NULL; return -1; } static void qesd_fini_in (HWVoiceIn *hw) { void *ret; ESDVoiceIn *esd = (ESDVoiceIn *) hw; audio_pt_lock (&esd->pt, AUDIO_FUNC); esd->done = 1; <API key> (&esd->pt, AUDIO_FUNC); audio_pt_join (&esd->pt, &ret, AUDIO_FUNC); if (esd->fd >= 0) { if (close (esd->fd)) { qesd_logerr (errno, "failed to close esd socket\n"); } esd->fd = -1; } audio_pt_fini (&esd->pt, AUDIO_FUNC); qemu_free (esd->pcm_buf); esd->pcm_buf = NULL; } static int qesd_ctl_in (HWVoiceIn *hw, int cmd, ...) { (void) hw; (void) cmd; return 0; } /* common */ static void *qesd_audio_init (void) { return &conf; } static void qesd_audio_fini (void *opaque) { (void) opaque; ldebug ("esd_fini"); } struct audio_option qesd_options[] = { { .name = "SAMPLES", .tag = AUD_OPT_INT, .valp = &conf.samples, .descr = "buffer size in samples" }, { .name = "DIVISOR", .tag = AUD_OPT_INT, .valp = &conf.divisor, .descr = "threshold divisor" }, { .name = "DAC_HOST", .tag = AUD_OPT_STR, .valp = &conf.dac_host, .descr = "playback host" }, { .name = "ADC_HOST", .tag = AUD_OPT_STR, .valp = &conf.adc_host, .descr = "capture host" }, { /* End of list */ } }; static struct audio_pcm_ops qesd_pcm_ops = { .init_out = qesd_init_out, .fini_out = qesd_fini_out, .run_out = qesd_run_out, .write = qesd_write, .ctl_out = qesd_ctl_out, .init_in = qesd_init_in, .fini_in = qesd_fini_in, .run_in = qesd_run_in, .read = qesd_read, .ctl_in = qesd_ctl_in, }; struct audio_driver esd_audio_driver = { .name = "esd", .descr = "http://en.wikipedia.org/wiki/Esound", .options = qesd_options, .init = qesd_audio_init, .fini = qesd_audio_fini, .pcm_ops = &qesd_pcm_ops, .can_be_default = 0, .max_voices_out = INT_MAX, .max_voices_in = INT_MAX, .voice_size_out = sizeof (ESDVoiceOut), .voice_size_in = sizeof (ESDVoiceIn) };
<?php /** * Template File: The users dashboard * * @package Tina-MVC * @subpackage Tina-Core-Views * @author Francis Crossen <francis@crossen.org> */ /** * You should include this check in every view file you write. The constant is defined in * tina_mvc_base_page->load_view() */ if( ! defined('TINA_MVC_LOAD_VIEW') ) exit();?> <?php require_once ('models/masvalor_utils.php'); global $current_user; get_currentuserinfo(); ?> <! <script language="JavaScript" src="wp-content/plugins/masvalor/app/includes/calendar/calendar_db.js"></script> <link rel="stylesheet" href="wp-content/plugins/masvalor/app/includes/calendar/calendar.css"> <script language="JavaScript" src="wp-content/plugins/masvalor/app/includes/simple-calendar/tcal.js"></script> <link rel="stylesheet" type="text/css" href="wp-content/plugins/masvalor/app/includes/simple-calendar/tcal.css"> <script language="javascript" type="text/javascript"> function resetFilter() { document.getElementById('search').value=''; document.getElementById('filter_sel').value=''; hiddenDateFilter(); document.getElementById('filter_date_from').value=''; document.getElementById('filter_date_to').value=''; submitbutton(); } function showDateFilter() { document.getElementById('filter_date').style.margin ='5px'; document.getElementById('filter_date').style.visibility ='visible'; document.getElementById('filter_date').style.height ='auto'; } function hiddenDateFilter() { document.getElementById('filter_date').style.margin ='0px'; document.getElementById('filter_date').style.visibility ='hidden'; document.getElementById('filter_date').style.height ='0px'; } function filterAdvanced() { if(document.getElementById('filter_date').style.visibility == 'hidden') showDateFilter(); else hiddenDateFilter(); } function saveDelete(cid){ if(confirm("¿Est\u00e1 seguro que quiere borrar?")) { document.forms['adminForm'].task.value = 'delete'; document.forms['adminForm'].cid.value = cid; document.forms['adminForm'].submit(); } } function activadSearches(){ if(confirm("¿Est\u00e1 seguro que quiere aceptar a las B\u00fasquedas?")) { document.forms['adminForm'].task.value = 'activadSearches'; document.forms['adminForm'].submit(); } } function checkUncheckAll(cid) { input = document.getElementById('userid'); input.value +=cid + ','; } </script> <style> #table_noticia thead{ background-color: #aaaaaa; } a{ text-decoration: none; color:black; } </style> <div id="table_noticia" style="font-size: 14px;margin-left: -35px;"> <form action="" method="post" name="tinymce" id="adminForm"> <h2 style="margin-left:13px;"><?php echo __('Activaci&oacute;n B&uacute;squedas') ?></h2> <br/> <table> <tr> <td> <div> <td style="width:100%;padding-left: 11px;"><?php echo __('Filtro') ?> <input type="text" name="search" style="height: 13px;" id="search" value="<?php //echo $this->lists['search'] ?>" class="text_area" title="Filtro"/> <select name="filter_sel" id="filter_sel" style="height: 26px;padding-top: 2px;"> <!--option value="status"><?php echo __('Estado') ?></option <option value="job_title"><?php echo __('Puesto') ?></option> <option value="company"><?php echo __('Instituci&oacute;n') ?></option> </select> <! <select id="filter_sel" name="filter_sel" style="height: 26px;padding-top: 2px;" > <option value="Pendiente"><?php echo __('Pendiente') ?></option> <option value="En curso"><?php echo __('En curso') ?> </option> <option value="Satisfecha"><?php echo __('Satisfecha') ?> </option> <option value="Insatisfecha"><?php echo __('Insatisfecha') ?> </option> </select> <button onclick="this.form.submit();" style="padding-top: 2px;">Buscar</button> <button style="padding-top: 2px;" onclick="document.getElementById('search').value='';this.form.getElementById('filter_state').value='-1';this.form.submit();">Reset</button> <a href="javascript:filterAdvanced()" title="Filtro Fechas" style=" margin-left: -55px;"><img src ="wp-content/plugins/masvalor/app/includes/image/dates.png" style="position: absolute; margin-left: 60px;" alt="Filtro fechas"></a> <div id="filter_date" style="visibility: hidden; height: 0px;"> <?php echo __('Entre Fechas:') ?> <input class="tcal" type="text" name="filter_date_from" id="filter_date_from" value="" title="Fecha desde"/> <input class="tcal" type="text" name="filter_date_to" id="filter_date_to" value="" title="Fecha hasta"/> </div> <script> if(document.getElementById('filter_date_from').value != '') { showDateFilter(); } </script> </div> <div style="float: right; margin-top: -34px;"> <a href="#" title="Activar" onclick="activadSearches()" > <img WIDTH="36" HEIGHT="36" src="wp-content/plugins/masvalor/app/includes/image/actived.png"></a> </div> <table id="<API key>" class="admintable" style="font-size:11px;width:683px;text-align:center;margin-bottom: 27px;"> <div style="width:100%"> <hr/> </div> <thead> <th><?php echo __('Nro') ?></th> <th><?php echo __('Fecha Inicio') ?></th> <th><?php echo __('Fecha Fin') ?></th> <th><?php echo __('Puesto') ?></th> <th><?php echo __('Instituci&oacute;n') ?></th> <th><?php echo __('Lugar') ?></th> <th><?php echo __('Activado') ?></th> </thead> <tbody> <?php foreach ( $V->datas as $result ) {?> <tr style="background-color:#eeeeee;"> <td><?php echo $result->id;?></td> <td><?php echo $result->start_date;?></td> <td><?php echo $result->end_date;?></td> <td><?php echo $result->job_title;?></td> <td><?php echo $result->company;?></td> <td><?php echo $result->city.','.$result->state;?></td> <td align="center"> <input type="checkbox" name="actived" id="actived" onclick="checkUncheckAll('<?php echo $result->id; ?>')" ><br></td> </tr> <?php } ?> </tbody> </table> </td> </tr> </table> <div class="paginator" style="margin-left:16px"> <?php $pages = ceil($V->count/$V->itemsPerPage); if ($pages > 1) for ($i=1;$i<=$pages;$i++){ $pageLink = masvalor_getUrl().'/searches_activated/&limitstart='.(($i-1)*$V->itemsPerPage); if ($V->currPage != $i) $href = '<a href='.$pageLink.'>'.$i.'</a>'; else $href = $i; if ($i==1) echo $href; else echo ' - '.$href; } ?> </div> <input type="hidden" name="cid" value="" /> <input type="hidden" name="userid" id="userid" value=""/> <input type="hidden" name="task" value="" /> </form> </div>
#include <cstring> #include <cstdlib> #include "game.h" #include <fstream> #ifdef PSP #include <pspkernel.h> #include <pspdebug.h> #include <pspctrl.h> #include <pspdebug.h> #endif #include "timerlib.h" extern timerLib timer; #include <math.h> #include "graphicslib.h" extern graphicsLib graphLib; #include "soundlib.h" extern soundLib soundManager; #include "inputlib.h" extern inputLib input; #include "file/format.h" #include "defines.h" #include "scenes/ending.h" #include "file/file_io.h" extern CURRENT_FILE_FORMAT::st_save game_save; extern CURRENT_FILE_FORMAT::st_game_config game_config; extern CURRENT_FILE_FORMAT::file_io fio; extern struct format_v_2_0_1::st_checkpoint checkpoint; extern string FILEPATH; extern CURRENT_FILE_FORMAT::file_game game_data; extern CURRENT_FILE_FORMAT::file_stage stage_data; extern bool GAME_FLAGS[FLAG_COUNT]; extern FREEZE_EFFECT_TYPES <API key>; // class constructor // game::game() : loaded_stage(NULL), _show_boss_hp(false), fps_timer(0) { currentStage = 1; fps_counter = 0; _frame_duration = 1000/80; // each frame must use this share of time <API key> = false; _dark_mode = false; <API key> = false; } // class destructor // game::~game() { // clean allocated stages //delete loaded_stage; } // initializar game, can't be on constructor because it needs other objects (circular) // void game::initGame() { stringstream player_name; player_name << "p" << game_save.selected_player; players.push_back(classPlayer(player_name.str(), game_save.selected_player)); // @TODO - optimixzation: make this uneeded // always insert all possible players, as it is used in cutscenes and such for (int i=0; i<FS_MAX_PLAYERS; i++) { if (i != game_save.selected_player) { stringstream player_name2; player_name2 << "p" << i; players.push_back(classPlayer(player_name2.str(), i)); } } config_manager.set_player_ref(&players.at(0)); unload_stage(); loaded_stage = new stage(currentStage, players); players.at(0).set_is_player(true); players.at(0).reset_hp(); players.at(1).set_is_player(true); players.at(1).reset_hp(); <API key> = GAME_FLAGS[FLAG_INVENCIBLE]; } void game::showGame(bool can_characters_move) { if (players.at(0).is_teleporting() == false) { // ignore input while player is teleporting because it caused some issues input.readInput(); } else { input.clean(); } if (config_manager.execute_ingame_menu()) { // game is paused return; } @TODO - move this to the player, so we don't need to check every single loop if (players.at(0).is_dead() == true) { restart_stage(); return; } if (test_teleport(&players.at(0))) { return; } <API key>(); loaded_stage->move_objects(); if (_dark_mode == false) { loaded_stage->showStage(); } if (can_characters_move == true) { players.at(0).execute(); loaded_stage->move_npcs(); } if (_dark_mode == false) { loaded_stage->show_npcs(); players.at(0).show(); loaded_stage->show_objects(); loaded_stage->showAbove(); } else { graphLib.blank_screen(); } } int game::getMapPointLock(struct st_position pos) { return loaded_stage->getMapPointLock(pos); } st_position game::checkScrolling() { st_position move; st_position mapScroll = loaded_stage->getMapScrolling(); st_position p1Pos(players.at(0).getPosition().x, players.at(0).getPosition().y); //cout << "game::checkScrolling - p1Pos.x: " << p1Pos.x << ", mapScroll.x: " << mapScroll.x << ", RES_W/2: " << RES_W/2 << "\n"; move.x += (p1Pos.x - mapScroll.x) - RES_W/2; if (mapScroll.x + move.x < 0 || mapScroll.x + move.x > MAP_W*TILESIZE) { move.x = 0; } return move; } void game::start_stage() { graphLib.set_colormap(currentStage); _show_boss_hp = false; input.clean(); loaded_stage->reset_current_map(); // TODO - this must be on a single method in soundlib players.at(0).set_position(st_position(80, -TILESIZE)); soundManager.stop_music(); soundManager.load_stage_music(stage_data.bgmusic_filename); loaded_stage->reload_stage(); players.at(0).reset_charging_shot(); players.at(0).cancel_slide(); draw_lib.update_colorcycle(); loaded_stage->showStage(); loaded_stage->showAbove(); draw_lib.update_screen(); players.at(0).clean_projectiles(); players.at(0).set_animation_type(ANIM_TYPE_TELEPORT); players.at(0).set_direction(<API key>); players.at(0).set_map(loaded_stage->get_current_map()); players.at(0).refill_weapons(); players.at(0).reset_hp(); // find teleport stop point int min_y = loaded_stage-><API key>(95); // x = 80 + half a player width (30) players.at(0).<API key>((min_y-3)*TILESIZE); loaded_stage->showStage(); // to fix colorcycle colors loaded_stage->showAbove(); draw_lib.update_screen(); show_ready(); /// @TODO - not updating colorcycle for some reason... soundManager.play_music(); @TODO: do not show twice if (GAME_FLAGS[FLAG_QUICKLOAD] == false) { while (players.at(0).get_anim_type() == ANIM_TYPE_TELEPORT) { showGame(); draw_lib.update_screen(); } for (int i=0; i<15; i++) { // extra delay to show dialogs showGame(false); draw_lib.update_screen(); } if (game_save.stages[currentStage] == 0) { game_dialogs.show_stage_dialog(); // reset timers for objects loaded_stage-><API key>(); } } } void game::show_ready() const { for (int i=0; i<4; i++) { draw_lib.show_ready(); timer.delay(400); draw_lib.update_screen(); loaded_stage->showStage(); // to fix colorcycle colors loaded_stage->show_objects(); loaded_stage->showAbove(); draw_lib.update_screen(); timer.delay(400); } } /* void graphicsLib::show_ready() { st_position dest_pos((RES_W/2)-26, (RES_H/2)-6); for (int i=0; i<4; i++) { copyArea(dest_pos, &ready_message, &gameScreen); updateScreen(); timer.delay(400); updateScreen(); timer.delay(400); } } */ void game::restart_stage() { // remove any used teleporter players.at(0).set_teleporter(-1); _player_teleporter.active = false; _show_boss_hp = false; input.clean(); loaded_stage->reset_current_map(); // TODO - this must be on a single method in soundlib players.at(0).set_position(st_position(checkpoint.x, -TILESIZE)); soundManager.stop_music(); soundManager.unload_music(); soundManager.load_stage_music(stage_data.bgmusic_filename); players.at(0).clean_projectiles(); players.at(0).set_animation_type(ANIM_TYPE_TELEPORT); std::cout << ">> checkpoint..x: " << checkpoint.x << ", checkpoint.y: " << checkpoint.y << std::endl; if (checkpoint.y == -1) { // did not reached any checkpoint, use the calculated value from stage start // find teleport stop point int min_y = loaded_stage-><API key>(95); // x = 80 + half a player width (30) players.at(0).<API key>((min_y-3)*TILESIZE); } else { players.at(0).<API key>(checkpoint.y-TILESIZE/2); } players.at(0).set_map(loaded_stage->get_current_map()); players.at(0).reset_hp(); loaded_stage->reset_stage_maps(); loaded_stage->showStage(); loaded_stage->showAbove(); graphLib.set_screen_adjust(st_position(0, 0)); //graphLib.set_colormap(currentStage); draw_lib.update_screen(); soundManager.restart_music(); show_ready(); } bool game::showIntro() { #ifdef PSP std::cout << "showIntro::RAM::BFR='" << _ram_counter.ramAvailable() << "'" << std::endl; #endif scenes.preloadScenes(); scenes.intro(); graphLib.set_colormap(-1); scenes.main_screen(); scenes.unload_intro(); currentStage = 0; #ifdef PSP std::cout << "showIntro::RAM::AFT='" << _ram_counter.ramAvailable() << "'" << std::endl; #endif initGame(); //std::cout << "game::showIntro - game_save.stages[INTRO_STAGE]: " << game_save.stages[INTRO_STAGE] << std::endl; if (game_save.stages[INTRO_STAGE] == 0) { input.clean(); start_stage(); } else { currentStage = scenes.pick_stage(); unload_stage(); loaded_stage = new stage(currentStage, players); // show boss intro with stars, if needed soundManager.stop_music(); if (game_save.stages[currentStage] == 0) { scenes.boss_intro(currentStage); } start_stage(); } //std::cout << "game::showIntro - selected_stage.x: " << selected_stage.x << ", selected_stage.y: " << selected_stage.y << ", currentStage: " << currentStage << std::endl; #ifdef PSP std::cout << "showIntro::RAM::STAGE_LOADED='" << _ram_counter.ramAvailable() << "'" << std::endl; #endif return true; } void game::fps_count() { fps_counter++; if (fps_timer <= timer.getTimer()) { sprintf(_fps_buffer, "fps: %d", fps_counter); fps_counter = 0; fps_timer = timer.getTimer()+1000; } if (fps_counter > 1) { std::string temp_str(_fps_buffer); graphLib.draw_text(10, 10, temp_str); } } bool game::test_teleport(classPlayer *test_player) { if (players.at(0).get_anim_type() == ANIM_TYPE_TELEPORT) { return false; } stage *temp_stage = loaded_stage; int currentMap = loaded_stage-><API key>(); int temp_x, temp_y; int temp_map_n=0; int player_x = 0; int transition_type = 0; int lim1, lim2, lim3, lim4; int i=0; bool MUST_TELEPORT = false; int teleporter_dist = 0; int link_type = -1; int px = test_player->getPosition().x + (test_player->get_size().width*0.5); int py = test_player->getPosition().y + (test_player->get_size().height*0.5) + (test_player->get_size().height*0.25); int j = 0; for (j=0; j<STAGE_MAX_LINKS; j++) { if (stage_data.links[j].id_map_origin == -1 || stage_data.links[j].id_map_destiny == -1) { continue; } if (stage_data.links[j].id_map_origin != -1) { if (currentStage == SKULLCASTLE5 && <API key>.find(i) != <API key>.end()) { i++; continue; } if ((stage_data.links[j].id_map_origin == currentMap && stage_data.links[j].pos_origin.x != -1)) { temp_x = stage_data.links[j].pos_origin.x; temp_y = stage_data.links[j].pos_origin.y; temp_map_n = stage_data.links[j].id_map_destiny; player_x = stage_data.links[j].pos_destiny.x; if (stage_data.links[j].pos_origin.y > stage_data.links[j].pos_destiny.y) { transition_type = <API key>; } else if (stage_data.links[j].pos_origin.y < stage_data.links[j].pos_destiny.y) { transition_type = <API key>; } } else if (stage_data.links[j].id_map_destiny == currentMap && stage_data.links[j].bidirecional == true && stage_data.links[j].pos_destiny.x != -1) { temp_x = stage_data.links[j].pos_destiny.x; temp_y = stage_data.links[j].pos_destiny.y; temp_map_n = stage_data.links[j].id_map_origin; player_x = stage_data.links[j].pos_origin.x; if (stage_data.links[j].pos_origin.y < stage_data.links[j].pos_destiny.y) { transition_type = <API key>; } else if (stage_data.links[j].pos_origin.y > stage_data.links[j].pos_destiny.y) { transition_type = <API key>; } } else { i++; continue; } lim1 = temp_x*TILESIZE; lim2 = temp_x*TILESIZE + stage_data.links[j].size*TILESIZE; lim3 = (temp_y)*TILESIZE; lim4 = ((temp_y)*TILESIZE)+TILESIZE; // give extra pixels in the END-Y, if top to bottom ot bottom to top if (stage_data.links[j].type != LINK_TELEPORTER && stage_data.links[j].type != <API key>) { if (transition_type == <API key>) { lim4 += TILESIZE; } else if (transition_type == <API key>) { lim3 -= TILESIZE; } } //std::cout << "GAME::test_teleport - found a LINK for this map" << std::endl; //std::cout << "LINK[" << j << "] - px: " << px << ", lim1: " << lim1 << ", lim2: " << lim2 << ", py: " << py << ", lim3: " << lim3 << ", lim4: " << lim4 << std::endl; if ((px >= lim1 && px <= lim2) && ((py > lim3 && py < lim4))) { if (test_player->get_teleporter() == -1) { // for transition up/down, only execute if player is partially out of screen if (stage_data.links[j].type != LINK_TELEPORTER && stage_data.links[j].type != <API key> && (transition_type == <API key> || transition_type == <API key>)) { short int p_posy = test_player->getPosition().y; if (p_posy > 0 && p_posy+test_player->get_size().height < RES_H-4) { //std::cout << "GAME::test_teleport - player position is not out-of-screen - t1: " << (p_posy+test_player->get_size().height) << " < t2: " << (RES_H-4) << std::endl; i++; continue; } } teleporter_dist = lim1 - player_x*TILESIZE - 8; MUST_TELEPORT = true; if (stage_data.links[j].type == <API key> && currentStage == SKULLCASTLE5 && currentMap == 2) { test_player->set_direction(<API key>); test_player->set_teleporter(i); } else if (stage_data.links[j].type != LINK_TELEPORTER) { test_player->set_teleporter(i); } link_type = stage_data.links[j].type; <API key>(i, st_position(players.at(0).getPosition().x, players.at(0).getPosition().y), false); break; } // only clean teleport when player is out of the teleporter } else { if (i == test_player->get_teleporter()) { if (link_type != <API key> || currentStage != SKULLCASTLE5 || currentMap != 2) { // only clean link if not teleporter nor is on final stage/map test_player->set_teleporter(-1); } } } } i++; } if (!MUST_TELEPORT) { return false; } <API key>(); reset_beam_objects(); // beam/ray objects must be reset when changing maps // TODO - define according to the condition, try to maintain it //playerObj->sprite->anim_type = ANIM_STAIRS; int dest_x = (player_x*TILESIZE) - temp_stage->getMapScrolling().x; int max_pos_x = MAP_W*TILESIZE - RES_W; if (dest_x > max_pos_x) { dest_x = max_pos_x; } if (dest_x < 0) { dest_x = 0; } //std::cout << ">>>>>>>>>>>> TELEPORT - temp_map_n: " << temp_map_n << ", dest_x: " << dest_x << " <<<<<<<<<<<<" << std::endl; // must move the map, so that the dest position in screen is equal to player_real_pos_x int new_map_pos_x; //int playerRealXPos = test_player->getPosition().x + temp_stage->getMapScrolling().x; //new_map_pos_x = ((player_x*TILESIZE)) - playerRealXPos + teleporter_dist; //std::cout << "game::test_teleport - playerRealXPos: " << playerRealXPos << ", teleporter_dist: " << teleporter_dist << ", link.dest.x: " << player_x << std::endl; new_map_pos_x = temp_stage->getMapScrolling().x - teleporter_dist; if (new_map_pos_x < 0) { new_map_pos_x = 0; } else if (new_map_pos_x > MAP_W*TILESIZE) { new_map_pos_x = MAP_W*TILESIZE; } int diff_h=6; if (test_player->get_size().width > 30) { diff_h = abs((float)test_player->get_size().width-30); } new_map_pos_x -= diff_h +2; if (link_type == LINK_TELEPORTER || link_type == <API key>) { //std::cout << "<<<<<<<<<<<< TELEPORTER LINK >>>>>>>>>>>>>>" << std::endl; test_player->teleport_out(); graphLib.blank_screen(); draw_lib.update_screen(); input.waitTime(500); currentMap = temp_map_n; new_map_pos_x = (stage_data.links[j].pos_destiny.x * TILESIZE) - TILESIZE*2; } else { //std::cout << "<<<<<<<<<<<< TRANSITION LINK >>>>>>>>>>>>>>" << std::endl; transitionScreen(transition_type, temp_map_n, new_map_pos_x, test_player); } set_current_map(temp_map_n); if (link_type == LINK_TELEPORTER || link_type == <API key>) { int new_scroll_pos = loaded_stage-><API key>(stage_data.links[j].pos_destiny.x); //std::cout << ">>>>>>>>>> teleporter.new_scroll_pos: " << new_scroll_pos << std::endl; loaded_stage->set_scrolling(st_position(new_scroll_pos, temp_stage->getMapScrolling().y)); test_player->set_position(st_position(stage_data.links[j].pos_destiny.x*TILESIZE, 0)); } else { loaded_stage->set_scrolling(st_position(new_map_pos_x, temp_stage->getMapScrolling().y)); test_player->set_position(st_position(abs((float)test_player->get_real_position().x+new_map_pos_x), test_player->getPosition().y)); } test_player-><API key>(); loaded_stage->get_current_map()->reset_scrolled(); draw_lib.update_screen(); return true; } void game::set_current_map(int temp_map_n) { //std::cout << "game::set_current_map - temp_map_n: " << temp_map_n << std::endl; loaded_stage->set_current_map(temp_map_n); loaded_stage-><API key>(); players.at(0).set_map(loaded_stage->get_current_map()); if (loaded_stage->get_current_map() != players.at(0).map) { std::cout << ">>>>>>>>>>>>>> ERROR" << std::endl; graphLib.show_debug_msg("EXIT exit(-1); } /* loaded_stage->get_current_map() != players.at(0).map */ } short game::get_current_map() const { return loaded_stage->get_current_map_n();; } void game::map_present_boss(bool show_dialog) { std::cout << "game::map_present_boss::START" << std::endl; <API key> = true; soundManager.stop_music(); soundManager.unload_music(); soundManager.play_boss_music(); // 1. keep showing game screen until player reaches ground players.at(0).clear_move_commands(); bool loop_run = true; while (loop_run == true) { //std::cout << "game::map_present_boss::LOOP #1" << std::endl; loaded_stage->showStage(); players.at(0).charMove(); bool hit_ground = players.at(0).hit_ground(); int anim_type = players.at(0).get_anim_type(); //std::cout << "game::map_present_boss - hit_ground: " << hit_ground << ", anim_type: " << anim_type << std::endl; if (hit_ground == true && anim_type == ANIM_TYPE_STAND) { loop_run = false; } players.at(0).show(); loaded_stage->showAbove(); input.waitTime(8); draw_lib.update_screen(); } // 2. blink screen graphLib.blink_screen(255, 255, 255); // 3. move boss from top to ground loop_run = true; while (loop_run == true) { //std::cout << "game::map_present_boss::LOOP #2" << std::endl; //std::cout << ">> game::boss_intro - waiting for hit_ground... <<" << std::endl; if (loaded_stage->boss_hit_ground() == true) { loop_run = false; } show_stage(0, true); } show_stage(8, true); if (show_dialog == true) { // 4. show boss dialog if (strlen(stage_data.boss_dialog.line1[0]) > 0 && game_save.stages[currentStage] == 0) { dialogs boss_dialog; boss_dialog.show_boss_dialog(); //std::cout << "PSP DEBUG - #A" << std::endl; } //std::cout << "PSP DEBUG - #B" << std::endl; } show_stage(8, false); std::cout << "game::map_present_boss::PASS #1" << std::endl; //std::cout << "PSP DEBUG - #1" << std::endl; fill_boss_hp_bar(); //std::cout << "PSP DEBUG - #2" << std::endl; _show_boss_hp = true; <API key> = false; //std::cout << "PSP DEBUG - #3" << std::endl; } character *game::get_player() { return (character*)&players.at(0); } object* game::get_player_platform() { return players.at(0).get_platform(); } void game::<API key>() { if (<API key>() == true) { std::cout << ">>>>>>> RETURN from teleporter <<<<<<<<<" << std::endl; <API key>(); } } bool game::must_show_boss_hp() const { return _show_boss_hp; } void game::fill_boss_hp_bar() const { //soundManager.play_repeated_sfx(SFX_GOT_ENERGY, 5); soundManager.play_timed_sfx(SFX_GOT_ENERGY, 60*PLAYER_INITIAL_HP+100); for (int i=0; i<PLAYER_INITIAL_HP; i++) { graphLib.draw_hp_bar(i, -1, -1); draw_lib.update_screen(); timer.delay(60); } timer.delay(200); } void game::fill_player_weapon(short weapon_n) { soundManager.play_timed_sfx(SFX_GOT_ENERGY, 60*PLAYER_INITIAL_HP+100); for (int i=0; i<PLAYER_INITIAL_HP; i++) { graphLib.draw_hp_bar(i, players.at(0).get_number(), weapon_n); draw_lib.update_screen(); timer.delay(60); } timer.delay(200); } void game::reset_stage_maps() const { loaded_stage->reset_stage_maps(); } // remove the projectiles from the list of all players and npcs // void game::<API key>() { std::vector<classPlayer>::iterator p_it; for (p_it=players.begin(); p_it!=players.end(); p_it++) { (*p_it).clean_projectiles(); } loaded_stage->get_current_map()-><API key>(); } void game::reset_beam_objects() { loaded_stage->get_current_map()->reset_beam_objects(); } void game::<API key>() { std::vector<classPlayer>::iterator p_it; for (p_it=players.begin(); p_it!=players.end(); p_it++) { (*p_it).cancel_slide(); } } //<API key>, <API key> void game::transitionScreen(short int type, short int map_n, short int adjust_x, classPlayer *pObj) { timer.pause(); <API key> temp_screen; short i = 0; stage* temp_stage = loaded_stage; graphLib.initSurface(st_size(RES_W, RES_H*2), &temp_screen); classMap* temp_map = temp_stage->maps[map_n]; temp_map->set_bg1_scroll(loaded_stage->get_current_map()->get_bg1_scroll()); temp_map->set_bg2_scroll(loaded_stage->get_current_map()->get_bg2_scroll()); temp_map->set_scrolling(st_position(adjust_x, 0)); if (type == <API key>) { temp_map-><API key>(temp_screen, loaded_stage->get_current_map()->get_bg1_scroll(), RES_H); } else { temp_map-><API key>(temp_screen, loaded_stage->get_current_map()->get_bg1_scroll(), 0); } graphLib.copyArea(st_rectangle(0, i*TRANSITION_STEP, RES_W, RES_H), st_position(0, 0), &temp_screen, &graphLib.gameScreen); // draw map in the screen, erasing all players/objects/npcs loaded_stage->showStage(); //std::cout << "transitionScreen::START - p.x: " << pObj->getPosition().x << ", p.y: " << pObj->getPosition().y << std::endl; // draw the offscreen with the new loaded map if (type == <API key> || type == <API key>) { // copy current screen to temp if (type == <API key>) { graphLib.<API key>(st_rectangle(0, 0, RES_W, RES_H), st_position(0, 0), &temp_screen); } else if (type == <API key>) { graphLib.<API key>(st_rectangle(0, 0, RES_W, RES_H), st_position(0, RES_H), &temp_screen); } // copy the new screen to the temp_area if (type == <API key>) { graphLib.<API key>(st_rectangle(adjust_x, 0, RES_W, RES_H), st_position(0, RES_H), temp_map->get_map_surface(), &temp_screen); } else if (type == <API key>) { graphLib.<API key>(st_rectangle(adjust_x, 0, RES_W, RES_H), st_position(0, 0), temp_map->get_map_surface(), &temp_screen); } graphLib.<API key>(&temp_screen); graphLib.<API key>(&temp_screen); // now, show the transition short int extra_y = 0; for (i=0; i<(RES_H+TILESIZE*0.5)/TRANSITION_STEP; i++) { graphLib.<API key>(&temp_screen); if (type == <API key>) { graphLib.copyArea(st_rectangle(0, i*TRANSITION_STEP, RES_W, RES_H), st_position(0, 0), &temp_screen, &graphLib.gameScreen); } else if (type == <API key>) { graphLib.copyArea(st_rectangle(0, RES_H-i*TRANSITION_STEP, RES_W, RES_H), st_position(0, 0), &temp_screen, &graphLib.gameScreen); } if (i % 2 == 0) { extra_y = 1; } else { extra_y = 0; } if (type == <API key>) { if (pObj->getPosition().y > 6) { pObj->set_position(st_position(pObj->getPosition().x, pObj->getPosition().y - TRANSITION_STEP + extra_y)); } } else if (type == <API key>) { if (pObj->getPosition().y < RES_H-TILESIZE*2) { pObj->set_position(st_position(pObj->getPosition().x, pObj->getPosition().y + TRANSITION_STEP - extra_y)); } } pObj-><API key>(); pObj->show(); if (type == <API key>) { loaded_stage->showAbove(-i*TRANSITION_STEP); loaded_stage->get_current_map()->show_objects(-i*TRANSITION_STEP); int <API key> = (RES_H+TILESIZE*0.5) - i*TRANSITION_STEP - 8; temp_map->show_objects(<API key>); temp_map->showAbove(<API key>, adjust_x); } else { loaded_stage->showAbove(i*TRANSITION_STEP); loaded_stage->get_current_map()->show_objects(i*TRANSITION_STEP); int <API key> = -(RES_H+TILESIZE*0.5) + i*TRANSITION_STEP + 8; // 8 is a adjust for some error I don't know the reason temp_map->show_objects(<API key>); temp_map->showAbove(<API key>, adjust_x); } draw_lib.update_screen(); #if !defined(PLAYSTATION2) && !defined(ANDROID) input.waitTime(8); #endif } if (type == <API key>) { temp_map->changeScrolling(st_position(temp_map->getMapScrolling().x, 0)); } if (type == <API key>) { if (pObj->getPosition().y > TILESIZE) { pObj->set_position(st_position(pObj->getPosition().x, pObj->getPosition().y - TRANSITION_STEP - 2)); } } else if (type == <API key>) { if (pObj->getPosition().y < RES_H-TILESIZE*2) { pObj->set_position(st_position(pObj->getPosition().x, pObj->getPosition().y + TRANSITION_STEP)); } } } temp_screen.freeGraphic(); pObj->set_teleporter(-1); pObj-><API key>(); timer.unpause(); //std::cout << "transitionScreen::END" << std::endl; } void game::<API key>(short direction, bool is_door, short tileX, short tileY) { int i = 0; int upTile = 0; int downTile = 0; classMap* temp_map = loaded_stage->get_current_map(); st_position scroll_move; if (direction == ANIM_DIRECTION_LEFT) { scroll_move.x = -2; } else { scroll_move.x = 2; } timer.pause(); if (is_door == true) { <API key>(); <API key>(); @TODO - interrupt slides, charged shots, etc // if there is a subboss alive, near left, you can't open if (<API key>(tileX) == true) { std::cout << "Oh não! Porta não pode ser aberta porque existe um sub-boss vivo à esquerda dela!" << std::endl; return; } loaded_stage->showStage(); upTile = tileY; for (i=tileY; i>=0; i if (temp_map->getMapPointLock(st_position(tileX, i)) == TERRAIN_DOOR) { upTile = i; } else { break; } } downTile = tileY; for (i=tileY; i<MAP_H; i++) { if (temp_map->getMapPointLock(st_position(tileX, i)) == TERRAIN_DOOR) { downTile = i; } else { break; } } soundManager.play_sfx(SFX_DOOR_OPEN); loaded_stage->redraw_boss_door(false, (downTile-upTile+1), tileX, tileY, players.at(0).get_number());//bool is_close, int nTiles, int tileX } int move_limit = (RES_W/abs((float)scroll_move.x))-TILESIZE/abs((float)scroll_move.x); //int move_limit = (RES_W/abs((float)scroll_move.x)); for (int i=0; i<move_limit; i++) { loaded_stage->changeScrolling(scroll_move, false); loaded_stage->showStage(); loaded_stage->show_npcs(); players.at(0).show(); loaded_stage->showAbove(); #if defined(PC) input.waitTime(3); #endif draw_lib.update_screen(); if (i%(TILESIZE/2) == 0) { players.at(0).set_position(st_position(players.at(0).getPosition().x+scroll_move.x, players.at(0).getPosition().y)); players.at(0).<API key>(); } } if (is_door == true) { soundManager.play_sfx(SFX_DOOR_OPEN); loaded_stage->redraw_boss_door(true, (downTile-upTile+1), tileX, tileY, players.at(0).get_number()); players.at(0).reset_charging_shot(); players.at(0).cancel_slide(); } std::cout << "<API key> END" << std::endl; input.waitTime(6); timer.unpause(); loaded_stage->showStage(); } void game::got_weapon() { bool <API key> = false; if (game_save.stages[currentStage] == 0) { <API key> = true; game_save.finished_stages++; } <API key> = GAME_FLAGS[FLAG_INVENCIBLE]; // store old value in order to not set the flag to false if it is on my command-line parameter //std::cout << "**** SAVE#1::<API key>: " << <API key> << ", GAME_FLAGS[FLAG_INVENCIBLE]: " << GAME_FLAGS[FLAG_INVENCIBLE] << std::endl; GAME_FLAGS[FLAG_INVENCIBLE] = true; //std::cout << "game::got_weapon - npc_name: " << npc_name << std::endl; // remove any projectiles, charged shots, slides, etc players.at(0).clean_projectiles(); players.at(0).clear_move_commands(); if (<API key> == true && currentStage != 0 && currentStage <= 8) { // check witch is the boss that was killed //if (npc_name ==) @TODO: save game @TODO: teletransport if capsules // fall to ground players.at(0).fall(); @TODO: walk to boss room middle, if inside a boss room (must create a way to check this), otherwise, just jump up <API key>(&players.at(0), RES_W/2); // jump up, implosion, jump down and teleport out of the screen players.at(0).execute_jump_up(); draw_implosion(players.at(0).get_real_position().x+players.at(0).get_size().width/2-6, players.at(0).get_real_position().y+players.at(0).get_size().height/2-4); players.at(0).show(); draw_lib.update_screen(); players.at(0).set_weapon(currentStage); fill_player_weapon(players.at(0).get_selected_weapon()); players.at(0).fall(); soundManager.play_sfx(SFX_GOT_WEAPON); input.waitTime(5000); // fall to ground players.at(0).fall(); input.waitTime(500); soundManager.play_sfx(SFX_TELEPORT); players.at(0).teleport_out(); players.at(0).set_show_hp(false); input.waitTime(1000); @TODO // show the "you got" screen graphLib.blank_screen(); soundManager.load_music("got_weapon.mod"); graphLib.blink_screen(255, 255, 255); graphLib.blank_screen(); soundManager.play_music(); <API key> temp_bg; graphLib.surfaceFromFile(FILEPATH+"data/images/backgrounds/stage_boss_intro.png", &temp_bg); graphLib.showSurface(&temp_bg); players.at(0).set_position(st_position(20, (RES_H * 0.5 - players.at(0).get_size().height/2))); players.at(0).set_animation_type(ANIM_TYPE_ATTACK); loaded_stage->set_scrolling(st_position(0, 0)); players.at(0).<API key>(); players.at(0).show(); graphLib.<API key>(); std::string weapon_name(game_data.weapons[currentStage].name); for (std::string::iterator p = weapon_name.begin(); weapon_name.end() != p; ++p) { *p = toupper(*p); } std::string phrase = std::string("YOU GOT ") + weapon_name; graphLib.<API key>((RES_W * 0.5 - 90), (RES_H * 0.5 - 4), phrase, false); std::string extra_name = ""; if (currentStage == COIL_GOT_STAGE) { extra_name = "AND FROG COIL ADAPTOR"; } else if (currentStage == JET_GOT_STAGE) { extra_name = "AND EAGLE JET ADAPTOR"; } graphLib.<API key>((RES_W * 0.5 - 90), (RES_H * 0.5 + 8), extra_name, false); players.at(0).show(); graphLib.<API key>(5000); graphLib.<API key>(); } else { players.at(0).teleport_out(); } players.at(0).set_show_hp(true); game_save.stages[currentStage] = 1; leave_stage(); } void game::leave_stage() { if (fio.write_save(game_save) == false) { show_savegame_error(); } graphLib.<API key>(); //std::cout << "[[[<API key>(RESET #2)]]]" << std::endl; draw_lib.set_flash_enabled(false); <API key> = FREEZE_EFFECT_NONE; GAME_FLAGS[FLAG_INVENCIBLE] = <API key>; // show password input.clean(); timer.delay(200); scenes.show_password(); // return to stage selection players.at(0).reset_charging_shot(); players.at(0).set_weapon(WEAPON_DEFAULT); currentStage = scenes.pick_stage(); unload_stage(); loaded_stage = new stage(currentStage, players); // show boss intro with stars, if needed soundManager.stop_music(); if (game_save.stages[currentStage] == 0) { scenes.boss_intro(currentStage); } checkpoint.map = 0; checkpoint.map_scroll_x = 0; checkpoint.x = 50; checkpoint.y = -1; start_stage(); } void game::leave_game() { //std::cout << ">>> LEAVEGAME <<<" <<std::endl; dialogs dialogs_obj; if (dialogs_obj.<API key>() != true) { //std::cout << "++ DON'T LEAVE GAME" << std::endl; return; } //std::cout << "++ YES, LEAVE GAME" << std::endl; if (fio.write_save(game_save) == false) { std::cout << "*** Show savegame Error" << std::endl; show_savegame_error(); } #ifdef PSP sceKernelExitGame(); #else SDL_Quit(); #endif exit(0); } void game::game_over() { <API key>.clear(); input.waitTime(200); input.clean(); soundManager.load_music("game_over.mod"); soundManager.play_music(); graphLib.blank_screen(); <API key> password_screen; std::string filename = FILEPATH + "data/images/backgrounds/config.png"; graphLib.surfaceFromFile(filename, &password_screen); graphLib.copyArea(st_rectangle(0, 0, password_screen.gSurface->w, password_screen.gSurface->h), st_position(0, 0), &password_screen, &graphLib.gameScreen); <API key> dialog_img; filename = FILEPATH + "data/images/backgrounds/dialog.png"; graphLib.surfaceFromFile(filename, &dialog_img); graphLib.copyArea(st_rectangle(0, 0, dialog_img.gSurface->w, dialog_img.gSurface->h), st_position(RES_W/2-dialog_img.gSurface->w/2, RES_H/2-dialog_img.gSurface->h/2), &dialog_img, &graphLib.gameScreen); graphLib.draw_centered_text(RES_H/2-6, "GAME OVER", graphLib.gameScreen, st_color(235, 235, 235)); draw_lib.update_screen(); input.waitTime(400); input.wait_keypress(); if (currentStage != INTRO_STAGE) { leave_stage(); } else { scenes.show_password(); soundManager.stop_music(); soundManager.load_stage_music(stage_data.bgmusic_filename); soundManager.play_music(); restart_stage(); } } void game::show_ending(st_position boss_pos) { // save the data indicating game was finished, so user can see ending later or get access to more features game_config.game_finished = true; fio.save_config(game_config); players.at(0).set_show_hp(false); // reset player colors to original players.at(0).set_weapon(0); ending game_ending; game_ending.set_boss_pos(boss_pos); game_ending.start(); leave_game(); } void game::quick_load_game() { if (fio.save_exists()) { fio.read_save(game_save); } currentStage = SKULLCASTLE5; game_save.selected_player = PLAYER_ROCKBOT; if (GAME_FLAGS[FLAG_PLAYER_ROCKBOT]) { game_save.selected_player = PLAYER_ROCKBOT; } else if (GAME_FLAGS[FLAG_PLAYER_BETABOT]) { game_save.selected_player = PLAYER_BETABOT; } else if (GAME_FLAGS[<API key>]) { game_save.selected_player = PLAYER_CANDYBOT; } else if (GAME_FLAGS[<API key>]) { game_save.selected_player = PLAYER_KITTYBOT; } //std::cout << ">> game_save.selected_player: " << game_save.selected_player << std::endl; //std::cout << "p4.arms: " << game_data.armor_pieces[3].special_ability[ARMOR_ARMS] << std::endl; scenes.preloadScenes(); initGame(); start_stage(); } void game::<API key>() { loaded_stage->changeScrolling(checkScrolling()); } void game::draw_explosion(short int centerX, short int centerY, bool show_players) { unsigned int timerInit; int distance=0, mode=0; int accel=1; timerInit = timer.getTimer(); /* if (show_players) { players.at(0).set_animation_type(ANIM_TYPE_STAND); } */ draw_lib.update_screen(); soundManager.stop_music(); soundManager.play_sfx(SFX_PLAYER_DEATH); // x = a + r * cos(t) // y = b + r * sin(t) while (timer.getTimer() < timerInit+2000) { loaded_stage->showStage(); if (show_players) { players.at(0).show(); } loaded_stage->showAbove(); for (int i=0; i<6; i++) { graphLib.copyArea(st_rectangle(TILESIZE*mode, 0, graphLib.small_explosion.width/3, graphLib.small_explosion.height), st_position(centerX+distance*cos(static_cast<double>(i*45)), centerY+distance*sin(static_cast<double>(i*45))), &graphLib.small_explosion, &graphLib.gameScreen); } if (distance > 50) { for (int i=0; i<6; i++) { graphLib.copyArea(st_rectangle(TILESIZE*mode, 0, graphLib.small_explosion.width/3, graphLib.small_explosion.height), st_position(centerX+(distance-50)*cos(static_cast<double>(i*45)), centerY+(distance-50)*sin(static_cast<double>(i*45))), &graphLib.small_explosion, &graphLib.gameScreen); } } distance += 3; if (distance % 6 == 0) { if (mode+1 <= 2) { mode++; } else { mode = 0; } if (accel +1 <= 5) { accel++; } } draw_lib.update_screen(); input.waitTime(10); } } void game::draw_implosion(short int centerX, short int centerY) { int distance=RES_W*0.5, mode=0; int accel=1; int second_distance = 100; draw_lib.update_screen(); soundManager.stop_music(); soundManager.play_repeated_sfx(SFX_IMPLOSION, 1); // x = a + r * cos(t) // y = b + r * sin(t) while (distance > -second_distance) { //std::cout << "distance: " << distance << std::endl; loaded_stage->showStage(); players.at(0).show(); loaded_stage->showAbove(); //loaded_stage->showAbove(); if (distance > 0) { for (int i=0; i<6; i++) { graphLib.copyArea(st_rectangle(TILESIZE*mode, 0, graphLib.small_explosion.width/3, graphLib.small_explosion.height), st_position(centerX+distance*cos(static_cast<double>(i*45)), centerY+distance*sin(static_cast<double>(i*45))), &graphLib.small_explosion, &graphLib.gameScreen); } } if (distance < RES_W*0.5-50) { for (int i=0; i<6; i++) { graphLib.copyArea(st_rectangle(TILESIZE*mode, 0, graphLib.small_explosion.width/3, graphLib.small_explosion.height), st_position(centerX+(distance+second_distance)*cos(static_cast<double>(i*45)), centerY+(distance+second_distance)*sin(static_cast<double>(i*45))), &graphLib.small_explosion, &graphLib.gameScreen); } } distance -= 3; if ((int)abs((float)distance) % 4 == 0) { if (mode+1 <= 2) { mode++; } else { mode = 0; } if (accel +1 <= 5) { accel++; } } draw_lib.update_screen(); input.waitTime(15); } } void game::show_player(short player_n) { players.at(player_n).show(); } void game::set_player_position(st_position pos, short player_n) { players.at(player_n).set_position(pos); players.at(player_n).<API key>(); } void game::<API key>(short xinc, short yinc, short player_n) { players.at(player_n).change_position(xinc, yinc); players.at(player_n).<API key>(); } void game::<API key>(ANIM_TYPE anim_type, short int player_n) { players.at(player_n).set_animation_type(anim_type); } st_position game::get_player_position(short player_n) { return st_position(players.at(player_n).getPosition().x, players.at(player_n).getPosition().y); } st_size game::get_player_size(short int player_n) { return players.at(player_n).get_size(); } void game::<API key>(short direction, short player_n) { players.at(player_n).set_direction(direction); } void game::player_fall(short int player_n) { players.at(player_n).fall(); } void game::<API key>(character *char_obj, short pos_x) { @TODO: jump obstacles if (char_obj->get_real_position().x+char_obj->get_size().width/2 > pos_x) { char_obj->set_animation_type(ANIM_TYPE_WALK); char_obj->set_direction(ANIM_DIRECTION_LEFT); while (char_obj->get_real_position().x+char_obj->get_size().width/2 > pos_x) { char_obj->set_position(st_position(char_obj->getPosition().x-2, char_obj->getPosition().y)); loaded_stage->showStage(); loaded_stage->showAbove(); loaded_stage->show_npcs(); players.at(0).show(); draw_lib.update_screen(); timer.delay(20); } } else if (char_obj->get_real_position().x+char_obj->get_size().width/2 < pos_x) { char_obj->set_direction(<API key>); char_obj->set_animation_type(ANIM_TYPE_WALK); while (char_obj->get_real_position().x+char_obj->get_size().width/2 < pos_x) { char_obj->set_position(st_position(char_obj->getPosition().x+2, char_obj->getPosition().y)); loaded_stage->showStage(); loaded_stage->showAbove(); loaded_stage->show_npcs(); players.at(0).show(); draw_lib.update_screen(); timer.delay(20); } } } void game::<API key>(short set_teleport_n, st_position set_player_pos, bool is_object) { _player_teleporter.is_object = is_object; _player_teleporter.teleporter_n = set_teleport_n; _player_teleporter.old_player_pos.x = set_player_pos.x; _player_teleporter.old_player_pos.y = set_player_pos.y; _player_teleporter.active = true; _player_teleporter.finished = false; //std::cout << "game::<API key> - scroll: " << loaded_stage->getMapScrolling().x << std::endl; _player_teleporter.old_map_scroll = loaded_stage->getMapScrolling(); _player_teleporter.old_map_n = loaded_stage->get_current_map_n(); } bool game::<API key>() const { return _player_teleporter.active; } void game::<API key>() { if (_player_teleporter.teleporter_n != -1) { <API key>.erase(_player_teleporter.teleporter_n); } players.at(0).set_teleporter(-1); } void game::<API key>() { <API key>(); <API key>(); players.at(0).recharge(ENERGY_TYPE_HP, ENERGY_ITEM_BIG); players.at(0).teleport_out(); timer.delay(1000); _player_teleporter.active = false; <API key>.insert(pair<int,bool>(_player_teleporter.teleporter_n, true)); // teleport out soundManager.play_sfx(SFX_TELEPORT); players.at(0).teleport_out(); _player_teleporter.old_player_pos.y -= 5; players.at(0).set_position(_player_teleporter.old_player_pos); loaded_stage->set_current_map(_player_teleporter.old_map_n); if (<API key>.size() == 8) { // search for the final-boss teleporter capsule and start it loaded_stage-><API key>(); } players.at(0).set_map(loaded_stage->get_current_map()); //std::cout << "game::<API key> - scroll.x: " << _player_teleporter.old_map_scroll.x << ", scroll.y: " << _player_teleporter.old_map_scroll.y << std::endl; loaded_stage->set_scrolling(st_position(_player_teleporter.old_map_scroll)); players.at(0).set_animation_type(ANIM_TYPE_STAND); if (_player_teleporter.is_object == true) { loaded_stage->get_current_map()-><API key>(_player_teleporter.teleporter_n); } players.at(0).set_teleporter(-1); soundManager.stop_music(); soundManager.load_stage_music(stage_data.bgmusic_filename); soundManager.play_music(); } void game::show_stage(int wait_time, bool move_npcs) { if (_dark_mode == false) { loaded_stage->showStage(); } if (move_npcs == true) { loaded_stage->move_npcs(); } if (_dark_mode == false) { loaded_stage->show_npcs(); players.at(0).show(); loaded_stage->showAbove(); } if (wait_time > 0) { input.waitTime(wait_time); } draw_lib.update_screen(); } bool game::<API key>(short tileX) { return loaded_stage-><API key>(tileX); } void game::<API key>(st_position dest_pos, int dest_map, int teleporter_id) { //std::cout << " if (<API key>.find(teleporter_id) != <API key>.end()) { //std::cout << "[TELEPORT-OBJ] teleporter_id [" << teleporter_id << "] already used" << std::endl; return; } <API key>(teleporter_id, st_position(players.at(0).getPosition().x, players.at(0).getPosition().y), true); classPlayer* test_player = &players.at(0); //std::cout << "<<<<<<<<<<<< TELEPORTER LINK >>>>>>>>>>>>>>" << std::endl; test_player->teleport_out(); graphLib.blank_screen(); draw_lib.update_screen(); input.waitTime(500); set_current_map(dest_map); int new_scroll_pos = loaded_stage-><API key>(dest_pos.x); //std::cout << ">>>>>>>>>> teleporter.new_scroll_pos: " << new_scroll_pos << std::endl; loaded_stage->set_scrolling(st_position(new_scroll_pos, 0)); test_player->set_position(st_position(dest_pos.x*TILESIZE, 0)); test_player-><API key>(); loaded_stage->get_current_map()->reset_scrolled(); draw_lib.update_screen(); } bool game::show_config(short finished_stage) { if (scenes.show_main_config(finished_stage) == 1) { input.clean(); input.waitTime(50); config_manager.disable_ingame_menu(); leave_stage(); return true; } return false; } void game::unload_stage() { if (loaded_stage == NULL) { return; } /* #ifdef PSP std::cout << "unload_stage::RAM::BFR='" << _ram_counter.ramAvailable() << "'" << std::endl; #endif */ delete loaded_stage; loaded_stage = NULL; /* #ifdef PSP std::cout << "unload_stage::RAM::AFT='" << _ram_counter.ramAvailable() << "'" << std::endl; #endif */ } void game::show_savegame_error() { std::vector<std::string> msgs; msgs.push_back("ERROR WHILE SAVING GAME,"); msgs.push_back("PLEASE CHECK THAT THE DEVICE OR"); msgs.push_back("FILE IS NOT WRITE-PROTECTED."); draw_lib.show_ingame_warning(msgs); } void game::get_drop_item_ids() { for (int i=0; i<DROP_ITEM_COUNT; i++) { _drop_item_list[i] = -1; } for (int i=0; i<GAME_MAX_OBJS; i++) { if (game_data.objects[i].type == OBJ_LIFE) { _drop_item_list[DROP_ITEM_1UP] = i; } else if (game_data.objects[i].type == <API key>) { _drop_item_list[<API key>] = i; } else if (game_data.objects[i].type == OBJ_ENERGY_PILL_BIG) { _drop_item_list[<API key>] = i; } else if (game_data.objects[i].type == <API key>) { _drop_item_list[<API key>] = i; } else if (game_data.objects[i].type == OBJ_WEAPON_PILL_BIG) { _drop_item_list[<API key>] = i; } } } classPlayer *game::get_player(int n) { return &players.at(n); } st_position game::<API key>() const { return loaded_stage->getMapScrolling(); } void game::reset_scroll() const { loaded_stage->reset_scrolling(); } short game::get_drop_item_id(short type) const { return _drop_item_list[type]; } void game::show_map() const { loaded_stage->showStage(); loaded_stage->showAbove(); draw_lib.update_screen(); } void game::showGotArmorDialog(e_ARMOR_PIECES armor_type) { game_dialogs.showGotArmorDialog(armor_type); }
using System; using System.Text; using System.IO; namespace Server.Network { public class PacketReader { private byte[] m_Data; private int m_Size; private int m_Index; public PacketReader( byte[] data, int size, bool fixedSize ) { m_Data = data; m_Size = size; m_Index = fixedSize ? 1 : 3; } public byte[] Buffer { get { return m_Data; } } public int Size { get { return m_Size; } } public void Trace( NetState state ) { try { using ( StreamWriter sw = new StreamWriter( "Packets.log", true ) ) { byte[] buffer = m_Data; if ( buffer.Length > 0 ) sw.WriteLine( "Client: {0}: Unhandled packet 0x{1:X2}", state, buffer[0] ); using ( MemoryStream ms = new MemoryStream( buffer ) ) Utility.FormatBuffer( sw, ms, buffer.Length ); sw.WriteLine(); sw.WriteLine(); } } catch { } } public int Seek( int offset, SeekOrigin origin ) { switch ( origin ) { case SeekOrigin.Begin: m_Index = offset; break; case SeekOrigin.Current: m_Index += offset; break; case SeekOrigin.End: m_Index = m_Size - offset; break; } return m_Index; } public int ReadInt32() { if ( (m_Index + 4) > m_Size ) return 0; return (m_Data[m_Index++] << 24) | (m_Data[m_Index++] << 16) | (m_Data[m_Index++] << 8) | m_Data[m_Index++]; } public short ReadInt16() { if ( (m_Index + 2) > m_Size ) return 0; return (short)((m_Data[m_Index++] << 8) | m_Data[m_Index++]); } public byte ReadByte() { if ( (m_Index + 1) > m_Size ) return 0; return m_Data[m_Index++]; } public uint ReadUInt32() { if ( (m_Index + 4) > m_Size ) return 0; return (uint)((m_Data[m_Index++] << 24) | (m_Data[m_Index++] << 16) | (m_Data[m_Index++] << 8) | m_Data[m_Index++]); } public ushort ReadUInt16() { if ( (m_Index + 2) > m_Size ) return 0; return (ushort)((m_Data[m_Index++] << 8) | m_Data[m_Index++]); } public sbyte ReadSByte() { if ( (m_Index + 1) > m_Size ) return 0; return (sbyte)m_Data[m_Index++]; } public bool ReadBoolean() { if ( (m_Index + 1) > m_Size ) return false; return ( m_Data[m_Index++] != 0 ); } public string ReadUnicodeStringLE() { StringBuilder sb = new StringBuilder(); int c; while ( (m_Index + 1) < m_Size && (c = (m_Data[m_Index++] | (m_Data[m_Index++] << 8))) != 0 ) sb.Append( (char)c ); return sb.ToString(); } public string <API key>( int fixedLength ) { int bound = m_Index + (fixedLength << 1); int end = bound; if ( bound > m_Size ) bound = m_Size; StringBuilder sb = new StringBuilder(); int c; while ( (m_Index + 1) < bound && (c = (m_Data[m_Index++] | (m_Data[m_Index++] << 8))) != 0 ) { if ( IsSafeChar( c ) ) sb.Append( (char)c ); } m_Index = end; return sb.ToString(); } public string <API key>() { StringBuilder sb = new StringBuilder(); int c; while ( (m_Index + 1) < m_Size && (c = (m_Data[m_Index++] | (m_Data[m_Index++] << 8))) != 0 ) { if ( IsSafeChar( c ) ) sb.Append( (char)c ); } return sb.ToString(); } public string <API key>() { StringBuilder sb = new StringBuilder(); int c; while ( (m_Index + 1) < m_Size && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 ) { if ( IsSafeChar( c ) ) sb.Append( (char)c ); } return sb.ToString(); } public string ReadUnicodeString() { StringBuilder sb = new StringBuilder(); int c; while ( (m_Index + 1) < m_Size && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 ) sb.Append( (char)c ); return sb.ToString(); } public bool IsSafeChar( int c ) { return ( c >= 0x20 && c < 0xFFFE ); } public string ReadUTF8StringSafe( int fixedLength ) { if ( m_Index >= m_Size ) { m_Index += fixedLength; return String.Empty; } int bound = m_Index + fixedLength; if ( bound > m_Size ) bound = m_Size; int count = 0; int index = m_Index; int start = m_Index; while ( index < bound && m_Data[index++] != 0 ) ++count; index = 0; byte[] buffer = new byte[count]; int value = 0; while ( m_Index < bound && (value = m_Data[m_Index++]) != 0 ) buffer[index++] = (byte)value; string s = Utility.UTF8.GetString( buffer ); bool isSafe = true; for ( int i = 0; isSafe && i < s.Length; ++i ) isSafe = IsSafeChar( (int) s[i] ); m_Index = start + fixedLength; if ( isSafe ) return s; StringBuilder sb = new StringBuilder( s.Length ); for ( int i = 0; i < s.Length; ++i ) if ( IsSafeChar( (int) s[i] ) ) sb.Append( s[i] ); return sb.ToString(); } public string ReadUTF8StringSafe() { if ( m_Index >= m_Size ) return String.Empty; int count = 0; int index = m_Index; while ( index < m_Size && m_Data[index++] != 0 ) ++count; index = 0; byte[] buffer = new byte[count]; int value = 0; while ( m_Index < m_Size && (value = m_Data[m_Index++]) != 0 ) buffer[index++] = (byte)value; string s = Utility.UTF8.GetString( buffer ); bool isSafe = true; for ( int i = 0; isSafe && i < s.Length; ++i ) isSafe = IsSafeChar( (int) s[i] ); if ( isSafe ) return s; StringBuilder sb = new StringBuilder( s.Length ); for ( int i = 0; i < s.Length; ++i ) { if ( IsSafeChar( (int) s[i] ) ) sb.Append( s[i] ); } return sb.ToString(); } public string ReadUTF8String() { if ( m_Index >= m_Size ) return String.Empty; int count = 0; int index = m_Index; while ( index < m_Size && m_Data[index++] != 0 ) ++count; index = 0; byte[] buffer = new byte[count]; int value = 0; while ( m_Index < m_Size && (value = m_Data[m_Index++]) != 0 ) buffer[index++] = (byte)value; return Utility.UTF8.GetString( buffer ); } public string ReadString() { StringBuilder sb = new StringBuilder(); int c; while ( m_Index < m_Size && (c = m_Data[m_Index++]) != 0 ) sb.Append( (char)c ); return sb.ToString(); } public string ReadStringSafe() { StringBuilder sb = new StringBuilder(); int c; while ( m_Index < m_Size && (c = m_Data[m_Index++]) != 0 ) { if ( IsSafeChar( c ) ) sb.Append( (char)c ); } return sb.ToString(); } public string <API key>( int fixedLength ) { int bound = m_Index + (fixedLength << 1); int end = bound; if ( bound > m_Size ) bound = m_Size; StringBuilder sb = new StringBuilder(); int c; while ( (m_Index + 1) < bound && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 ) { if ( IsSafeChar( c ) ) sb.Append( (char)c ); } m_Index = end; return sb.ToString(); } public string ReadUnicodeString( int fixedLength ) { int bound = m_Index + (fixedLength << 1); int end = bound; if ( bound > m_Size ) bound = m_Size; StringBuilder sb = new StringBuilder(); int c; while ( (m_Index + 1) < bound && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 ) sb.Append( (char)c ); m_Index = end; return sb.ToString(); } public string ReadStringSafe( int fixedLength ) { int bound = m_Index + fixedLength; int end = bound; if ( bound > m_Size ) bound = m_Size; StringBuilder sb = new StringBuilder(); int c; while ( m_Index < bound && (c = m_Data[m_Index++]) != 0 ) { if ( IsSafeChar( c ) ) sb.Append( (char)c ); } m_Index = end; return sb.ToString(); } public string ReadString( int fixedLength ) { int bound = m_Index + fixedLength; int end = bound; if ( bound > m_Size ) bound = m_Size; StringBuilder sb = new StringBuilder(); int c; while ( m_Index < bound && (c = m_Data[m_Index++]) != 0 ) sb.Append( (char)c ); m_Index = end; return sb.ToString(); } } }
#ifndef <API key> #define <API key> #include "Fantasma.hpp" class FantasmaAmarillo : public Fantasma { public: static const int id_fantasma = 3; FantasmaAmarillo(Tablero &mitablero,Pacman& j,Puntuacion& p,int x,int y); protected: void moverNormal() override; private: }; #endif // <API key>
# Still do to: # Handle continuation lines (see Prefs::parseText). These should always # go into a text area. package Foswiki::Plugins::PreferencesPlugin; use strict; use warnings; use Foswiki::Func (); # The plugins API use Foswiki::Plugins (); # For the API version use vars qw( @shelter ); our $VERSION = '$Rev: 14572 (2012-04-06) $'; our $RELEASE = '1.1.3'; our $SHORTDESCRIPTION = 'Allows editing of preferences using fields predefined in a form'; our $NO_PREFS_IN_TOPIC = 1; my $MARKER = "\007"; # Markers used during form generation my $START_MARKER = $MARKER . 'STARTPREF' . $MARKER; my $END_MARKER = $MARKER . 'ENDPREF' . $MARKER; sub initPlugin { # check for Plugins.pm versions if ( $Foswiki::Plugins::VERSION < 1.026 ) { Foswiki::Func::writeWarning( 'Version mismatch between PreferencesPlugin and Plugins.pm'); return 0; } @shelter = (); return 1; } sub <API key> { my ( $text, $topic, $web ) = @_; my $topic = $_[1]; my $web = $_[2]; return unless ( $_[0] =~ m/%EDITPREFERENCES(?:{(.*?)})?%/ ); require CGI; require Foswiki::Attrs; my $formDef; my $attrs = new Foswiki::Attrs($1); if ( defined( $attrs->{_DEFAULT} ) ) { my ( $formWeb, $form ) = Foswiki::Func::<API key>( $web, $attrs->{_DEFAULT} ); # SMELL: Unpublished API. No choice, though :-( require Foswiki::Form; # SMELL $formDef = new Foswiki::Form( $Foswiki::Plugins::SESSION, $formWeb, $form ); } my $query = Foswiki::Func::getCgiQuery(); my $action = lc( $query->param('prefsaction') || '' ); $query->Delete('prefsaction'); $action =~ s/\s.*$ if ( $action eq 'edit' ) { Foswiki::Func::setTopicEditLock( $web, $topic, 1 ); # Replace setting values by form fields but not inside comments Item4816 # and also not inside verbatim blocks Item1117 my $outtext = ''; my $insidecomment = 0; my $insideverbatim = 0; foreach my $token ( split /(|<\/?verbatim\b[^>]*>)/, $_[0] ) { if ( !$insideverbatim and $token =~ /<! $insidecomment++; } elsif ( !$insideverbatim and $token =~ / $insidecomment-- if ( $insidecomment > 0 ); } elsif ( $token =~ /<verbatim/ ) { $insideverbatim++; } elsif ( $token =~ /<\/verbatim/ ) { $insideverbatim-- if ( $insideverbatim > 0 ); } elsif ( !$insidecomment and !$insideverbatim ) { $token =~ s/^($Foswiki::regex{setRegex})($Foswiki::regex{tagNameRegex})\s*\=(.*$(?:\n[ \t]+[^\s*].*$)*)/ $1._generateEditField($web, $topic, $3, $4, $formDef)/gem; } $outtext .= $token; } $_[0] = $outtext; $_[0] =~ s/%EDITPREFERENCES({.*?})?%/ <API key>($web, $topic)/ge; my $viewUrl = Foswiki::Func::getScriptUrl( $web, $topic, 'viewauth' ); my $startForm = CGI::start_form( -name => 'editpreferences', -method => 'post', -action => $viewUrl ); $startForm =~ s/\s+$ my $endForm = CGI::end_form(); $endForm =~ s/\s+$ $_[0] =~ s/^(.*?)$START_MARKER(.*)$END_MARKER(.*?)$/$1$startForm$2$endForm$3/s; $_[0] =~ s/$START_MARKER|$END_MARKER } if ( $action eq 'cancel' ) { Foswiki::Func::setTopicEditLock( $web, $topic, 0 ); } elsif ( $action eq 'save' ) { # Make sure the request came from POST if ( $query && $query->method() && uc( $query->method() ) ne 'POST' ) { # silently ignore it if the request didn't come from a POST } else { my ( $meta, $text ) = Foswiki::Func::readTopic( $web, $topic ); # SMELL: unchecked implicit untaint of value? # $text =~ s/($Foswiki::regex{setVarRegex})/ $text =~ s/^($Foswiki::regex{setRegex})($Foswiki::regex{tagNameRegex})\s*\=(.*$(?:\n[ \t]+[^\s*].*$)*)/ $1._saveSet($query, $web, $topic, $3, $4, $formDef)/mgeo; Foswiki::Func::saveTopic( $web, $topic, $meta, $text ); } Foswiki::Func::setTopicEditLock( $web, $topic, 0 ); # Finish with a redirect so that the *new* values are seen my $viewUrl = Foswiki::Func::getScriptUrl( $web, $topic, 'view' ); Foswiki::Func::redirectCgiQuery( undef, $viewUrl ); return; } # implicit action="view", or drop through from "save" or "cancel" $_[0] =~ s/%EDITPREFERENCES({.*?})?%/_generateEditButton($web, $topic)/ge; } # Use the post-rendering handler to plug our formatted editor units # into the text sub <API key> { my ( $text ) = @_; $_[0] =~ s/SHELTER$MARKER(\d+)/$shelter[$1]/g; } # Pluck the default value of a named field from a form definition sub _getField { my ( $formDef, $name ) = @_; foreach my $f ( @{ $formDef->{fields} } ) { if ( $f->{name} eq $name ) { return $f; } } return; } # Generate a field suitable for editing this type. Use of the core # function 'renderFieldForEdit' ensures that we will pick up # extra edit types defined in other plugins. sub _generateEditField { my ( $web, $topic, $name, $value, $formDef ) = @_; $value =~ s/^\s*(.*?)\s*$/$1/ge; my ( $extras, $html ); if ($formDef) { my $fieldDef = $formDef->getField($name); if ($fieldDef) { my ($topicObject) = Foswiki::Func::readTopic( $web, $topic ); ( $extras, $html ) = $fieldDef->renderForEdit( $topicObject, $value ); } } unless ($html) { if ( $value =~ /\n/ ) { my $rows = 1; $rows++ while $value =~ /\n/g; # No form definition and there are newlines, default to textarea $html = CGI::textarea( -class => 'foswikiAlert foswikiInputField', -name => $name, -cols => 80, -rows => $rows, -default => $value ); } else { # No form definition and no newlines, default to text field. $html = CGI::textfield( -class => 'foswikiAlert foswikiInputField', -name => $name, -size => 80, -value => $value ); } } push( @shelter, $html ); return $START_MARKER . CGI::span( { class => 'foswikiAlert', style => 'font-weight:bold;' }, $name . ' = SHELTER' . $MARKER . $#shelter ) . $END_MARKER; } # Generate the button that replaces the EDITPREFERENCES tag in view mode sub _generateEditButton { my ( $web, $topic ) = @_; my $viewUrl = Foswiki::Func::getScriptUrl( $web, $topic, 'viewauth' ); my $text = CGI::start_form( -name => 'editpreferences', -method => 'post', -action => $viewUrl ); $text .= CGI::input( { type => 'hidden', name => 'prefsaction', value => 'edit' } ); $text .= CGI::submit( -name => 'edit', -value => 'Edit Preferences', -class => 'foswikiButton' ); $text .= CGI::end_form(); $text =~ s/\n return $text; } # Generate the buttons that replace the EDITPREFERENCES tag in edit mode sub <API key> { my ( $web, $topic ) = @_; my $text = $START_MARKER . CGI::submit( -name => 'prefsaction', -value => 'Save new settings', -class => 'foswikiSubmit', -accesskey => 's' ); $text .= '&nbsp;'; $text .= CGI::submit( -name => 'prefsaction', -value => 'Cancel', -class => 'foswikiButtonCancel', -accesskey => 'c' ) . $END_MARKER; return $text; } # Given a Set in the topic being saved, look in the query to see # if there is a new value for the Set and generate a new # Set statement. sub _saveSet { my ( $query, $web, $topic, $name, $value, $formDef ) = @_; my $newValue = $query->param($name); if ( not defined $newValue ) { $newValue = $value; $newValue =~ s/^\s+//; # strip leading whitespace } if ($formDef) { my $fieldDef = _getField( $formDef, $name ); my $type = $fieldDef->{type} || ''; if ( $type && $type =~ /^checkbox/ ) { my $val = ''; my $vals = $fieldDef->{value}; foreach my $item (@$vals) { my $cvalue = $query->param( $name . $item ); if ( defined($cvalue) ) { if ( !$val ) { $val = ''; } else { $val .= ', ' if ($cvalue); } $val .= $item if ($cvalue); } } $newValue = $val; } } # if no form def, it's just treated as text return $name . ' = ' . $newValue; } 1; __END__ Foswiki - The Free and Open Source Wiki, http://foswiki.org/ Copyright (C) 2008-2012 Foswiki Contributors. Foswiki Contributors are listed in the AUTHORS file in the root of this distribution. NOTE: Please extend that file, not this notice. 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. For more details read LICENSE in the root of this distribution. 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. As per the GPL, removal of this notice is prohibited.
FactoryGirl.define do factory :task_type do name { Faker::HipsterIpsum.words(3).join(' ') } end end
<?php // no direct access defined('_JEXEC') or die; class <API key> extends <API key> { public function process() { $db = JFactory::getDbo(); $query = $db->getQuery(true); $start = $this->input->getInt('start', 0); $query->select('id') ->from('#<API key>') ->where('is_profile = 1') ->where('plan_id > 0') ->where('published >= 1 OR payment_method LIKE "os_offline%"'); $db->setQuery($query, $start, 1000); $profileIds = $db->loadColumn(); if (empty($profileIds)) { // No records left, redirect to complete page $this->setRedirect('index.php?option=com_osmembership&view=dashboard', JText::_('The extension and data was successfully updated')); } else { $query->clear() ->select('id, profile_id, plan_id, published, from_date, to_date') ->from('#<API key>') ->where('plan_id > 0') ->where('profile_id IN (' . implode(',', $profileIds) . ')') ->where('(published >= 1 OR payment_method LIKE "os_offline%")') ->order('id'); $db->setQuery($query); $rows = $db->loadObjectList(); $data = array(); foreach ($rows as $row) { $data[$row->profile_id][$row->plan_id][] = $row; } foreach ($profileIds as $profileId) { foreach ($data[$profileId] as $planId => $subscriptions) { $isActive = false; $isPending = false; $isExpired = false; $lastActiveDate = null; $lastExpiredDate = null; $planFromDate = $subscriptions[0]->from_date; $planMainRecordId = $subscriptions[0]->id; foreach ($subscriptions as $subscription) { if ($subscription->published == 1) { $isActive = true; $lastActiveDate = $subscription->to_date; } elseif ($subscription->published == 0) { $isPending = true; } elseif ($subscription->published == 2) { $isExpired = true; $lastExpiredDate = $subscription->to_date; } } if ($isActive) { $published = 1; $planToDate = $lastActiveDate; } elseif ($isPending) { $published = 0; } elseif ($isExpired) { $published = 2; $planToDate = $lastExpiredDate; } else { $published = 3; $planToDate = $subscription->to_date; } $query->clear() ->update('#<API key>') ->set('<API key> = ' . (int) $published) ->set('<API key> = ' . $db->quote($planFromDate)) ->set('<API key> = ' . $db->quote($planToDate)) ->where('plan_id = ' . $planId) ->where('profile_id = ' . $profileId); $db->setQuery($query); $db->execute(); $query->clear() ->update('#<API key>') ->set('plan_main_record = 1') ->where('id = ' . $planMainRecordId); $db->setQuery($query); $db->execute(); } } $start += count($profileIds); $this->setRedirect('index.php?option=com_osmembership&view=datamigration&start=' . $start); } } }
<?php if (!defined('FREEPBX_IS_AUTH')) { die('No direct script access allowed'); } global $db; $sql = " CREATE TABLE IF NOT EXISTS `custom_destinations` ( `custom_dest` varchar(80) NOT NULL default '', `description` varchar(40) NOT NULL default '', `notes` varchar(255) NOT NULL default '', PRIMARY KEY (`custom_dest`) )"; $check = $db->query($sql); if(DB::IsError($check)) { die_freepbx("Can not create custom_destinations table\n"); } $sql = " CREATE TABLE IF NOT EXISTS `custom_extensions` ( `custom_exten` varchar(80) NOT NULL default '', `description` varchar(40) NOT NULL default '', `notes` varchar(255) NOT NULL default '', PRIMARY KEY (`custom_exten`) )"; $check = $db->query($sql); if(DB::IsError($check)) { die_freepbx("Can not create custom_extensions table\n"); } ?>
<?php /** * Main plugin class. */ class QBTTC { /** * Path to the plugin. * * @access protected * * @var string */ protected $plugin_path; /** * Form object. * * @access protected * * @var QBTTC_Form */ protected $form; /** * Constructor. * * Hooks all of the plugin functionality. * * @access public */ public function __construct() { // set the path to the plugin main directory $this->set_plugin_path(dirname(__FILE__)); // include all plugin files $this->include_files(); // initialize the admin form $this->set_form( new QBTTC_Form() ); } /** * Load the plugin classes and libraries. * * @access protected */ protected function include_files() { require_once($this->get_plugin_path() . '/includes/hierarchy.php'); require_once($this->get_plugin_path() . '/includes/taxonomies.php'); require_once($this->get_plugin_path() . '/includes/field.php'); require_once($this->get_plugin_path() . '/includes/field-text.php'); require_once($this->get_plugin_path() . '/includes/field-textarea.php'); require_once($this->get_plugin_path() . '/includes/field-select.php'); require_once($this->get_plugin_path() . '/includes/form.php'); } /** * Retrieve the path to the main plugin directory. * * @access public * * @return string $plugin_path The path to the main plugin directory. */ public function get_plugin_path() { return $this->plugin_path; } /** * Modify the path to the main plugin directory. * * @access protected * * @param string $plugin_path The new path to the main plugin directory. */ protected function set_plugin_path($plugin_path) { $this->plugin_path = $plugin_path; } /** * Retrieve the form object. * * @access public * * @return string $form The form object. */ public function get_form() { return $this->form; } /** * Modify the form object. * * @access protected * * @param string $form The new form object. */ protected function set_form($form) { $this->form = $form; } } // initialize the plugin global $qbttc; $qbttc = new QBTTC();
export { <API key> } from './sync/card_service.js'; export { <API key> } from './sync/card_service.js'; export { HotkeysService } from './hotkeys_service.js'; export { ImageServiceManager } from './sync/image_service.js'; export { KeyValuePredicate, AndPredicate, OrPredicate, NotPredicate } from './<API key>/<API key>.js'; export { PersistenceService } from './persistence_service.js'; export { <API key> } from './<API key>.js'; export { SortService } from './sort_service.js'; export { StatusService } from './status_service.js'; export { <API key> } from './rng_service.js'; export * from './account';
# @brief helper function to turn pkgconfig files into ASKAP package.info # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # This file is part of the ASKAP software distribution. # The ASKAP software distribution is free software: you can redistribute it # or (at your option) any later version. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. import os import re import string def _replace_vars(lst, vardict): '''a generator to replace allcaps variables found in .pc files :param lst: a list of strings :param vardict: the dictionary of variable definitions ''' varrx = re.compile("\$\{([A-Z_]+)\}") for item in lst: vnames = varrx.search(item) if vnames: for v in vnames.groups(): dv = vardict.get(v, None) if dv is not None: replaced = varrx.sub(dv, item) yield replaced else: yield item def to_info(pkgfile=None): '''To be executed from the build.py directory. This will extract the information from a pkgconfig file and writes it to a ASKAPsoft 'package.info' file. This will only work if there is not already a 'package.info'. @param pkgfile The path to the .pc file. Default None, means look for a '.pc' file in 'install/lib/pkgconfig' ''' if os.path.exists("package.info"): # nothing to do return if not pkgfile: pcdir = "install/lib/pkgconfig" if not os.path.exists(pcdir): return files = os.listdir(pcdir) if not files: # assume no dependencies return # there should only be one pc file pkgfile = os.path.join(pcdir, files[0]) incdir = None libdir = None libs = [] outlibs=[] varnames = {} varrx = re.compile("\$\{\w*prefix\}/") f = file(pkgfile) for line in f.readlines(): line = line.strip() if line.count(":"): k,v = line.split(":") if k.startswith("Libs"): ls = v.split() for l in ls: if l.startswith("-l"): libs.append(l[2:]) if line.count("="): k,v = line.split("=") if varrx.search(v): v = varrx.sub("", v) varnames[k] = v f.close() outlibs = [i for i in _replace_vars(libs, varnames)] incdir = [i for i in _replace_vars([varnames["includedir"]], varnames)][0] if incdir == "include": incdir = None libdir = [i for i in _replace_vars([varnames["libdir"]], varnames)][0] if libdir == "lib": libdir = None outtxt = "# Auto-generated by build.py - DO NOT MODIFY\n" outtxt += "libs=%s\n" % string.join(outlibs) if libdir: outtxt += "libdir=%s\n" % libdir if incdir: outtxt += "incdir=%s\n" % incdir f = file("package.info", "w+") f.write(outtxt) f.close()
#include "fullscreenshell.h" #include "fullscreenshell_p.h" #include "output.h" #include "output_p.h" #include "surface.h" #include "surface_p.h" Q_LOGGING_CATEGORY(FSH_CLIENT_PROTOCOL, "greenisland.protocols.fullscreenshell.client") namespace GreenIsland { namespace Client { /* * <API key> */ <API key>::<API key>() : QtWayland::<API key>() , capabilities(FullScreenShell::NoCapability) { } void <API key>::<API key>(uint32_t capability) { Q_Q(FullScreenShell); FullScreenShell::Capabilities oldCapabilities = capabilities; if (capability & QtWayland::<API key>::<API key>) capabilities |= FullScreenShell::ArbitraryModes; if (capability & QtWayland::<API key>::<API key>) capabilities |= FullScreenShell::CursorPlane; if (oldCapabilities != capabilities) Q_EMIT q->capabilitiesChanged(); } /* * FullScreenShell */ FullScreenShell::FullScreenShell(QObject *parent) : QObject(parent) { } FullScreenShell::Capabilities FullScreenShell::capabilities() const { Q_D(const FullScreenShell); return d->capabilities; } void FullScreenShell::presentSurface(Surface *surface, Output *output, PresentMethod method) { Q_D(FullScreenShell); d->present_surface(SurfacePrivate::get(surface)->object(), static_cast<uint32_t>(method), OutputPrivate::get(output)->object()); } void FullScreenShell::hideOutput(Output *output) { Q_D(FullScreenShell); d->present_surface(Q_NULLPTR, QtWayland::<API key>::<API key>, OutputPrivate::get(output)->object()); } } // namespace Client } // namespace GreenIsland #include "moc_fullscreenshell.cpp"
package edu.ucsd.ncmir.WIB.client.core.messages; import edu.ucsd.ncmir.spl.LinearAlgebra.Matrix2D; import edu.ucsd.ncmir.WIB.client.core.message.Message; /** * * @author spl */ public class DisplayInitMessage extends Message { private final int _width; private final int _height; private final int _depth; private final int _tilesize; private final int _timesteps; private final String _atlas_name; private final int _page; private final Matrix2D _matrix; private final int _red_map; private final int _green_map; private final int _blue_map; public DisplayInitMessage( int width, int height, int depth, int tilesize, int timesteps, String atlas_name, int page, Matrix2D matrix, int red_map, int green_map, int blue_map ) { this._width = width; this._height = height; this._depth = depth; this._tilesize = tilesize; this._timesteps = timesteps; this._atlas_name = atlas_name; this._page = page; this._matrix = matrix; this._red_map = red_map; this._green_map = green_map; this._blue_map = blue_map; } /** * @return the width */ public int getWidth() { return this._width; } /** * @return the height */ public int getHeight() { return this._height; } /** * @return the depth */ public int getDepth() { return this._depth; } /** * @return the tilesize */ public int getTilesize() { return this._tilesize; } /** * @return the timesteps */ public int getTimesteps() { return this._timesteps; } /** * @return the atlas name */ public String getAtlasName() { return this._atlas_name; } /** * @return the atlas page */ public int getAtlasPage() { return this._page; } /** * @return the matrix */ public Matrix2D getMatrix() { return this._matrix; } /** * @return the red map */ public int getRedMap() { return this._red_map; } /** * @return the green map */ public int getGreenMap() { return this._green_map; } /** * @return the blue map */ public int getBlueMap() { return this._blue_map; } }
package com.veenvliet.seeyousoon; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.provider.Settings; public class SettingsActivity extends PreferenceActivity { @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <API key>(R.xml.preferences); Preference <API key> = (Preference) findPreference("<API key>"); <API key> .<API key>(new Preference.<API key>() { public boolean onPreferenceClick(Preference preference) { Intent viewIntent = new Intent( Settings.<API key>); startActivity(viewIntent); return true; } }); } }
#define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/bootmem.h> #include <linux/console.h> #include <linux/debugfs.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/dma-mapping.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/kernel.h> #include <linux/leds.h> #include <linux/memory.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/msm_mdp.h> #include <linux/proc_fs.h> #include <linux/pm_runtime.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/uaccess.h> #include <linux/version.h> #include <linux/vmalloc.h> #include <linux/sync.h> #include <linux/sw_sync.h> #include <linux/file.h> #include <linux/memory_alloc.h> #include <linux/kthread.h> #include <linux/of_address.h> #include <mach/board.h> #include <mach/memory.h> #include <mach/iommu.h> #include <mach/iommu_domains.h> #include <mach/msm_memtypes.h> #include "mdss_fb.h" #include "mdss_mdp.h" #include "<API key>.h" #ifdef <API key> #define MDSS_FB_NUM 3 #else #define MDSS_FB_NUM 2 #endif #define MAX_FBI_LIST 32 static struct fb_info *fbi_list[MAX_FBI_LIST]; static int fbi_list_index; static u32 <API key>[16] = { 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; static struct msm_mdp_interface *mdp_instance; static int mdss_fb_register(struct msm_fb_data_type *mfd); static int mdss_fb_open(struct fb_info *info, int user); static int mdss_fb_release(struct fb_info *info, int user); static int mdss_fb_release_all(struct fb_info *info, bool release_all); static int mdss_fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info); static int mdss_fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info); static int mdss_fb_set_par(struct fb_info *info); static int mdss_fb_blank_sub(int blank_mode, struct fb_info *info, int op_enable); static int mdss_fb_suspend_sub(struct msm_fb_data_type *mfd); static int mdss_fb_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg); static int <API key>(struct fb_info *info, struct vm_area_struct *vma); static int <API key>(struct msm_fb_data_type *mfd, size_t size); static void <API key>(struct msm_fb_data_type *mfd); static int <API key>(struct notifier_block *p, unsigned long val, void *data); static int <API key>(void *data); static int mdss_fb_pan_idle(struct msm_fb_data_type *mfd); static int <API key>(struct msm_fb_data_type *mfd, int event, void *arg); static void <API key>(struct msm_fb_data_type *mfd); void <API key>(unsigned long data) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)data; if (!mfd) { pr_err("%s mfd NULL\n", __func__); return; } mfd->no_update.value = <API key>; complete(&mfd->no_update.comp); } void <API key>(struct msm_fb_data_type *mfd) { if (!mfd) { pr_err("%s mfd NULL\n", __func__); return; } mutex_lock(&mfd->update.lock); if (mfd->update.ref_count > 0) { mutex_unlock(&mfd->update.lock); mfd->update.value = <API key>; complete(&mfd->update.comp); mutex_lock(&mfd->update.lock); } mutex_unlock(&mfd->update.lock); mutex_lock(&mfd->no_update.lock); if (mfd->no_update.ref_count > 0) { mutex_unlock(&mfd->no_update.lock); mfd->no_update.value = <API key>; complete(&mfd->no_update.comp); mutex_lock(&mfd->no_update.lock); } mutex_unlock(&mfd->no_update.lock); } static int <API key>(struct msm_fb_data_type *mfd, unsigned long *argp) { int ret; unsigned long notify = 0x0, to_user = 0x0; ret = copy_from_user(&notify, argp, sizeof(unsigned long)); if (ret) { pr_err("%s:ioctl failed\n", __func__); return ret; } if (notify > <API key>) return -EINVAL; if (notify == NOTIFY_UPDATE_INIT) { mutex_lock(&mfd->update.lock); mfd->update.init_done = true; mutex_unlock(&mfd->update.lock); ret = 1; } else if (notify == <API key>) { mutex_lock(&mfd->update.lock); mfd->update.init_done = false; mutex_unlock(&mfd->update.lock); complete(&mfd->update.comp); complete(&mfd->no_update.comp); ret = 1; } else if (mfd->update.is_suspend) { to_user = NOTIFY_TYPE_SUSPEND; mfd->update.is_suspend = 0; ret = 1; } else if (notify == NOTIFY_UPDATE_START) { mutex_lock(&mfd->update.lock); if (mfd->update.init_done) INIT_COMPLETION(mfd->update.comp); else { mutex_unlock(&mfd->update.lock); pr_err("notify update start called without init\n"); return -EINVAL; } mfd->update.ref_count++; mutex_unlock(&mfd->update.lock); ret = <API key>( &mfd->update.comp, 4 * HZ); mutex_lock(&mfd->update.lock); mfd->update.ref_count mutex_unlock(&mfd->update.lock); to_user = (unsigned int)mfd->update.value; if (mfd->update.type == NOTIFY_TYPE_SUSPEND) { to_user = (unsigned int)mfd->update.type; ret = 1; } } else if (notify == NOTIFY_UPDATE_STOP) { mutex_lock(&mfd->update.lock); if (mfd->update.init_done) INIT_COMPLETION(mfd->no_update.comp); else { mutex_unlock(&mfd->update.lock); pr_err("notify update stop called without init\n"); return -EINVAL; } mutex_unlock(&mfd->update.lock); mutex_lock(&mfd->no_update.lock); mfd->no_update.ref_count++; mutex_unlock(&mfd->no_update.lock); ret = <API key>( &mfd->no_update.comp, 4 * HZ); mutex_lock(&mfd->no_update.lock); mfd->no_update.ref_count mutex_unlock(&mfd->no_update.lock); to_user = (unsigned int)mfd->no_update.value; } else { if (mdss_fb_is_power_on(mfd)) { INIT_COMPLETION(mfd->power_off_comp); ret = <API key>( &mfd->power_off_comp, 1 * HZ); } } if (ret == 0) ret = -ETIMEDOUT; else if (ret > 0) ret = copy_to_user(argp, &to_user, sizeof(unsigned long)); return ret; } static int <API key>; static void <API key>(struct led_classdev *led_cdev, enum led_brightness value) { struct msm_fb_data_type *mfd = dev_get_drvdata(led_cdev->dev->parent); int bl_lvl; if (value > mfd->panel_info->brightness_max) value = mfd->panel_info->brightness_max; /* This maps android backlight level 0 to 255 into driver backlight level 0 to bl_max with rounding */ MDSS_BRIGHT_TO_BL(bl_lvl, value, mfd->panel_info->bl_max, mfd->panel_info->brightness_max); if (!bl_lvl && value) bl_lvl = 1; if (!IS_CALIB_MODE_BL(mfd) && (!mfd->ext_bl_ctrl || !value || !mfd->bl_level)) { mutex_lock(&mfd->bl_lock); <API key>(mfd, bl_lvl); mutex_unlock(&mfd->bl_lock); } } static struct led_classdev backlight_led = { .name = "lcd-backlight", .brightness = <API key>, .brightness_set = <API key>, }; static ssize_t mdss_fb_get_type(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret = 0; struct fb_info *fbi = dev_get_drvdata(dev); struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)fbi->par; switch (mfd->panel.type) { case NO_PANEL: ret = snprintf(buf, PAGE_SIZE, "no panel\n"); break; case HDMI_PANEL: ret = snprintf(buf, PAGE_SIZE, "hdmi panel\n"); break; case LVDS_PANEL: ret = snprintf(buf, PAGE_SIZE, "lvds panel\n"); break; case DTV_PANEL: ret = snprintf(buf, PAGE_SIZE, "dtv panel\n"); break; case MIPI_VIDEO_PANEL: ret = snprintf(buf, PAGE_SIZE, "mipi dsi video panel\n"); break; case MIPI_CMD_PANEL: ret = snprintf(buf, PAGE_SIZE, "mipi dsi cmd panel\n"); break; case WRITEBACK_PANEL: ret = snprintf(buf, PAGE_SIZE, "writeback panel\n"); break; case EDP_PANEL: ret = snprintf(buf, PAGE_SIZE, "edp panel\n"); break; default: ret = snprintf(buf, PAGE_SIZE, "unknown panel\n"); break; } return ret; } static void mdss_fb_parse_dt(struct msm_fb_data_type *mfd) { u32 data[2] = {0}; u32 panel_xres; struct platform_device *pdev = mfd->pdev; <API key>(pdev->dev.of_node, "qcom,mdss-fb-split", data, 2); panel_xres = mfd->panel_info->xres; if (data[0] && data[1]) { if (mfd->split_display) panel_xres *= 2; if (panel_xres == data[0] + data[1]) { mfd->split_fb_left = data[0]; mfd->split_fb_right = data[1]; } } else { if (mfd->split_display) mfd->split_fb_left = mfd->split_fb_right = panel_xres; else mfd->split_fb_left = mfd->split_fb_right = 0; } pr_info("split framebuffer left=%d right=%d\n", mfd->split_fb_left, mfd->split_fb_right); } static ssize_t mdss_fb_get_split(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret = 0; struct fb_info *fbi = dev_get_drvdata(dev); struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)fbi->par; ret = snprintf(buf, PAGE_SIZE, "%d %d\n", mfd->split_fb_left, mfd->split_fb_right); return ret; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *fbi = dev_get_drvdata(dev); struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)fbi->par; int ret; pr_debug("fb%d panel_power_state = %d\n", mfd->index, mfd->panel_power_state); ret = scnprintf(buf, PAGE_SIZE, "panel_power_on = %d\n", mfd->panel_power_state); return ret; } static void <API key>(struct work_struct *work) { struct delayed_work *dw = to_delayed_work(work); struct msm_fb_data_type *mfd = container_of(dw, struct msm_fb_data_type, lp_cooloff_work); mfd->lp_coff = 0; } static void <API key>(struct work_struct *work) { struct delayed_work *dw = to_delayed_work(work); struct msm_fb_data_type *mfd = container_of(dw, struct msm_fb_data_type, idle_notify_work); /* Notify idle-ness here */ pr_debug("Idle timeout %dms expired!\n", mfd->idle_time); sysfs_notify(&mfd->fbi->dev->kobj, NULL, "idle_notify"); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *fbi = dev_get_drvdata(dev); struct msm_fb_data_type *mfd = fbi->par; int ret; ret = scnprintf(buf, PAGE_SIZE, "%d", mfd->idle_time); return ret; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fb_info *fbi = dev_get_drvdata(dev); struct msm_fb_data_type *mfd = fbi->par; int rc = 0; int idle_time = 0; rc = kstrtoint(buf, 10, &idle_time); if (rc) { pr_err("kstrtoint failed. rc=%d\n", rc); return rc; } pr_debug("Idle time = %d\n", idle_time); mfd->idle_time = idle_time; return count; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *fbi = dev_get_drvdata(dev); struct msm_fb_data_type *mfd = fbi->par; int ret; ret = scnprintf(buf, PAGE_SIZE, "%s", work_busy(&mfd->idle_notify_work.work) ? "no" : "yes"); return ret; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *fbi = dev_get_drvdata(dev); struct msm_fb_data_type *mfd = fbi->par; struct mdss_panel_info *pinfo = mfd->panel_info; int ret; ret = scnprintf(buf, PAGE_SIZE, "pu_en=%d\nxstart=%d\nwalign=%d\nystart=%d\nhalign=%d\n" "min_w=%d\nmin_h=%d\ndyn_fps_en=%d\nmin_fps=%d\n" "max_fps=%d\n", pinfo-><API key>, pinfo->xstart_pix_align, pinfo->width_pix_align, pinfo->ystart_pix_align, pinfo->height_pix_align, pinfo->min_width, pinfo->min_height, pinfo->dynamic_fps, pinfo->min_fps, pinfo->max_fps); return ret; } /* * mdss_fb_lpm_enable() - Function to Control LowPowerMode * @mfd: Framebuffer data structure for display * @mode: Enabled/Disable LowPowerMode * 1: Enter into LowPowerMode * 0: Exit from LowPowerMode * * This Function dynamically switches to and from LowPowerMode * based on the argument @mode. */ static int mdss_fb_lpm_enable(struct msm_fb_data_type *mfd, int mode) { int ret = 0; u32 bl_lvl = 0; struct mdss_panel_info *pinfo = NULL; struct mdss_panel_data *pdata; if (!mfd || !mfd->panel_info) return -EINVAL; pinfo = mfd->panel_info; if (!pinfo->mipi.<API key>) { pr_warn("Panel does not support dynamic switch!\n"); return 0; } if (mode == pinfo->mipi.mode) { pr_debug("Already in requested mode!\n"); return 0; } pdata = dev_get_platdata(&mfd->pdev->dev); pr_debug("Enter mode: %d\n", mode); pdata->panel_info.<API key> = true; mutex_lock(&mfd->bl_lock); bl_lvl = mfd->bl_level; <API key>(mfd, 0); mutex_unlock(&mfd->bl_lock); lock_fb_info(mfd->fbi); ret = mdss_fb_blank_sub(FB_BLANK_POWERDOWN, mfd->fbi, mfd->op_enable); if (ret) { pr_err("can't turn off display!\n"); unlock_fb_info(mfd->fbi); return ret; } mfd->op_enable = false; ret = mfd->mdp.configure_panel(mfd, mode); <API key>(mfd); mfd->op_enable = true; ret = mdss_fb_blank_sub(FB_BLANK_UNBLANK, mfd->fbi, mfd->op_enable); if (ret) { pr_err("can't turn on display!\n"); unlock_fb_info(mfd->fbi); return ret; } unlock_fb_info(mfd->fbi); mutex_lock(&mfd->bl_lock); mfd->bl_updated = true; <API key>(mfd, bl_lvl); mutex_unlock(&mfd->bl_lock); pdata->panel_info.<API key> = false; pdata->panel_info.is_lpm_mode = mode ? 1 : 0; if (ret) { pr_err("can't turn on display!\n"); return ret; } pr_debug("Exit mode: %d\n", mode); return 0; } static int pcc_r = 32768, pcc_g = 32768, pcc_b = 32768; static ssize_t mdss_get_rgb(struct device *dev, struct device_attribute *attr, char *buf) { u32 copyback = 0; struct mdp_pcc_cfg_data pcc_cfg; memset(&pcc_cfg, 0, sizeof(struct mdp_pcc_cfg_data)); pcc_cfg.block = <API key>; pcc_cfg.ops = MDP_PP_OPS_READ; mdss_mdp_pcc_config(&pcc_cfg, &copyback); /* We disable pcc when using default values and reg * are zeroed on pp resume, so ignore empty values. */ if (pcc_cfg.r.r && pcc_cfg.g.g && pcc_cfg.b.b) { pcc_r = pcc_cfg.r.r; pcc_g = pcc_cfg.g.g; pcc_b = pcc_cfg.b.b; } return scnprintf(buf, PAGE_SIZE, "%d %d %d\n", pcc_r, pcc_g, pcc_b); } static ssize_t mdss_set_rgb(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { uint32_t r = 0, g = 0, b = 0; struct mdp_pcc_cfg_data pcc_cfg; u32 copyback = 0; if (count > 19) return -EINVAL; sscanf(buf, "%d %d %d", &r, &g, &b); if (r < 0 || r > 32768) return -EINVAL; if (g < 0 || g > 32768) return -EINVAL; if (b < 0 || b > 32768) return -EINVAL; pr_info("%s: r=%d g=%d b=%d\n", __func__, r, g, b); memset(&pcc_cfg, 0, sizeof(struct mdp_pcc_cfg_data)); pcc_cfg.block = <API key>; if (r == 32768 && g == 32768 && b == 32768) pcc_cfg.ops = MDP_PP_OPS_DISABLE; else pcc_cfg.ops = MDP_PP_OPS_ENABLE; pcc_cfg.ops |= MDP_PP_OPS_WRITE; pcc_cfg.r.r = r; pcc_cfg.g.g = g; pcc_cfg.b.b = b; if (mdss_mdp_pcc_config(&pcc_cfg, &copyback) == 0) { pcc_r = r; pcc_g = g; pcc_b = b; return count; } return -EINVAL; } static DEVICE_ATTR(msm_fb_type, S_IRUGO, mdss_fb_get_type, NULL); static DEVICE_ATTR(msm_fb_split, S_IRUGO, mdss_fb_get_split, NULL); static DEVICE_ATTR(show_blank_event, S_IRUGO, <API key>, NULL); static DEVICE_ATTR(idle_time, S_IRUGO | S_IWUSR | S_IWGRP, <API key>, <API key>); static DEVICE_ATTR(idle_notify, S_IRUGO, <API key>, NULL); static DEVICE_ATTR(msm_fb_panel_info, S_IRUGO, <API key>, NULL); static DEVICE_ATTR(rgb, S_IRUGO | S_IWUSR | S_IWGRP, mdss_get_rgb, mdss_set_rgb); static struct attribute *mdss_fb_attrs[] = { &<API key>.attr, &<API key>.attr, &<API key>.attr, &dev_attr_idle_time.attr, &<API key>.attr, &<API key>.attr, &dev_attr_rgb.attr, NULL, }; static struct attribute_group mdss_fb_attr_group = { .attrs = mdss_fb_attrs, }; static int <API key>(struct msm_fb_data_type *mfd) { int rc; rc = sysfs_create_group(&mfd->fbi->dev->kobj, &mdss_fb_attr_group); if (rc) pr_err("sysfs group creation failed, rc=%d\n", rc); return rc; } static void <API key>(struct msm_fb_data_type *mfd) { sysfs_remove_group(&mfd->fbi->dev->kobj, &mdss_fb_attr_group); } static void mdss_fb_shutdown(struct platform_device *pdev) { struct msm_fb_data_type *mfd = <API key>(pdev); mfd->shutdown_pending = true; lock_fb_info(mfd->fbi); mdss_fb_release_all(mfd->fbi, true); unlock_fb_info(mfd->fbi); } static int mdss_fb_probe(struct platform_device *pdev) { struct msm_fb_data_type *mfd = NULL; struct mdss_panel_data *pdata; struct fb_info *fbi; int rc; if (fbi_list_index >= MAX_FBI_LIST) return -ENOMEM; pdata = dev_get_platdata(&pdev->dev); if (!pdata) return -EPROBE_DEFER; /* * alloc framebuffer info + par data */ fbi = framebuffer_alloc(sizeof(struct msm_fb_data_type), NULL); if (fbi == NULL) { pr_err("can't allocate framebuffer info data!\n"); return -ENOMEM; } mfd = (struct msm_fb_data_type *)fbi->par; mfd->key = MFD_KEY; mfd->fbi = fbi; mfd->panel_info = &pdata->panel_info; mfd->panel.type = pdata->panel_info.type; mfd->panel.id = mfd->index; mfd->fb_page = MDSS_FB_NUM; mfd->index = fbi_list_index; mfd-><API key> = <API key>; mfd->ext_ad_ctrl = -1; mfd->bl_level = 0; mfd-><API key> = 0; mfd->bl_scale = 1024; mfd->bl_min_lvl = 30; mfd->ad_bl_level = 0; mfd->fb_imgType = MDP_RGBA_8888; mfd->pdev = pdev; if (pdata->next) mfd->split_display = true; mfd->mdp = *mdp_instance; INIT_LIST_HEAD(&mfd->proc_list); mutex_init(&mfd->bl_lock); fbi_list[fbi_list_index++] = fbi; <API key>(pdev, mfd); rc = mdss_fb_register(mfd); if (rc) return rc; if (mfd->mdp.init_fnc) { rc = mfd->mdp.init_fnc(mfd); if (rc) { pr_err("init_fnc failed\n"); return rc; } } rc = <API key>(mfd->fbi->dev); if (rc < 0) pr_err("pm_runtime: fail to set active.\n"); pm_runtime_enable(mfd->fbi->dev); /* android supports only one lcd-backlight/lcd for now */ if (!<API key>) { backlight_led.brightness = mfd->panel_info->brightness_max; backlight_led.max_brightness = mfd->panel_info->brightness_max; if (<API key>(&pdev->dev, &backlight_led)) pr_err("<API key> failed\n"); else <API key> = 1; } <API key>(mfd); <API key>(mfd, <API key>, fbi); mfd->mdp_sync_pt_data.fence_name = "mdp-fence"; if (mfd->mdp_sync_pt_data.timeline == NULL) { char timeline_name[16]; snprintf(timeline_name, sizeof(timeline_name), "mdss_fb_%d", mfd->index); mfd->mdp_sync_pt_data.timeline = <API key>(timeline_name); if (mfd->mdp_sync_pt_data.timeline == NULL) { pr_err("cannot create release fence time line\n"); return -ENOMEM; } mfd->mdp_sync_pt_data.notifier.notifier_call = <API key>; } <API key>(mfd); if (mfd->mdp.splash_init_fnc) mfd->mdp.splash_init_fnc(mfd); INIT_DELAYED_WORK(&mfd->idle_notify_work, <API key>); INIT_DELAYED_WORK(&mfd->lp_cooloff_work, <API key>); return rc; } static void <API key>(struct msm_fb_data_type *mfd) { if (!mfd) return; switch (mfd->panel.type) { case WRITEBACK_PANEL: mfd->mdp_sync_pt_data.threshold = 1; mfd->mdp_sync_pt_data.retire_threshold = 0; break; case MIPI_CMD_PANEL: mfd->mdp_sync_pt_data.threshold = 1; mfd->mdp_sync_pt_data.retire_threshold = 1; break; default: mfd->mdp_sync_pt_data.threshold = 2; mfd->mdp_sync_pt_data.retire_threshold = 0; break; } } static int mdss_fb_remove(struct platform_device *pdev) { struct msm_fb_data_type *mfd; mfd = (struct msm_fb_data_type *)<API key>(pdev); if (!mfd) return -ENODEV; <API key>(mfd); pm_runtime_disable(mfd->fbi->dev); if (mfd->key != MFD_KEY) return -EINVAL; if (mdss_fb_suspend_sub(mfd)) pr_err("msm_fb_remove: can't stop the device %d\n", mfd->index); /* remove /dev/fb* */ <API key>(mfd->fbi); if (<API key>) { <API key> = 0; <API key>(&backlight_led); } return 0; } static int <API key>(struct msm_fb_data_type *mfd, int event, void *arg) { struct mdss_panel_data *pdata; pdata = dev_get_platdata(&mfd->pdev->dev); if (!pdata) { pr_err("no panel connected\n"); return -ENODEV; } pr_debug("sending event=%d for fb%d\n", event, mfd->index); if (pdata->event_handler) return pdata->event_handler(pdata, event, arg); return 0; } static int mdss_fb_suspend_sub(struct msm_fb_data_type *mfd) { int ret = 0; if ((!mfd) || (mfd->key != MFD_KEY)) return 0; pr_debug("mdss_fb suspend index=%d\n", mfd->index); mdss_fb_pan_idle(mfd); ret = <API key>(mfd, MDSS_EVENT_SUSPEND, NULL); if (ret) { pr_warn("unable to suspend fb%d (%d)\n", mfd->index, ret); return ret; } mfd->suspend.op_enable = mfd->op_enable; mfd->suspend.panel_power_state = mfd->panel_power_state; if (mfd->op_enable) { /* * Ideally, display should have been blanked by now. * If not, then blank the display */ ret = mdss_fb_blank_sub(FB_BLANK_POWERDOWN, mfd->fbi, mfd->suspend.op_enable); if (ret) { pr_warn("can't turn off display!\n"); return ret; } mfd->op_enable = false; fb_set_suspend(mfd->fbi, <API key>); } return 0; } static int mdss_fb_resume_sub(struct msm_fb_data_type *mfd) { int ret = 0; if ((!mfd) || (mfd->key != MFD_KEY)) return 0; INIT_COMPLETION(mfd->power_set_comp); mfd->is_power_setting = true; pr_debug("mdss_fb resume index=%d\n", mfd->index); mdss_fb_pan_idle(mfd); ret = <API key>(mfd, MDSS_EVENT_RESUME, NULL); if (ret) { pr_warn("unable to resume fb%d (%d)\n", mfd->index, ret); return ret; } /* resume state var recover */ mfd->op_enable = mfd->suspend.op_enable; if (<API key>(mfd->suspend.panel_power_state)) { ret = mdss_fb_blank_sub(FB_BLANK_UNBLANK, mfd->fbi, mfd->op_enable); if (ret) pr_warn("can't turn on display!\n"); else fb_set_suspend(mfd->fbi, <API key>); } mfd->is_power_setting = false; complete_all(&mfd->power_set_comp); return ret; } #if defined(CONFIG_PM) && !defined(CONFIG_PM_SLEEP) static int mdss_fb_suspend(struct platform_device *pdev, pm_message_t state) { struct msm_fb_data_type *mfd = <API key>(pdev); if (!mfd) return -ENODEV; dev_dbg(&pdev->dev, "display suspend\n"); return mdss_fb_suspend_sub(mfd); } static int mdss_fb_resume(struct platform_device *pdev) { struct msm_fb_data_type *mfd = <API key>(pdev); if (!mfd) return -ENODEV; dev_dbg(&pdev->dev, "display resume\n"); return mdss_fb_resume_sub(mfd); } #else #define mdss_fb_suspend NULL #define mdss_fb_resume NULL #endif #ifdef CONFIG_PM_SLEEP static int mdss_fb_pm_suspend(struct device *dev) { struct msm_fb_data_type *mfd = dev_get_drvdata(dev); if (!mfd) return -ENODEV; dev_dbg(dev, "display pm suspend\n"); return mdss_fb_suspend_sub(mfd); } static int mdss_fb_pm_resume(struct device *dev) { struct msm_fb_data_type *mfd = dev_get_drvdata(dev); if (!mfd) return -ENODEV; dev_dbg(dev, "display pm resume\n"); /* * It is possible that the runtime status of the fb device may * have been active when the system was suspended. Reset the runtime * status to suspended state after a complete system resume. */ pm_runtime_disable(dev); <API key>(dev); pm_runtime_enable(dev); return mdss_fb_resume_sub(mfd); } #endif static const struct dev_pm_ops mdss_fb_pm_ops = { <API key>(mdss_fb_pm_suspend, mdss_fb_pm_resume) }; static const struct of_device_id mdss_fb_dt_match[] = { { .compatible = "qcom,mdss-fb",}, {} }; EXPORT_COMPAT("qcom,mdss-fb"); static struct platform_driver mdss_fb_driver = { .probe = mdss_fb_probe, .remove = mdss_fb_remove, .suspend = mdss_fb_suspend, .resume = mdss_fb_resume, .shutdown = mdss_fb_shutdown, .driver = { .name = "mdss_fb", .of_match_table = mdss_fb_dt_match, .pm = &mdss_fb_pm_ops, }, }; static void mdss_fb_scale_bl(struct msm_fb_data_type *mfd, u32 *bl_lvl) { u32 temp = *bl_lvl; pr_debug("input = %d, scale = %d", temp, mfd->bl_scale); if (temp >= mfd->bl_min_lvl) { if (temp > mfd->panel_info->bl_max) { pr_warn("%s: invalid bl level\n", __func__); temp = mfd->panel_info->bl_max; } if (mfd->bl_scale > 1024) { pr_warn("%s: invalid bl scale\n", __func__); mfd->bl_scale = 1024; } /* * bl_scale is the numerator of * scaling fraction (x/1024) */ temp = (temp * mfd->bl_scale) / 1024; /*if less than minimum level, use min level*/ if (temp < mfd->bl_min_lvl) temp = mfd->bl_min_lvl; } pr_debug("output = %d", temp); (*bl_lvl) = temp; } /* must call this function from within mfd->bl_lock */ void <API key>(struct msm_fb_data_type *mfd, u32 bkl_lvl) { struct mdss_panel_data *pdata; u32 temp = bkl_lvl; bool bl_notify_needed = false; if ((((<API key>(mfd) && mfd->dcm_state != DCM_ENTER) || !mfd->bl_updated) && !IS_CALIB_MODE_BL(mfd)) || mfd->panel_info->cont_splash_enabled) { mfd->unset_bl_level = bkl_lvl; return; } else { mfd->unset_bl_level = 0; } pdata = dev_get_platdata(&mfd->pdev->dev); if ((pdata) && (pdata->set_backlight)) { if (mfd->mdp.ad_calc_bl) (*mfd->mdp.ad_calc_bl)(mfd, temp, &temp, &bl_notify_needed); if (bl_notify_needed) <API key>(mfd); mfd-><API key> = mfd->bl_level_scaled; if (!IS_CALIB_MODE_BL(mfd)) mdss_fb_scale_bl(mfd, &temp); /* * Even though backlight has been scaled, want to show that * backlight has been set to bkl_lvl to those that read from * sysfs node. Thus, need to set bl_level even if it appears * the backlight has already been set to the level it is at, * as well as setting bl_level to bkl_lvl even though the * backlight has been set to the scaled value. */ if (mfd->bl_level_scaled == temp) { mfd->bl_level = bkl_lvl; } else { pr_debug("backlight sent to panel :%d\n", temp); pdata->set_backlight(pdata, temp); mfd->bl_level = bkl_lvl; mfd->bl_level_scaled = temp; } } } void <API key>(struct msm_fb_data_type *mfd) { struct mdss_panel_data *pdata; u32 temp; bool bl_notify = false; if (mfd->unset_bl_level) { mutex_lock(&mfd->bl_lock); if (!mfd->bl_updated) { pdata = dev_get_platdata(&mfd->pdev->dev); if ((pdata) && (pdata->set_backlight)) { mfd->bl_level = mfd->unset_bl_level; temp = mfd->bl_level; if (mfd->mdp.ad_calc_bl) (*mfd->mdp.ad_calc_bl)(mfd, temp, &temp, &bl_notify); if (bl_notify) <API key>(mfd); pdata->set_backlight(pdata, temp); mfd->bl_level_scaled = mfd->unset_bl_level; mfd->bl_updated = 1; } } mutex_unlock(&mfd->bl_lock); } } static int <API key>(struct msm_fb_data_type *mfd) { int ret = 0; pr_debug("%pS: start display thread fb%d\n", <API key>(0), mfd->index); atomic_set(&mfd->commits_pending, 0); mfd->disp_thread = kthread_run(<API key>, mfd, "mdss_fb%d", mfd->index); if (IS_ERR(mfd->disp_thread)) { pr_err("ERROR: unable to start display thread %d\n", mfd->index); ret = PTR_ERR(mfd->disp_thread); mfd->disp_thread = NULL; } return ret; } static void <API key>(struct msm_fb_data_type *mfd) { pr_debug("%pS: stop display thread fb%d\n", <API key>(0), mfd->index); kthread_stop(mfd->disp_thread); mfd->disp_thread = NULL; } static int mdss_fb_unblank_sub(struct msm_fb_data_type *mfd) { int ret = 0; int cur_power_state; if (!mfd) return -EINVAL; /* Start Display thread */ if (mfd->disp_thread == NULL) { ret = <API key>(mfd); if (IS_ERR_VALUE(ret)) return ret; } cur_power_state = mfd->panel_power_state; if (!<API key>(cur_power_state) && mfd->mdp.on_fnc) { ret = mfd->mdp.on_fnc(mfd); if (ret == 0) { mfd->panel_power_state = MDSS_PANEL_POWER_ON; mfd->panel_info->panel_dead = false; } else if (mfd->disp_thread) { <API key>(mfd); goto error; } mutex_lock(&mfd->update.lock); mfd->update.type = NOTIFY_TYPE_UPDATE; mfd->update.is_suspend = 0; mutex_unlock(&mfd->update.lock); /* Start the work thread to signal idle time */ if (mfd->idle_time) <API key>(&mfd->idle_notify_work, msecs_to_jiffies(mfd->idle_time)); } error: return ret; } static int mdss_fb_blank_sub(int blank_mode, struct fb_info *info, int op_enable) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int ret = 0; int cur_power_state, req_power_state = <API key>; if (!mfd || !op_enable) return -EPERM; if (mfd->dcm_state == DCM_ENTER) return -EPERM; pr_debug("%pS mode:%d\n", <API key>(0), blank_mode); cur_power_state = mfd->panel_power_state; /* * If doze mode is requested for video mode panels, treat * the request as full unblank as there are no low power mode * settings for video mode panels. */ if ((<API key> == blank_mode) && (mfd->panel_info->type != MIPI_CMD_PANEL)) { pr_debug("Doze mode only valid for cmd mode panels\n"); if (<API key>(cur_power_state)) return 0; else blank_mode = FB_BLANK_UNBLANK; } switch (blank_mode) { case FB_BLANK_UNBLANK: pr_debug("unblank called. cur pwr state=%d\n", cur_power_state); ret = mdss_fb_unblank_sub(mfd); break; case <API key>: pr_debug("Doze power mode requested\n"); /* * If doze mode is requested when panel is already off, * then first unblank the panel before entering doze mode */ if (<API key>(mfd) && mfd->mdp.on_fnc) { if (mfd->lp_coff) { mfd->lp_coff = 0; } else { pr_debug("off --> doze. switch to on first\n"); ret = mdss_fb_unblank_sub(mfd); } } break; case <API key>: case FB_BLANK_NORMAL: case FB_BLANK_POWERDOWN: default: pr_debug("blank powerdown called. cur mode=%d, req mode=%d\n", cur_power_state, req_power_state); if (mdss_fb_is_power_on(mfd) && mfd->mdp.off_fnc) { int bl_level_old; cur_power_state = mfd->panel_power_state; mutex_lock(&mfd->update.lock); mfd->update.type = NOTIFY_TYPE_SUSPEND; mfd->update.is_suspend = 1; mutex_unlock(&mfd->update.lock); complete(&mfd->update.comp); del_timer(&mfd->no_update.timer); mfd->no_update.value = NOTIFY_TYPE_SUSPEND; complete(&mfd->no_update.comp); mfd->op_enable = false; mutex_lock(&mfd->bl_lock); if (mfd->bl_updated) bl_level_old = mfd->bl_level; else bl_level_old = mfd->unset_bl_level; if (<API key>(req_power_state)) { /* Stop Display thread */ if (mfd->disp_thread) <API key>(mfd); <API key>(mfd, 0); mfd->unset_bl_level = bl_level_old; mfd->bl_updated = 0; } mfd->panel_power_state = req_power_state; mutex_unlock(&mfd->bl_lock); ret = mfd->mdp.off_fnc(mfd); if (ret) mfd->panel_power_state = cur_power_state; else if (<API key>(req_power_state)) <API key>(mfd); mfd->op_enable = true; complete(&mfd->power_off_comp); mfd->lp_coff = 1; <API key>(&mfd->lp_cooloff_work, msecs_to_jiffies(FB_LP_COOLOFF)); } break; } /* Notify listeners */ sysfs_notify(&mfd->fbi->dev->kobj, NULL, "show_blank_event"); return ret; } static int mdss_fb_blank(int blank_mode, struct fb_info *info) { struct mdss_panel_data *pdata; struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; mdss_fb_pan_idle(mfd); if (mfd->op_enable == 0) { if (blank_mode == FB_BLANK_UNBLANK || blank_mode == <API key>) mfd->suspend.panel_power_state = MDSS_PANEL_POWER_ON; else mfd->suspend.panel_power_state = <API key>; return 0; } pr_debug("mode: %d\n", blank_mode); pdata = dev_get_platdata(&mfd->pdev->dev); if (pdata->panel_info.is_lpm_mode && blank_mode == FB_BLANK_UNBLANK) { pr_debug("panel is in lpm mode\n"); mfd->mdp.configure_panel(mfd, 0); <API key>(mfd); pdata->panel_info.is_lpm_mode = false; } return mdss_fb_blank_sub(blank_mode, info, mfd->op_enable); } static inline int <API key>(struct msm_fb_data_type *mfd) { mfd->fb_ion_client = <API key>(-1 , "mdss_fb_iclient"); if (IS_ERR_OR_NULL(mfd->fb_ion_client)) { pr_err("Err:client not created, val %d\n", PTR_RET(mfd->fb_ion_client)); mfd->fb_ion_client = NULL; return PTR_RET(mfd->fb_ion_client); } return 0; } void <API key>(struct msm_fb_data_type *mfd) { if (!mfd) { pr_err("no mfd\n"); return; } if (!mfd->fbi->screen_base) return; if (!mfd->fb_ion_client || !mfd->fb_ion_handle) { pr_err("invalid input parameters for fb%d\n", mfd->index); return; } mfd->fbi->screen_base = NULL; mfd->fbi->fix.smem_start = 0; ion_unmap_kernel(mfd->fb_ion_client, mfd->fb_ion_handle); if (mfd->mdp.<API key>) { ion_unmap_iommu(mfd->fb_ion_client, mfd->fb_ion_handle, mfd->mdp.<API key>(), 0); } ion_free(mfd->fb_ion_client, mfd->fb_ion_handle); mfd->fb_ion_handle = NULL; } int <API key>(struct msm_fb_data_type *mfd, size_t fb_size) { unsigned long buf_size; int rc; void *vaddr; if (!mfd) { pr_err("Invalid input param - no mfd"); return -EINVAL; } if (!mfd->fb_ion_client) { rc = <API key>(mfd); if (rc < 0) { pr_err("fb ion client couldn't be created - %d\n", rc); return rc; } } pr_debug("size for mmap = %zu", fb_size); mfd->fb_ion_handle = ion_alloc(mfd->fb_ion_client, fb_size, SZ_4K, ION_HEAP(ION_SYSTEM_HEAP_ID), 0); if (IS_ERR_OR_NULL(mfd->fb_ion_handle)) { pr_err("unable to alloc fbmem from ion - %ld\n", PTR_ERR(mfd->fb_ion_handle)); return PTR_ERR(mfd->fb_ion_handle); } if (mfd->mdp.<API key>) { rc = ion_map_iommu(mfd->fb_ion_client, mfd->fb_ion_handle, mfd->mdp.<API key>(), 0, SZ_4K, 0, &mfd->iova, &buf_size, 0, 0); if (rc) { pr_err("Cannot map fb_mem to IOMMU. rc=%d\n", rc); goto fb_mmap_failed; } } else { pr_err("No IOMMU Domain"); rc = -EINVAL; goto fb_mmap_failed; } vaddr = ion_map_kernel(mfd->fb_ion_client, mfd->fb_ion_handle); if (IS_ERR_OR_NULL(vaddr)) { pr_err("ION memory mapping failed - %ld\n", PTR_ERR(vaddr)); rc = PTR_ERR(vaddr); if (mfd->mdp.<API key>) { ion_unmap_iommu(mfd->fb_ion_client, mfd->fb_ion_handle, mfd->mdp.<API key>(), 0); } goto fb_mmap_failed; } pr_debug("alloc 0x%zuB vaddr = %p (%pa iova) for fb%d\n", fb_size, vaddr, &mfd->iova, mfd->index); mfd->fbi->screen_base = (char *) vaddr; mfd->fbi->fix.smem_start = (unsigned int) mfd->iova; mfd->fbi->fix.smem_len = fb_size; return rc; fb_mmap_failed: ion_free(mfd->fb_ion_client, mfd->fb_ion_handle); return rc; } /** * <API key>() - Custom fb mmap() function for MSM driver. * * @info - Framebuffer info. * @vma - VM area which is part of the process virtual memory. * * This framebuffer mmap function differs from standard mmap() function by * allowing for customized page-protection and dynamically allocate framebuffer * memory from system heap and map to iommu virtual address. * * Return: virtual address is returned through vma */ static int <API key>(struct fb_info *info, struct vm_area_struct *vma) { int rc = 0; size_t req_size, fb_size; struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct sg_table *table; unsigned long addr = vma->vm_start; unsigned long offset = vma->vm_pgoff * PAGE_SIZE; struct scatterlist *sg; unsigned int i; struct page *page; if (!mfd || !mfd->pdev || !mfd->pdev->dev.of_node) { pr_err("Invalid device node\n"); return -ENODEV; } req_size = vma->vm_end - vma->vm_start; fb_size = mfd->fbi->fix.smem_len; if (req_size > fb_size) { pr_warn("requested map is greater than framebuffer"); return -EOVERFLOW; } if (!mfd->fbi->screen_base) { rc = <API key>(mfd, fb_size); if (rc < 0) { pr_err("fb mmap failed!!!!"); return rc; } } table = ion_sg_table(mfd->fb_ion_client, mfd->fb_ion_handle); if (IS_ERR(table)) { pr_err("Unable to get sg_table from ion:%ld\n", PTR_ERR(table)); mfd->fbi->screen_base = NULL; return PTR_ERR(table); } else if (!table) { pr_err("sg_list is NULL\n"); mfd->fbi->screen_base = NULL; return -EINVAL; } page = sg_page(table->sgl); if (page) { for_each_sg(table->sgl, sg, table->nents, i) { unsigned long remainder = vma->vm_end - addr; unsigned long len = sg->length; page = sg_page(sg); if (offset >= sg->length) { offset -= sg->length; continue; } else if (offset) { page += offset / PAGE_SIZE; len = sg->length - offset; offset = 0; } len = min(len, remainder); if (mfd-><API key> == <API key>) vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); pr_debug("vma=%p, addr=%x len=%ld", vma, (unsigned int)addr, len); pr_cont("vm_start=%x vm_end=%x vm_page_prot=%ld\n", (unsigned int)vma->vm_start, (unsigned int)vma->vm_end, (unsigned long int)vma->vm_page_prot); io_remap_pfn_range(vma, addr, page_to_pfn(page), len, vma->vm_page_prot); addr += len; if (addr >= vma->vm_end) break; } } else { pr_err("PAGE is null\n"); <API key>(mfd); return -ENOMEM; } return rc; } /* * <API key>() - Custom fb mmap() function for MSM driver. * * @info - Framebuffer info. * @vma - VM area which is part of the process virtual memory. * * This framebuffer mmap function differs from standard mmap() function as * map to framebuffer memory from the CMA memory which is allocated during * bootup. * * Return: virtual address is returned through vma */ static int <API key>(struct fb_info *info, struct vm_area_struct *vma) { /* Get frame buffer memory range. */ unsigned long start = info->fix.smem_start; u32 len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.smem_len); unsigned long off = vma->vm_pgoff << PAGE_SHIFT; struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; if (!start) { pr_warn("No framebuffer memory is allocated\n"); return -ENOMEM; } /* Set VM flags. */ start &= PAGE_MASK; if ((vma->vm_end <= vma->vm_start) || (off >= len) || ((vma->vm_end - vma->vm_start) > (len - off))) return -EINVAL; off += start; if (off < start) return -EINVAL; vma->vm_pgoff = off >> PAGE_SHIFT; /* This is an IO map - tell maydump to skip this VMA */ vma->vm_flags |= VM_IO; if (mfd-><API key> == <API key>) vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); /* Remap the frame buffer I/O range */ if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot)) return -EAGAIN; return 0; } static int mdss_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int rc = 0; if (!info->fix.smem_start && !mfd->fb_ion_handle) rc = <API key>(info, vma); else rc = <API key>(info, vma); if (rc < 0) pr_err("fb mmap failed with rc = %d", rc); return rc; } static struct fb_ops mdss_fb_ops = { .owner = THIS_MODULE, .fb_open = mdss_fb_open, .fb_release = mdss_fb_release, .fb_check_var = mdss_fb_check_var, /* vinfo check */ .fb_set_par = mdss_fb_set_par, /* set the video mode */ .fb_blank = mdss_fb_blank, /* blank display */ .fb_pan_display = mdss_fb_pan_display, /* pan display */ .fb_ioctl = mdss_fb_ioctl, /* perform fb specific ioctl */ #ifdef CONFIG_COMPAT .fb_compat_ioctl = <API key>, #endif .fb_mmap = mdss_fb_mmap, }; static int <API key>(struct msm_fb_data_type *mfd, int dom) { void *virt = NULL; phys_addr_t phys = 0; size_t size = 0; struct platform_device *pdev = mfd->pdev; int rc = 0; struct device_node *fbmem_pnode = NULL; if (!pdev || !pdev->dev.of_node) { pr_err("Invalid device node\n"); return -ENODEV; } fbmem_pnode = of_parse_phandle(pdev->dev.of_node, "linux,contiguous-region", 0); if (!fbmem_pnode) { pr_debug("fbmem is not reserved for %s\n", pdev->name); mfd->fbi->screen_base = NULL; mfd->fbi->fix.smem_start = 0; return 0; } else { const u32 *addr; u64 len; addr = of_get_address(fbmem_pnode, 0, &len, NULL); if (!addr) { pr_err("fbmem size is not specified\n"); of_node_put(fbmem_pnode); return -EINVAL; } size = (size_t)len; of_node_put(fbmem_pnode); } pr_debug("%s frame buffer reserve_size=0x%zx\n", __func__, size); if (size < PAGE_ALIGN(mfd->fbi->fix.line_length * mfd->fbi->var.yres_virtual)) pr_warn("reserve size is smaller than framebuffer size\n"); virt = dma_alloc_coherent(&pdev->dev, size, &phys, GFP_KERNEL); if (!virt) { pr_err("unable to alloc fbmem size=%zx\n", size); return -ENOMEM; } rc = <API key>(phys, dom, 0, size, SZ_4K, 0, &mfd->iova); if (rc) pr_warn("Cannot map fb_mem %pa to IOMMU. rc=%d\n", &phys, rc); pr_debug("alloc 0x%zxB @ (%pa phys) (0x%p virt) (%pa iova) for fb%d\n", size, &phys, virt, &mfd->iova, mfd->index); mfd->fbi->screen_base = virt; mfd->fbi->fix.smem_start = phys; mfd->fbi->fix.smem_len = size; return 0; } static int mdss_fb_alloc_fbmem(struct msm_fb_data_type *mfd) { if (mfd->mdp.fb_mem_alloc_fnc) { return mfd->mdp.fb_mem_alloc_fnc(mfd); } else if (mfd->mdp.<API key>) { int dom = mfd->mdp.<API key>(); if (dom >= 0) return <API key>(mfd, dom); else return -ENOMEM; } else { pr_err("no fb memory allocator function defined\n"); return -ENOMEM; } } static int mdss_fb_register(struct msm_fb_data_type *mfd) { int ret = -ENODEV; int bpp; struct mdss_panel_info *panel_info = mfd->panel_info; struct fb_info *fbi = mfd->fbi; struct fb_fix_screeninfo *fix; struct fb_var_screeninfo *var; int *id; /* * fb info initialization */ fix = &fbi->fix; var = &fbi->var; fix->type_aux = 0; /* if type == <API key> */ fix->visual = FB_VISUAL_TRUECOLOR; /* True Color */ fix->ywrapstep = 0; /* No support */ fix->mmio_start = 0; /* No MMIO Address */ fix->mmio_len = 0; /* No MMIO Address */ fix->accel = FB_ACCEL_NONE;/* FB_ACCEL_MSM needes to be added in fb.h */ var->xoffset = 0, /* Offset from virtual to visible */ var->yoffset = 0, /* resolution */ var->grayscale = 0, /* No graylevels */ var->nonstd = 0, /* standard pixel format */ var->activate = FB_ACTIVATE_VBL, /* activate it at vsync */ var->height = -1, /* height of picture in mm */ var->width = -1, /* width of picture in mm */ var->accel_flags = 0, /* acceleration flags */ var->sync = 0, /* see FB_SYNC_* */ var->rotate = 0, /* angle we rotate counter clockwise */ mfd->op_enable = false; switch (mfd->fb_imgType) { case MDP_RGB_565: fix->type = <API key>; fix->xpanstep = 1; fix->ypanstep = 1; var->vmode = <API key>; var->blue.offset = 0; var->green.offset = 5; var->red.offset = 11; var->blue.length = 5; var->green.length = 6; var->red.length = 5; var->blue.msb_right = 0; var->green.msb_right = 0; var->red.msb_right = 0; var->transp.offset = 0; var->transp.length = 0; bpp = 2; break; case MDP_RGB_888: fix->type = <API key>; fix->xpanstep = 1; fix->ypanstep = 1; var->vmode = <API key>; var->blue.offset = 0; var->green.offset = 8; var->red.offset = 16; var->blue.length = 8; var->green.length = 8; var->red.length = 8; var->blue.msb_right = 0; var->green.msb_right = 0; var->red.msb_right = 0; var->transp.offset = 0; var->transp.length = 0; bpp = 3; break; case MDP_ARGB_8888: fix->type = <API key>; fix->xpanstep = 1; fix->ypanstep = 1; var->vmode = <API key>; var->blue.offset = 0; var->green.offset = 8; var->red.offset = 16; var->blue.length = 8; var->green.length = 8; var->red.length = 8; var->blue.msb_right = 0; var->green.msb_right = 0; var->red.msb_right = 0; var->transp.offset = 24; var->transp.length = 8; bpp = 4; break; case MDP_RGBA_8888: fix->type = <API key>; fix->xpanstep = 1; fix->ypanstep = 1; var->vmode = <API key>; var->blue.offset = 8; var->green.offset = 16; var->red.offset = 24; var->blue.length = 8; var->green.length = 8; var->red.length = 8; var->blue.msb_right = 0; var->green.msb_right = 0; var->red.msb_right = 0; var->transp.offset = 0; var->transp.length = 8; bpp = 4; break; case MDP_YCRYCB_H2V1: fix->type = <API key>; fix->xpanstep = 2; fix->ypanstep = 1; var->vmode = <API key>; /* how about R/G/B offset? */ var->blue.offset = 0; var->green.offset = 5; var->red.offset = 11; var->blue.length = 5; var->green.length = 6; var->red.length = 5; var->blue.msb_right = 0; var->green.msb_right = 0; var->red.msb_right = 0; var->transp.offset = 0; var->transp.length = 0; bpp = 2; break; default: pr_err("msm_fb_init: fb %d unkown image type!\n", mfd->index); return ret; } var->xres = panel_info->xres; if (mfd->split_display) var->xres *= 2; fix->type = panel_info->is_3d_panel; if (mfd->mdp.fb_stride) fix->line_length = mfd->mdp.fb_stride(mfd->index, var->xres, bpp); else fix->line_length = var->xres * bpp; var->yres = panel_info->yres; if (panel_info->physical_width) var->width = panel_info->physical_width; if (panel_info->physical_height) var->height = panel_info->physical_height; var->xres_virtual = var->xres; var->yres_virtual = panel_info->yres * mfd->fb_page; var->bits_per_pixel = bpp * 8; /* FrameBuffer color depth */ var->upper_margin = panel_info->lcdc.v_back_porch; var->lower_margin = panel_info->lcdc.v_front_porch; var->vsync_len = panel_info->lcdc.v_pulse_width; var->left_margin = panel_info->lcdc.h_back_porch; var->right_margin = panel_info->lcdc.h_front_porch; var->hsync_len = panel_info->lcdc.h_pulse_width; var->pixclock = panel_info->clk_rate / 1000; /* * Populate smem length here for uspace to get the * Framebuffer size when FBIO_FSCREENINFO ioctl is * called. */ fix->smem_len = PAGE_ALIGN(fix->line_length * var->yres) * mfd->fb_page; /* id field for fb app */ id = (int *)&mfd->panel; snprintf(fix->id, sizeof(fix->id), "mdssfb_%x", (u32) *id); fbi->fbops = &mdss_fb_ops; fbi->flags = FBINFO_FLAG_DEFAULT; fbi->pseudo_palette = <API key>; mfd->ref_cnt = 0; mfd->panel_power_state = <API key>; mfd->dcm_state = DCM_UNINIT; mdss_fb_parse_dt(mfd); if (mdss_fb_alloc_fbmem(mfd)) pr_warn("unable to allocate fb memory in fb register\n"); mfd->op_enable = true; mutex_init(&mfd->update.lock); mutex_init(&mfd->no_update.lock); mutex_init(&mfd->mdp_sync_pt_data.sync_mutex); atomic_set(&mfd->mdp_sync_pt_data.commit_cnt, 0); atomic_set(&mfd->commits_pending, 0); atomic_set(&mfd->ioctl_ref_cnt, 0); atomic_set(&mfd->kickoff_pending, 0); init_timer(&mfd->no_update.timer); mfd->no_update.timer.function = <API key>; mfd->no_update.timer.data = (unsigned long)mfd; mfd->update.ref_count = 0; mfd->no_update.ref_count = 0; mfd->update.init_done = false; init_completion(&mfd->update.comp); init_completion(&mfd->no_update.comp); init_completion(&mfd->power_off_comp); init_completion(&mfd->power_set_comp); init_waitqueue_head(&mfd->commit_wait_q); init_waitqueue_head(&mfd->idle_wait_q); init_waitqueue_head(&mfd->ioctl_q); init_waitqueue_head(&mfd->kickoff_wait_q); ret = fb_alloc_cmap(&fbi->cmap, 256, 0); if (ret) pr_err("fb_alloc_cmap() failed!\n"); if (<API key>(fbi) < 0) { fb_dealloc_cmap(&fbi->cmap); mfd->op_enable = false; return -EPERM; } pr_info("FrameBuffer[%d] %dx%d registered successfully!\n", mfd->index, fbi->var.xres, fbi->var.yres); return 0; } static int mdss_fb_open(struct fb_info *info, int user) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct mdss_fb_proc_info *pinfo = NULL; int result; int pid = current->tgid; struct task_struct *task = current->group_leader; if (mfd->shutdown_pending) { pr_err("Shutdown pending. Aborting operation. Request from pid:%d name=%s\n", pid, task->comm); return -EPERM; } list_for_each_entry(pinfo, &mfd->proc_list, list) { if (pinfo->pid == pid) break; } if ((pinfo == NULL) || (pinfo->pid != pid)) { pinfo = kmalloc(sizeof(*pinfo), GFP_KERNEL); if (!pinfo) { pr_err("unable to alloc process info\n"); return -ENOMEM; } pinfo->pid = pid; pinfo->ref_cnt = 0; list_add(&pinfo->list, &mfd->proc_list); pr_debug("new process entry pid=%d\n", pinfo->pid); } result = pm_runtime_get_sync(info->dev); if (result < 0) { pr_err("pm_runtime: fail to wake up\n"); goto pm_error; } if (!mfd->ref_cnt) { result = mdss_fb_blank_sub(FB_BLANK_UNBLANK, info, mfd->op_enable); if (result) { pr_err("can't turn on fb%d! rc=%d\n", mfd->index, result); goto blank_error; } } pinfo->ref_cnt++; mfd->ref_cnt++; return 0; blank_error: if (pinfo && !pinfo->ref_cnt) { list_del(&pinfo->list); kfree(pinfo); } pm_runtime_put(info->dev); pm_error: return result; } static int mdss_fb_release_all(struct fb_info *info, bool release_all) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct mdss_fb_proc_info *pinfo = NULL, *temp_pinfo = NULL; int ret = 0, ad_ret = 0; int pid = current->tgid; bool unknown_pid = true, release_needed = false; struct task_struct *task = current->group_leader; if (!mfd->ref_cnt) { pr_info("try to close unopened fb %d! from %s\n", mfd->index, task->comm); return -EINVAL; } if (!wait_event_timeout(mfd->ioctl_q, !atomic_read(&mfd->ioctl_ref_cnt) || !release_all, msecs_to_jiffies(1000))) pr_warn("fb%d ioctl could not finish. waited 1 sec.\n", mfd->index); mdss_fb_pan_idle(mfd); pr_debug("release_all = %s\n", release_all ? "true" : "false"); <API key>(pinfo, temp_pinfo, &mfd->proc_list, list) { if (!release_all && (pinfo->pid != pid)) continue; unknown_pid = false; pr_debug("found process %s pid=%d mfd->ref=%d pinfo->ref=%d\n", task->comm, mfd->ref_cnt, pinfo->pid, pinfo->ref_cnt); do { if (mfd->ref_cnt < pinfo->ref_cnt) pr_warn("WARN:mfd->ref=%d < pinfo->ref=%d\n", mfd->ref_cnt, pinfo->ref_cnt); else mfd->ref_cnt pinfo->ref_cnt pm_runtime_put(info->dev); } while (release_all && pinfo->ref_cnt); if (pinfo->ref_cnt == 0) { list_del(&pinfo->list); kfree(pinfo); release_needed = !release_all; } if (!release_all) break; } if (release_needed) { pr_debug("known process %s pid=%d mfd->ref=%d\n", task->comm, pid, mfd->ref_cnt); if (mfd->mdp.release_fnc) { ret = mfd->mdp.release_fnc(mfd, false); if (ret) pr_err("error releasing fb%d pid=%d\n", mfd->index, pid); } } else if (unknown_pid || release_all) { pr_warn("unknown process %s pid=%d mfd->ref=%d\n", task->comm, pid, mfd->ref_cnt); if (mfd->ref_cnt) mfd->ref_cnt if (mfd->mdp.release_fnc) { ret = mfd->mdp.release_fnc(mfd, true); if (ret) pr_err("error fb%d release process %s pid=%d\n", mfd->index, task->comm, pid); } } if (!mfd->ref_cnt) { if (mfd->mdp.release_fnc) { ret = mfd->mdp.release_fnc(mfd, true); if (ret) pr_err("error fb%d release process %s pid=%d\n", mfd->index, task->comm, pid); } if (mfd->mdp.ad_shutdown_cleanup) { ad_ret = (*mfd->mdp.ad_shutdown_cleanup)(mfd); if (ad_ret) pr_err("AD shutdown cleanup failed ret = %d\n", ad_ret); } ret = mdss_fb_blank_sub(FB_BLANK_POWERDOWN, info, mfd->op_enable); if (ret) { pr_err("can't turn off fb%d! rc=%d process %s pid=%d\n", mfd->index, ret, task->comm, pid); return ret; } if (mfd->fb_ion_handle) <API key>(mfd); atomic_set(&mfd->ioctl_ref_cnt, 0); } return ret; } static int mdss_fb_release(struct fb_info *info, int user) { return mdss_fb_release_all(info, false); } static void <API key>(struct msm_fb_data_type *mfd) { int ret; if (mfd->is_power_setting) { ret = <API key>( &mfd->power_set_comp, msecs_to_jiffies(<API key>)); if (ret < 0) ret = -ERESTARTSYS; else if (!ret) pr_err("%s wait for power_set_comp timeout %d %d", __func__, ret, mfd->is_power_setting); if (ret <= 0) { mfd->is_power_setting = false; complete_all(&mfd->power_set_comp); } } } void <API key>(struct msm_sync_pt_data *sync_pt_data) { struct sync_fence *fences[MDP_MAX_FENCE_FD]; int fence_cnt; int i, ret = 0; pr_debug("%s: wait for fences\n", sync_pt_data->fence_name); mutex_lock(&sync_pt_data->sync_mutex); /* * Assuming that acq_fen_cnt is sanitized in bufsync ioctl * to check for sync_pt_data->acq_fen_cnt) <= MDP_MAX_FENCE_FD */ fence_cnt = sync_pt_data->acq_fen_cnt; sync_pt_data->acq_fen_cnt = 0; if (fence_cnt) memcpy(fences, sync_pt_data->acq_fen, fence_cnt * sizeof(struct sync_fence *)); mutex_unlock(&sync_pt_data->sync_mutex); /* buf sync */ for (i = 0; i < fence_cnt && !ret; i++) { ret = sync_fence_wait(fences[i], <API key>); if (ret == -ETIME) { pr_warn("%s: sync_fence_wait timed out! ", sync_pt_data->fence_name); pr_cont("Waiting %ld more seconds\n", <API key>/MSEC_PER_SEC); ret = sync_fence_wait(fences[i], <API key>); } sync_fence_put(fences[i]); } if (ret < 0) { pr_err("%s: sync_fence_wait failed! ret = %x\n", sync_pt_data->fence_name, ret); for (; i < fence_cnt; i++) sync_fence_put(fences[i]); } } /** * <API key>() - signal a single release fence * @sync_pt_data: Sync point data structure for the timeline which * should be signaled. * * This is called after a frame has been pushed to display. This signals the * timeline to release the fences associated with this frame. */ void <API key>(struct msm_sync_pt_data *sync_pt_data) { mutex_lock(&sync_pt_data->sync_mutex); if (atomic_add_unless(&sync_pt_data->commit_cnt, -1, 0) && sync_pt_data->timeline) { <API key>(sync_pt_data->timeline, 1); sync_pt_data->timeline_value++; pr_debug("%s: buffer signaled! timeline val=%d remaining=%d\n", sync_pt_data->fence_name, sync_pt_data->timeline_value, atomic_read(&sync_pt_data->commit_cnt)); } else { pr_debug("%s timeline signaled without commits val=%d\n", sync_pt_data->fence_name, sync_pt_data->timeline_value); } mutex_unlock(&sync_pt_data->sync_mutex); } /** * <API key>() - signal all pending release fences * @mfd: Framebuffer data structure for display * * Release all currently pending release fences, including those that are in * the process to be commited. * * Note: this should only be called during close or suspend sequence. */ static void <API key>(struct msm_fb_data_type *mfd) { struct msm_sync_pt_data *sync_pt_data = &mfd->mdp_sync_pt_data; int val; mutex_lock(&sync_pt_data->sync_mutex); if (sync_pt_data->timeline) { val = sync_pt_data->threshold + atomic_read(&sync_pt_data->commit_cnt); <API key>(sync_pt_data->timeline, val); sync_pt_data->timeline_value += val; atomic_set(&sync_pt_data->commit_cnt, 0); } mutex_unlock(&sync_pt_data->sync_mutex); } /** * <API key>() - process async display events * @p: Notifier block registered for async events. * @event: Event enum to identify the event. * @data: Optional argument provided with the event. * * See enum mdp_notify_event for events handled. */ static int <API key>(struct notifier_block *p, unsigned long event, void *data) { struct msm_sync_pt_data *sync_pt_data; struct msm_fb_data_type *mfd; sync_pt_data = container_of(p, struct msm_sync_pt_data, notifier); mfd = container_of(sync_pt_data, struct msm_fb_data_type, mdp_sync_pt_data); switch (event) { case <API key>: if (mfd->idle_time) { <API key>(&mfd->idle_notify_work); <API key>(&mfd->idle_notify_work, msecs_to_jiffies(mfd->idle_time)); } break; case <API key>: if (sync_pt_data->async_wait_fences) <API key>(sync_pt_data); break; case <API key>: pr_debug("%s: frame flushed\n", sync_pt_data->fence_name); sync_pt_data->flushed = true; break; case <API key>: pr_err("%s: frame timeout\n", sync_pt_data->fence_name); <API key>(sync_pt_data); break; case <API key>: pr_debug("%s: frame done\n", sync_pt_data->fence_name); <API key>(sync_pt_data); break; } return NOTIFY_OK; } /** * mdss_fb_pan_idle() - wait for panel programming to be idle * @mfd: Framebuffer data structure for display * * Wait for any pending programming to be done if in the process of programming * hardware configuration. After this function returns it is safe to perform * software updates for next frame. */ static int mdss_fb_pan_idle(struct msm_fb_data_type *mfd) { int ret = 0; ret = wait_event_timeout(mfd->idle_wait_q, (!atomic_read(&mfd->commits_pending) || mfd->shutdown_pending), msecs_to_jiffies(<API key>)); if (!ret) { pr_err("wait for idle timeout %d pending=%d\n", ret, atomic_read(&mfd->commits_pending)); <API key>(&mfd->mdp_sync_pt_data); } else if (mfd->shutdown_pending) { pr_debug("Shutdown signalled\n"); return -EPERM; } return 0; } static int <API key>(struct msm_fb_data_type *mfd) { int ret = 0; ret = wait_event_timeout(mfd->kickoff_wait_q, (!atomic_read(&mfd->kickoff_pending) || mfd->shutdown_pending), msecs_to_jiffies(<API key> / 2)); if (!ret) { pr_err("wait for kickoff timeout %d pending=%d\n", ret, atomic_read(&mfd->kickoff_pending)); } else if (mfd->shutdown_pending) { pr_debug("Shutdown signalled\n"); return -EPERM; } return 0; } static int <API key>(struct fb_info *info, struct mdp_display_commit *disp_commit) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct fb_var_screeninfo *var = &disp_commit->var; u32 wait_for_finish = disp_commit->wait_for_finish; int ret = 0; if (!mfd || (!mfd->op_enable)) return -EPERM; if ((<API key>(mfd)) && !((mfd->dcm_state == DCM_ENTER) && (mfd->panel.type == MIPI_CMD_PANEL))) return -EPERM; if (var->xoffset > (info->var.xres_virtual - info->var.xres)) return -EINVAL; if (var->yoffset > (info->var.yres_virtual - info->var.yres)) return -EINVAL; ret = mdss_fb_pan_idle(mfd); if (ret) { pr_err("Shutdown pending. Aborting operation\n"); return ret; } mutex_lock(&mfd->mdp_sync_pt_data.sync_mutex); if (info->fix.xpanstep) info->var.xoffset = (var->xoffset / info->fix.xpanstep) * info->fix.xpanstep; if (info->fix.ypanstep) info->var.yoffset = (var->yoffset / info->fix.ypanstep) * info->fix.ypanstep; mfd->msm_fb_backup.info = *info; mfd->msm_fb_backup.disp_commit = *disp_commit; atomic_inc(&mfd->mdp_sync_pt_data.commit_cnt); atomic_inc(&mfd->commits_pending); atomic_inc(&mfd->kickoff_pending); wake_up_all(&mfd->commit_wait_q); mutex_unlock(&mfd->mdp_sync_pt_data.sync_mutex); if (wait_for_finish) mdss_fb_pan_idle(mfd); return ret; } static int mdss_fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { struct mdp_display_commit disp_commit; memset(&disp_commit, 0, sizeof(disp_commit)); disp_commit.wait_for_finish = true; memcpy(&disp_commit.var, var, sizeof(struct fb_var_screeninfo)); return <API key>(info, &disp_commit); } static int <API key>(struct fb_var_screeninfo *var, struct fb_info *info) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; if (!mfd->op_enable) return -EPERM; if ((<API key>(mfd)) && !((mfd->dcm_state == DCM_ENTER) && (mfd->panel.type == MIPI_CMD_PANEL))) return -EPERM; if (var->xoffset > (info->var.xres_virtual - info->var.xres)) return -EINVAL; if (var->yoffset > (info->var.yres_virtual - info->var.yres)) return -EINVAL; if (info->fix.xpanstep) info->var.xoffset = (var->xoffset / info->fix.xpanstep) * info->fix.xpanstep; if (info->fix.ypanstep) info->var.yoffset = (var->yoffset / info->fix.ypanstep) * info->fix.ypanstep; if (mfd->mdp.dma_fnc) mfd->mdp.dma_fnc(mfd); else pr_warn("dma function not set for panel type=%d\n", mfd->panel.type); return 0; } static void <API key>(struct fb_var_screeninfo *var, struct mdss_panel_info *pinfo) { pinfo->xres = var->xres; pinfo->yres = var->yres; pinfo->lcdc.v_front_porch = var->lower_margin; pinfo->lcdc.v_back_porch = var->upper_margin; pinfo->lcdc.v_pulse_width = var->vsync_len; pinfo->lcdc.h_front_porch = var->right_margin; pinfo->lcdc.h_back_porch = var->left_margin; pinfo->lcdc.h_pulse_width = var->hsync_len; pinfo->clk_rate = var->pixclock; } /** * <API key>() - process a frame to display * @mfd: Framebuffer data structure for display * * Processes all layers and buffers programmed and ensures all pending release * fences are signaled once the buffer is transfered to display. */ static int <API key>(struct msm_fb_data_type *mfd) { struct msm_sync_pt_data *sync_pt_data = &mfd->mdp_sync_pt_data; struct msm_fb_backup_type *fb_backup = &mfd->msm_fb_backup; int ret = -ENOSYS; if (!sync_pt_data->async_wait_fences) <API key>(sync_pt_data); sync_pt_data->flushed = false; if (fb_backup->disp_commit.flags & <API key>) { if (mfd->mdp.kickoff_fnc) ret = mfd->mdp.kickoff_fnc(mfd, &fb_backup->disp_commit); else pr_warn("no kickoff function setup for fb%d\n", mfd->index); } else { ret = <API key>(&fb_backup->disp_commit.var, &fb_backup->info); if (ret) pr_err("pan display failed %x on fb%d\n", ret, mfd->index); atomic_set(&mfd->kickoff_pending, 0); wake_up_all(&mfd->kickoff_wait_q); } if (!ret) <API key>(mfd); if (IS_ERR_VALUE(ret) || !sync_pt_data->flushed) <API key>(sync_pt_data); return ret; } static int <API key>(void *data) { struct msm_fb_data_type *mfd = data; int ret; struct sched_param param; param.sched_priority = 16; ret = sched_setscheduler(current, SCHED_FIFO, &param); if (ret) pr_warn("set priority failed for fb%d display thread\n", mfd->index); while (1) { <API key>(mfd->commit_wait_q, (atomic_read(&mfd->commits_pending) || kthread_should_stop())); if (kthread_should_stop()) break; ret = <API key>(mfd); atomic_dec(&mfd->commits_pending); wake_up_all(&mfd->idle_wait_q); } atomic_set(&mfd->commits_pending, 0); atomic_set(&mfd->kickoff_pending, 0); wake_up_all(&mfd->idle_wait_q); return ret; } static int mdss_fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; if (var->rotate != FB_ROTATE_UR) return -EINVAL; if (var->grayscale != info->var.grayscale) return -EINVAL; switch (var->bits_per_pixel) { case 16: if ((var->green.offset != 5) || !((var->blue.offset == 11) || (var->blue.offset == 0)) || !((var->red.offset == 11) || (var->red.offset == 0)) || (var->blue.length != 5) || (var->green.length != 6) || (var->red.length != 5) || (var->blue.msb_right != 0) || (var->green.msb_right != 0) || (var->red.msb_right != 0) || (var->transp.offset != 0) || (var->transp.length != 0)) return -EINVAL; break; case 24: if ((var->blue.offset != 0) || (var->green.offset != 8) || (var->red.offset != 16) || (var->blue.length != 8) || (var->green.length != 8) || (var->red.length != 8) || (var->blue.msb_right != 0) || (var->green.msb_right != 0) || (var->red.msb_right != 0) || !(((var->transp.offset == 0) && (var->transp.length == 0)) || ((var->transp.offset == 24) && (var->transp.length == 8)))) return -EINVAL; break; case 32: /* Figure out if the user meant RGBA or ARGB and verify the position of the RGB components */ if (var->transp.offset == 24) { if ((var->blue.offset != 0) || (var->green.offset != 8) || (var->red.offset != 16)) return -EINVAL; } else if (var->transp.offset == 0) { if ((var->blue.offset != 8) || (var->green.offset != 16) || (var->red.offset != 24)) return -EINVAL; } else return -EINVAL; /* Check the common values for both RGBA and ARGB */ if ((var->blue.length != 8) || (var->green.length != 8) || (var->red.length != 8) || (var->transp.length != 8) || (var->blue.msb_right != 0) || (var->green.msb_right != 0) || (var->red.msb_right != 0)) return -EINVAL; break; default: return -EINVAL; } if ((var->xres_virtual <= 0) || (var->yres_virtual <= 0)) return -EINVAL; if (info->fix.smem_start) { u32 len = var->xres_virtual * var->yres_virtual * (var->bits_per_pixel / 8); if (len > info->fix.smem_len) return -EINVAL; } if ((var->xres == 0) || (var->yres == 0)) return -EINVAL; if (var->xoffset > (var->xres_virtual - var->xres)) return -EINVAL; if (var->yoffset > (var->yres_virtual - var->yres)) return -EINVAL; if (mfd->panel_info) { struct mdss_panel_info panel_info; int rc; memcpy(&panel_info, mfd->panel_info, sizeof(panel_info)); <API key>(var, &panel_info); rc = <API key>(mfd, <API key>, &panel_info); if (IS_ERR_VALUE(rc)) return rc; mfd->panel_reconfig = rc; } return 0; } static int mdss_fb_set_par(struct fb_info *info) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct fb_var_screeninfo *var = &info->var; int old_imgType; int ret = 0; ret = mdss_fb_pan_idle(mfd); if (ret) { pr_err("Shutdown pending. Aborting operation\n"); return ret; } old_imgType = mfd->fb_imgType; switch (var->bits_per_pixel) { case 16: if (var->red.offset == 0) mfd->fb_imgType = MDP_BGR_565; else mfd->fb_imgType = MDP_RGB_565; break; case 24: if ((var->transp.offset == 0) && (var->transp.length == 0)) mfd->fb_imgType = MDP_RGB_888; else if ((var->transp.offset == 24) && (var->transp.length == 8)) { mfd->fb_imgType = MDP_ARGB_8888; info->var.bits_per_pixel = 32; } break; case 32: if (var->transp.offset == 24) mfd->fb_imgType = MDP_ARGB_8888; else mfd->fb_imgType = MDP_RGBA_8888; break; default: return -EINVAL; } if (mfd->mdp.fb_stride) mfd->fbi->fix.line_length = mfd->mdp.fb_stride(mfd->index, var->xres, var->bits_per_pixel / 8); else mfd->fbi->fix.line_length = var->xres * var->bits_per_pixel / 8; mfd->fbi->fix.smem_len = mfd->fbi->fix.line_length * mfd->fbi->var.yres_virtual; if (mfd->panel_reconfig || (mfd->fb_imgType != old_imgType)) { mdss_fb_blank_sub(FB_BLANK_POWERDOWN, info, mfd->op_enable); <API key>(var, mfd->panel_info); mdss_fb_blank_sub(FB_BLANK_UNBLANK, info, mfd->op_enable); mfd->panel_reconfig = false; } return ret; } int mdss_fb_dcm(struct msm_fb_data_type *mfd, int req_state) { int ret = 0; if (req_state == mfd->dcm_state) { pr_warn("Already in correct DCM/DTM state"); return ret; } switch (req_state) { case DCM_UNBLANK: if (mfd->dcm_state == DCM_UNINIT && <API key>(mfd) && mfd->mdp.on_fnc) { ret = mfd->mdp.on_fnc(mfd); if (ret == 0) { mfd->panel_power_state = MDSS_PANEL_POWER_ON; mfd->dcm_state = DCM_UNBLANK; } } break; case DCM_ENTER: if (mfd->dcm_state == DCM_UNBLANK) { /* * Keep unblank path available for only * DCM operation */ mfd->panel_power_state = <API key>; mfd->dcm_state = DCM_ENTER; } break; case DCM_EXIT: if (mfd->dcm_state == DCM_ENTER) { /* Release the unblank path for exit */ mfd->panel_power_state = MDSS_PANEL_POWER_ON; mfd->dcm_state = DCM_EXIT; } break; case DCM_BLANK: if ((mfd->dcm_state == DCM_EXIT || mfd->dcm_state == DCM_UNBLANK) && mdss_fb_is_power_on(mfd) && mfd->mdp.off_fnc) { ret = mfd->mdp.off_fnc(mfd); if (ret == 0) { mfd->panel_power_state = <API key>; mfd->dcm_state = DCM_UNINIT; } } break; case DTM_ENTER: if (mfd->dcm_state == DCM_UNINIT) mfd->dcm_state = DTM_ENTER; break; case DTM_EXIT: if (mfd->dcm_state == DTM_ENTER) mfd->dcm_state = DCM_UNINIT; break; } return ret; } static int mdss_fb_cursor(struct fb_info *info, void __user *p) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct fb_cursor cursor; int ret; if (!mfd->mdp.cursor_update) return -ENODEV; ret = copy_from_user(&cursor, p, sizeof(cursor)); if (ret) return ret; return mfd->mdp.cursor_update(mfd, &cursor); } static int mdss_fb_set_lut(struct fb_info *info, void __user *p) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct fb_cmap cmap; int ret; if (!mfd->mdp.lut_update) return -ENODEV; ret = copy_from_user(&cmap, p, sizeof(cmap)); if (ret) return ret; mfd->mdp.lut_update(mfd, &cmap); return 0; } /** * <API key>() - get fence from timeline * @timeline: Timeline to create the fence on * @fence_name: Name of the fence that will be created for debugging * @val: Timeline value at which the fence will be signaled * * Function returns a fence on the timeline given with the name provided. * The fence created will be signaled when the timeline is advanced. */ struct sync_fence *<API key>(struct sw_sync_timeline *timeline, const char *fence_name, int val) { struct sync_pt *sync_pt; struct sync_fence *fence; pr_debug("%s: buf sync fence timeline=%d\n", fence_name, val); sync_pt = sw_sync_pt_create(timeline, val); if (sync_pt == NULL) { pr_err("%s: cannot create sync point\n", fence_name); return NULL; } /* create fence */ fence = sync_fence_create(fence_name, sync_pt); if (fence == NULL) { sync_pt_free(sync_pt); pr_err("%s: cannot create fence\n", fence_name); return NULL; } return fence; } static int <API key>(struct msm_sync_pt_data *sync_pt_data, struct mdp_buf_sync *buf_sync) { int i, ret = 0; int acq_fen_fd[MDP_MAX_FENCE_FD]; struct sync_fence *fence, *rel_fence, *retire_fence; int rel_fen_fd; int retire_fen_fd; int val; if ((buf_sync->acq_fen_fd_cnt > MDP_MAX_FENCE_FD) || (sync_pt_data->timeline == NULL)) return -EINVAL; if (buf_sync->acq_fen_fd_cnt) ret = copy_from_user(acq_fen_fd, buf_sync->acq_fen_fd, buf_sync->acq_fen_fd_cnt * sizeof(int)); if (ret) { pr_err("%s: copy_from_user failed", sync_pt_data->fence_name); return ret; } if (sync_pt_data->acq_fen_cnt) { pr_warn("%s: currently %d fences active. waiting...\n", sync_pt_data->fence_name, sync_pt_data->acq_fen_cnt); <API key>(sync_pt_data); } mutex_lock(&sync_pt_data->sync_mutex); for (i = 0; i < buf_sync->acq_fen_fd_cnt; i++) { fence = sync_fence_fdget(acq_fen_fd[i]); if (fence == NULL) { pr_err("%s: null fence! i=%d fd=%d\n", sync_pt_data->fence_name, i, acq_fen_fd[i]); ret = -EINVAL; break; } sync_pt_data->acq_fen[i] = fence; } sync_pt_data->acq_fen_cnt = i; if (ret) goto buf_sync_err_1; val = sync_pt_data->timeline_value + sync_pt_data->threshold + atomic_read(&sync_pt_data->commit_cnt); /* Set release fence */ rel_fence = <API key>(sync_pt_data->timeline, sync_pt_data->fence_name, val); if (IS_ERR_OR_NULL(rel_fence)) { pr_err("%s: unable to retrieve release fence\n", sync_pt_data->fence_name); ret = rel_fence ? PTR_ERR(rel_fence) : -ENOMEM; goto buf_sync_err_1; } /* create fd */ rel_fen_fd = get_unused_fd_flags(0); if (rel_fen_fd < 0) { pr_err("%s: get_unused_fd_flags failed\n", sync_pt_data->fence_name); ret = -EIO; goto buf_sync_err_2; } sync_fence_install(rel_fence, rel_fen_fd); ret = copy_to_user(buf_sync->rel_fen_fd, &rel_fen_fd, sizeof(int)); if (ret) { pr_err("%s: copy_to_user failed\n", sync_pt_data->fence_name); goto buf_sync_err_3; } if (!(buf_sync->flags & <API key>)) goto skip_retire_fence; if (sync_pt_data->get_retire_fence) retire_fence = sync_pt_data->get_retire_fence(sync_pt_data); else retire_fence = NULL; if (IS_ERR_OR_NULL(retire_fence)) { val += sync_pt_data->retire_threshold; retire_fence = <API key>( sync_pt_data->timeline, "mdp-retire", val); } if (IS_ERR_OR_NULL(retire_fence)) { pr_err("%s: unable to retrieve retire fence\n", sync_pt_data->fence_name); ret = retire_fence ? PTR_ERR(rel_fence) : -ENOMEM; goto buf_sync_err_3; } retire_fen_fd = get_unused_fd_flags(0); if (retire_fen_fd < 0) { pr_err("%s: get_unused_fd_flags failed for retire fence\n", sync_pt_data->fence_name); ret = -EIO; sync_fence_put(retire_fence); goto buf_sync_err_3; } sync_fence_install(retire_fence, retire_fen_fd); ret = copy_to_user(buf_sync->retire_fen_fd, &retire_fen_fd, sizeof(int)); if (ret) { pr_err("%s: copy_to_user failed for retire fence\n", sync_pt_data->fence_name); put_unused_fd(retire_fen_fd); sync_fence_put(retire_fence); goto buf_sync_err_3; } skip_retire_fence: mutex_unlock(&sync_pt_data->sync_mutex); if (buf_sync->flags & <API key>) <API key>(sync_pt_data); return ret; buf_sync_err_3: put_unused_fd(rel_fen_fd); buf_sync_err_2: sync_fence_put(rel_fence); buf_sync_err_1: for (i = 0; i < sync_pt_data->acq_fen_cnt; i++) sync_fence_put(sync_pt_data->acq_fen[i]); sync_pt_data->acq_fen_cnt = 0; mutex_unlock(&sync_pt_data->sync_mutex); return ret; } static int <API key>(struct fb_info *info, unsigned long *argp) { int ret; struct mdp_display_commit disp_commit; ret = copy_from_user(&disp_commit, argp, sizeof(disp_commit)); if (ret) { pr_err("%s:copy_from_user failed", __func__); return ret; } ret = <API key>(info, &disp_commit); return ret; } static int __ioctl_wait_idle(struct msm_fb_data_type *mfd, u32 cmd) { int ret = 0; if (mfd->wait_for_kickoff && ((cmd == <API key>) || (cmd == MSMFB_BUFFER_SYNC) || (cmd == MSMFB_OVERLAY_SET))) { ret = <API key>(mfd); } else if ((cmd != MSMFB_VSYNC_CTRL) && (cmd != <API key>) && (cmd != MSMFB_ASYNC_BLIT) && (cmd != MSMFB_BLIT) && (cmd != MSMFB_NOTIFY_UPDATE) && (cmd != <API key>)) { ret = mdss_fb_pan_idle(mfd); } if (ret) pr_debug("Shutdown pending. Aborting operation %x\n", cmd); return ret; } static int mdss_fb_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg) { struct msm_fb_data_type *mfd; void __user *argp = (void __user *)arg; struct mdp_page_protection fb_page_protection; int ret = -ENOSYS; struct mdp_buf_sync buf_sync; struct msm_sync_pt_data *sync_pt_data = NULL; unsigned int dsi_mode = 0; if (!info || !info->par) return -EINVAL; mfd = (struct msm_fb_data_type *)info->par; if (!mfd) return -EINVAL; if (mfd->shutdown_pending) return -EPERM; atomic_inc(&mfd->ioctl_ref_cnt); <API key>(mfd); ret = __ioctl_wait_idle(mfd, cmd); if (ret) goto exit; switch (cmd) { case MSMFB_CURSOR: ret = mdss_fb_cursor(info, argp); break; case MSMFB_SET_LUT: ret = mdss_fb_set_lut(info, argp); break; case <API key>: fb_page_protection.page_protection = mfd-><API key>; ret = copy_to_user(argp, &fb_page_protection, sizeof(fb_page_protection)); if (ret) goto exit; break; case MSMFB_BUFFER_SYNC: ret = copy_from_user(&buf_sync, argp, sizeof(buf_sync)); if (ret) goto exit; if ((!mfd->op_enable) || (<API key>(mfd))) { ret = -EPERM; goto exit; } if (mfd->mdp.get_sync_fnc) sync_pt_data = mfd->mdp.get_sync_fnc(mfd, &buf_sync); if (!sync_pt_data) sync_pt_data = &mfd->mdp_sync_pt_data; ret = <API key>(sync_pt_data, &buf_sync); if (!ret) ret = copy_to_user(argp, &buf_sync, sizeof(buf_sync)); break; case MSMFB_NOTIFY_UPDATE: ret = <API key>(mfd, argp); break; case <API key>: ret = <API key>(info, argp); break; case MSMFB_LPM_ENABLE: ret = copy_from_user(&dsi_mode, argp, sizeof(dsi_mode)); if (ret) { pr_err("%s: MSMFB_LPM_ENABLE ioctl failed\n", __func__); goto exit; } ret = mdss_fb_lpm_enable(mfd, dsi_mode); break; default: if (mfd->mdp.ioctl_handler) ret = mfd->mdp.ioctl_handler(mfd, cmd, argp); break; } if (ret == -ENOSYS) pr_err("unsupported ioctl (%x)\n", cmd); exit: if (!atomic_dec_return(&mfd->ioctl_ref_cnt)) wake_up_all(&mfd->ioctl_q); return ret; } struct fb_info *<API key>(void) { int c = 0; for (c = 0; c < fbi_list_index; ++c) { struct msm_fb_data_type *mfd; mfd = (struct msm_fb_data_type *)fbi_list[c]->par; if (mfd->panel.type == WRITEBACK_PANEL) return fbi_list[c]; } return NULL; } EXPORT_SYMBOL(<API key>); static int <API key>(struct platform_device *pdev, struct mdss_panel_data *pdata) { struct mdss_panel_data *fb_pdata; fb_pdata = dev_get_platdata(&pdev->dev); if (!fb_pdata) { pr_err("framebuffer device %s contains invalid panel data\n", dev_name(&pdev->dev)); return -EINVAL; } if (fb_pdata->next) { pr_err("split panel already setup for framebuffer device %s\n", dev_name(&pdev->dev)); return -EEXIST; } fb_pdata->next = pdata; return 0; } int mdss_register_panel(struct platform_device *pdev, struct mdss_panel_data *pdata) { struct platform_device *fb_pdev, *mdss_pdev; struct device_node *node; int rc = 0; bool master_panel = true; if (!pdev || !pdev->dev.of_node) { pr_err("Invalid device node\n"); return -ENODEV; } if (!mdp_instance) { pr_err("mdss mdp resource not initialized yet\n"); return -EPROBE_DEFER; } node = of_parse_phandle(pdev->dev.of_node, "qcom,mdss-fb-map", 0); if (!node) { pr_err("Unable to find fb node for device: %s\n", pdev->name); return -ENODEV; } mdss_pdev = <API key>(node->parent); if (!mdss_pdev) { pr_err("Unable to find mdss for node: %s\n", node->full_name); rc = -ENODEV; goto mdss_notfound; } fb_pdev = <API key>(node); if (fb_pdev) { rc = <API key>(fb_pdev, pdata); if (rc == 0) master_panel = false; } else { pr_info("adding framebuffer device %s\n", dev_name(&pdev->dev)); fb_pdev = <API key>(node, NULL, &mdss_pdev->dev); if (fb_pdev) fb_pdev->dev.platform_data = pdata; } if (master_panel && mdp_instance->panel_register_done) mdp_instance->panel_register_done(pdata); mdss_notfound: of_node_put(node); return rc; } EXPORT_SYMBOL(mdss_register_panel); int <API key>(struct msm_mdp_interface *mdp) { if (mdp_instance) { pr_err("multiple MDP instance registration"); return -EINVAL; } mdp_instance = mdp; return 0; } EXPORT_SYMBOL(<API key>); int <API key>(unsigned long *start, unsigned long *len, int fb_num) { struct fb_info *info; struct msm_fb_data_type *mfd; if (fb_num >= MAX_FBI_LIST) return -EINVAL; info = fbi_list[fb_num]; if (!info) return -ENOENT; mfd = (struct msm_fb_data_type *)info->par; if (!mfd) return -ENODEV; if (mfd->iova) *start = mfd->iova; else *start = info->fix.smem_start; *len = info->fix.smem_len; return 0; } EXPORT_SYMBOL(<API key>); int __init mdss_fb_init(void) { int rc = -ENODEV; if (<API key>(&mdss_fb_driver)) return rc; return 0; } module_init(mdss_fb_init); int <API key>(struct device *dev, void *data) { struct msm_fb_data_type *mfd; int rc; u32 event; if (!data) { pr_err("Device state not defined\n"); return -EINVAL; } mfd = dev_get_drvdata(dev); if (!mfd) return 0; event = *((bool *) data) ? MDSS_EVENT_RESUME : MDSS_EVENT_SUSPEND; rc = <API key>(mfd, event, NULL); if (rc) pr_warn("unable to %s fb%d (%d)\n", event == MDSS_EVENT_RESUME ? "resume" : "suspend", mfd->index, rc); return rc; }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Thu Apr 09 10:31:52 MDT 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.lucene.analysis.payloads.PayloadHelper (Lucene 5.1.0 API)</title> <meta name="date" content="2015-04-09"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.lucene.analysis.payloads.PayloadHelper (Lucene 5.1.0 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/lucene/analysis/payloads/PayloadHelper.html" title="class in org.apache.lucene.analysis.payloads">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/lucene/analysis/payloads/class-use/PayloadHelper.html" target="_top">Frames</a></li> <li><a href="PayloadHelper.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.apache.lucene.analysis.payloads.PayloadHelper" class="title">Uses of Class<br>org.apache.lucene.analysis.payloads.PayloadHelper</h2> </div> <div class="classUseContainer">No usage of org.apache.lucene.analysis.payloads.PayloadHelper</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/lucene/analysis/payloads/PayloadHelper.html" title="class in org.apache.lucene.analysis.payloads">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/lucene/analysis/payloads/class-use/PayloadHelper.html" target="_top">Frames</a></li> <li><a href="PayloadHelper.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
<?php // section testimonials global $allowedposttags,$<API key>; $section_hide = absint(alchem_option('section_7_hide',0)); $content_model = absint(alchem_option('section_7_model',0)); $section_id = esc_attr(sanitize_title(alchem_option('section_7_id'))); $section_color = esc_attr(alchem_option('section_7_color')); $section_title = wp_kses(alchem_option('section_7_title'), $allowedposttags); $sub_title = wp_kses(alchem_option('section_7_sub_title'), $allowedposttags); $section_content = wp_kses(alchem_option('section_7_content'), $allowedposttags); $columns = absint(alchem_option('section_7_columns',3)); $col = $columns>0?12/$columns:4; $section_content = str_replace('\\\'','\'',$section_content); $section_content = str_replace('\\"','"',$section_content); ?> <?php if( $section_hide != '1' ):?> <section class="section magee-section parallax-scrolling <API key> alchem-home-style-1" id="<?php echo $section_id;?>"> <div class="section-content" style="color:<?php echo $section_color;?>;"> <div class="container"> <?php if( $content_model == 0 ):?> <?php if( $section_title != '' ):?> <h2 class="section-title"><?php echo $section_title;?></h2> <div style="text-align:center;"><?php echo do_shortcode($sub_title);?></div> <div style="height: 80px;"></div> <?php endif;?> <div class="<?php echo $<API key>;?> " <API key>="0.9" data-animationtype="fadeIn" data-imageanimation="no" id=""> <div class="magee-carousel multi-carousel <API key>" id=""> <div class="<API key>"> <div id="<API key>" class="owl-carousel owl-theme"> <?php $testimonial = ''; $testimonials = ''; $animationtype = array('fadeInLeft','fadeInDown','fadeInRight','fadeInLeft','fadeInUp','fadeInRight'); for( $j=0; $j<6; $j++ ){ $avatar = esc_url(alchem_option('section_7_avatar_'.$j)); $name = esc_attr(alchem_option('section_7_name_'.$j)); $byline = esc_attr(alchem_option('section_7_byline_'.$j)); $description = wp_kses(alchem_option('section_7_desc_'.$j), $allowedposttags); if( $description != '' ): $image = ''; if( $avatar != '' ) $image = '<img src="'.$avatar.'" style="width:150px; display:inline-block;" class="img-circle">'; $testimonial .= '<div class="item"> <div class="row"> <div class="col-md-10"> <div style="height: 50px;"></div> <div style="font-family: \'Dancing Script\';font-size:18px;text-align:center;">'.do_shortcode($description).'</div> </div> <div class="col-md-2"> <div style="height: 20px;"></div> <p style="text-align:center;">'.$image.'</p> <div style="font-family: \'Playfair Display\';font-size: 18px; font-weight: bold; text-align: center;">'.$name.'</div> <div style="text-align: center;">'.$byline.'</div> </div> </div> </div>'; endif; } echo $testimonial; ?> </div> </div> <!-- Controls --> <div class="multi-carousel-nav style2 nav-bg nav-rounded"> <a href="javascript:;" class="carousel-prev" role="button" data-slide="prev"> <span class="<API key>"></span> </a> <a class="carousel-next" href="javascript:;" role="button" data-slide="next"> <span class="<API key>"></span> </a> </div> </div> </div> <?php else:?> <?php echo do_shortcode($section_content);?> <?php endif;?> </div> </div> </section> <?php endif;?>
#include "nlm_vits_wrapper.h" #include <asm/netlogic/debug.h> #define __VTSS_LIBRARY__ #define VTSS_TRACE_LAYER 1 #include "vitesse_io.h" #include "meigsii_reg.h" #define <API key> (0x8000*sizeof(ulong)) #ifdef VITGENIO #include <linux/vitgenio.h> #include <fcntl.h> /* open() */ #include <sys/ioctl.h> /* ioctl() */ #include <sys/mman.h> /* mmap() */ #endif #ifdef CUSTOMERIO #endif #define VTSS_BLK_SYSTEM M2_BLK_SYSTEM #define VTSS_SUBBLK_CTRL M2_SUBBLK_CTRL #define VTSS_REG_SW_RESET M2_SW_RESET #define <API key> M2_SI_TRANSFER_SEL #define VTSS_REG_LOCAL_DATA M2_LOCAL_DATA #define <API key> M2_LOCAL_STATUS #define VTSS_T_RESET 2000000L #if 0 /* Reset and configure the chip. */ static void vtss_io_reset_chip( void ) { /* Reset the chip */ vtss_io_write(VTSS_BLK_SYSTEM,VTSS_SUBBLK_CTRL,VTSS_REG_SW_RESET,0x80000001); VTSS_NSLEEP(VTSS_T_RESET); /* Set the chip hardware access configuration (pin polarity etc.). */ { const ulong <API key> = 0x99999999; vtss_io_writemasked(VTSS_BLK_SYSTEM,VTSS_SUBBLK_CTRL, <API key>, (0/*<API key>*/)?0: <API key>,<API key>); } } #endif /* Note: This must be called before any access to the target chip. * vtss_reset_io_layer() calls this directly. */ void vtss_io_reset( void ) { #ifdef VITGENIO /* Setup the hardware access (open device driver and setup MMU). */ if (vtss_io_state->chip_addr == NULL) { vtss_io_state->fd_driver = open( "/dev/vitgenio", 0 ); //VTSS_ASSERT(vtss_io_state->fd_driver != -1); #ifdef NO_MMAP printf ("VTSS:io_reset no_mmap\n"); vtss_io_state->chip_addr = (void*)4; /* Any non-NULL value to indicate that the driver is ready. */ #else vtss_io_state->chip_addr = mmap( 0, <API key>, PROT_READ | PROT_WRITE, MAP_SHARED, vtss_io_state->fd_driver, 0 ); //VTSS_ASSERT( vtss_io_state->chip_addr != MAP_FAILED ); #endif } /* Call the I/O Layer driver callback, if present. */ if (vtss_io_state->io_driver_callback) vtss_io_state->io_driver_callback(); #endif #ifdef CUSTOMERIO /* Setup the hardware access (open device driver and setup MMU). */ /* Call the I/O Layer driver callback, if present. */ vtss_io_state->chip_addr = (void*)4; if (vtss_io_state->io_driver_callback) vtss_io_state->io_driver_callback(); #endif /* Reset and configure the chip. */ /* vtss_io_reset_chip(); */ } static ulong vtss_io_pi_read(const uint block, const uint subblock, const uint reg) { //VTSS_ASSERT( (block<=0x7)&&(subblock<=0xF)&&(reg<=0xFF) ); /* Use 32 bit access, letting the CPU split it up to two 16 bit bus accesses */ VTSS_NSLEEP( 240 ); /* Refer to the data sheet for timing diagrams. */ if ((block==VTSS_BLK_SYSTEM) && (subblock==VTSS_SUBBLK_CTRL) && ((reg==VTSS_REG_LOCAL_DATA)||(reg==<API key>))) { return (ulong)megis_read(block, subblock, reg); } else { /* Perform a dummy read to activate read request. */ megis_read(block, subblock, reg) ; /* Wait for data ready. */ VTSS_NSLEEP( 1000 ); /* Refer to the data sheet for timing diagrams. */ return (ulong)megis_read(VTSS_BLK_SYSTEM, VTSS_SUBBLK_CTRL, VTSS_REG_LOCAL_DATA); } } static void vtss_io_pi_write(const uint block, const uint subblock, const uint reg, const ulong value) { //VTSS_ASSERT( (block<=0x7)&&(subblock<=0xF)&&(reg<=0xFF) ); /* Use 32 bit access, letting the CPU split it up to two 16 bit bus accesses */ VTSS_NSLEEP( 120 ); /* Refer to the data sheet for timing diagrams. */ megis_write(block, subblock, reg, value); } ulong vtss_io_read(uint block, uint subblock, const uint reg) { ulong value; value = vtss_io_pi_read(block, subblock, reg); VTSS_N(("R 0x%01X 0x%01X 0x%02X 0x%08lX",block,subblock,reg,value)); return value; } void vtss_io_write(uint block, uint subblock, const uint reg, const ulong value) { VTSS_N(("W 0x%01X 0x%01X 0x%02X 0x%08lX",block,subblock,reg,value)); vtss_io_pi_write(block, subblock, reg, value); } void vtss_io_writemasked(uint block, uint subblock, const uint reg, const ulong value, const ulong mask) { VTSS_N(("M 0x%01X 0x%01X 0x%02X 0x%08lX 0x%08lX", block,subblock,reg,value,mask)); vtss_io_write(block,subblock,reg, (vtss_io_read(block,subblock,reg) & ~mask) | (value & mask) ); } static vtss_io_state_t default_io_state = { /* The following members must be present: */ /* This optional callback function will be called after the vtss_io_init function has completed. */ NULL, /*void (*io_driver_callback) (void);*/ /* The following members are implementation specific: */ 0, /*int fd_driver;*/ NULL /*ulong * chip_addr;*/ }; /* Pointer to current state. */ vtss_io_state_t * vtss_io_state = &default_io_state;
// Based on the ScummVM (GPLv2+) file of the same name #include "common/system.h" #include "scumm/actor.h" #include "scumm/charset.h" #ifdef ENABLE_HE #include "scumm/he/intern_he.h" #endif #include "scumm/resource.h" #include "scumm/scumm_v0.h" #include "scumm/scumm_v5.h" #include "scumm/scumm_v6.h" #include "scumm/usage_bits.h" #include "scumm/he/wiz_he.h" #include "scumm/util.h" #ifdef USE_ARM_GFX_ASM #ifndef IPHONE #define <API key> <API key> #define asmCopy8Col _asmCopy8Col #endif extern "C" void <API key>(int height, int width, void const* text, void const* src, byte* dst, int vsPitch, int vmScreenWidth, int textSurfacePitch); extern "C" void asmCopy8Col(byte* dst, int dstPitch, const byte* src, int height, uint8 bitDepth); #endif /* USE_ARM_GFX_ASM */ namespace Scumm { static void blit(byte *dst, int dstPitch, const byte *src, int srcPitch, int w, int h, uint8 bitDepth); static void fill(byte *dst, int dstPitch, uint16 color, int w, int h, uint8 bitDepth); #ifndef USE_ARM_GFX_ASM static void copy8Col(byte *dst, int dstPitch, const byte *src, int height, uint8 bitDepth); #endif static void clear8Col(byte *dst, int dstPitch, int height, uint8 bitDepth); static void ditherHerc(byte *src, byte *hercbuf, int srcPitch, int *x, int *y, int *width, int *height); struct StripTable { int offsets[160]; int run[160]; int color[160]; int zoffsets[120]; // FIXME: Why only 120 here? int zrun[120]; // FIXME: Why only 120 here? }; enum { kScrolltime = 500, // ms scrolling is supposed to take kPictureDelay = 20, kFadeDelay = 4 // 1/4th of a jiffie }; #define NUM_SHAKE_POSITIONS 8 static const int8 shake_positions[NUM_SHAKE_POSITIONS] = { 0, 1 * 2, 2 * 2, 1 * 2, 0 * 2, 2 * 2, 3 * 2, 1 * 2 }; /** * The following structs define four basic fades/transitions used by * transitionEffect(), each looking differently to the user. * Note that the stripTables contain strip numbers, and they assume * that the screen has 40 vertical strips (i.e. 320 pixel), and 25 horizontal * strips (i.e. 200 pixel). There is a hack in transitionEffect that * makes it work correctly in games which have a different screen height * (for example, 240 pixel), but nothing is done regarding the width, so this * code won't work correctly in COMI. Also, the number of iteration depends * on min(vertStrips, horizStrips}. So the 13 is derived from 25/2, rounded up. * And the 25 = min(25,40). Hence for Zak256 instead of 13 and 25, the values * 15 and 30 should be used, and for COMI probably 30 and 60. */ struct TransitionEffect { byte numOfIterations; int8 deltaTable[16]; // four times l / t / r / b byte stripTable[16]; // ditto }; static const TransitionEffect transitionEffects[6] = { // Iris effect (looks like an opening/closing camera iris) { 13, // Number of iterations { 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1 }, { 0, 0, 39, 0, 39, 0, 39, 24, 0, 24, 39, 24, 0, 0, 0, 24 } }, // Box wipe (a box expands from the upper-left corner to the lower-right corner) { 25, // Number of iterations { 0, 1, 2, 1, 2, 0, 2, 1, 2, 0, 2, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 255, 0, 0, 0 } }, // Box wipe (a box expands from the lower-right corner to the upper-left corner) { 25, // Number of iterations { -2, -1, 0, -1, -2, -1, -2, 0, -2, -1, -2, 0, 0, 0, 0, 0 }, { 39, 24, 39, 24, 39, 24, 39, 24, 38, 24, 38, 24, 255, 0, 0, 0 } }, // Inverse box wipe { 25, // Number of iterations { 0, -1, -2, -1, -2, 0, -2, -1, -2, 0, -2, -1, 0, 0, 0, 0 }, { 0, 24, 39, 24, 39, 0, 39, 24, 38, 0, 38, 24, 255, 0, 0, 0 } }, // Inverse iris effect, specially tailored for V1/V2 games { 9, // Number of iterations { -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1 }, { 7, 7, 32, 7, 7, 8, 32, 8, 7, 8, 7, 8, 32, 7, 32, 8 } }, // Horizontal wipe (a box expands from left to right side). For MM NES { 16, // Number of iterations { 2, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 15, 1, 0, 1, 15, 255, 0, 0, 0, 255, 0, 0, 0 } } }; Gdi::Gdi(ScummEngine *vm) : _vm(vm) { _numZBuffer = 0; memset(_imgBufOffs, 0, sizeof(_imgBufOffs)); _numStrips = 0; _paletteMod = 0; _roomPalette = vm->_roomPalette; _transparentColor = 255; _decomp_shr = 0; _decomp_mask = 0; _vertStripNextInc = 0; _zbufferDisabled = false; _objectMode = false; _distaff = false; } Gdi::~Gdi() { } GdiHE::GdiHE(ScummEngine *vm) : Gdi(vm), _tmskPtr(0) { } GdiNES::GdiNES(ScummEngine *vm) : Gdi(vm) { memset(&_NES, 0, sizeof(_NES)); } GdiPCEngine::GdiPCEngine(ScummEngine *vm) : Gdi(vm) { memset(&_PCE, 0, sizeof(_PCE)); } GdiPCEngine::~GdiPCEngine() { free(_PCE.roomTiles); free(_PCE.staffTiles); free(_PCE.masks); } GdiV1::GdiV1(ScummEngine *vm) : Gdi(vm) { memset(&_V1, 0, sizeof(_V1)); } GdiV2::GdiV2(ScummEngine *vm) : Gdi(vm) { _roomStrips = 0; } GdiV2::~GdiV2() { free(_roomStrips); } GdiHE16bit::GdiHE16bit(ScummEngine *vm) : GdiHE(vm) { } void Gdi::init() { _numStrips = _vm->_screenWidth / 8; // Increase the number of screen strips by one; needed for smooth scrolling if (_vm->_game.version >= 7) { // We now have mostly working smooth scrolling code in place for V7+ games // (i.e. The Dig, Full Throttle and COMI). It seems to work very well so far. // To understand how we achieve smooth scrolling, first note that with it, the // virtual screen strips don't match the display screen strips anymore. To // overcome that problem, we simply use a screen pitch that is 8 pixel wider // than the actual screen width, and always draw one strip more than needed to // the backbuf (thus we have to treat the right border seperately). _numStrips += 1; } } void Gdi::roomChanged(byte *roomptr) { } void GdiNES::roomChanged(byte *roomptr) { decodeNESGfx(roomptr); } void GdiPCEngine::roomChanged(byte *roomptr) { decodePCEngineGfx(roomptr); } void Gdi::loadTiles(byte *roomptr) { } void GdiPCEngine::loadTiles(byte *roomptr) { <API key>(_vm->findResourceData(MKTAG('T','I','L','E'), roomptr)); } void GdiV1::roomChanged(byte *roomptr) { for (int i = 0; i < 4; i++){ _V1.colors[i] = roomptr[6 + i]; } decodeV1Gfx(roomptr + READ_LE_UINT16(roomptr + 10), _V1.charMap, 2048); decodeV1Gfx(roomptr + READ_LE_UINT16(roomptr + 12), _V1.picMap, roomptr[4] * roomptr[5]); decodeV1Gfx(roomptr + READ_LE_UINT16(roomptr + 14), _V1.colorMap, roomptr[4] * roomptr[5]); decodeV1Gfx(roomptr + READ_LE_UINT16(roomptr + 16), _V1.maskMap, roomptr[4] * roomptr[5]); // Read the mask data. The 16bit length value seems to always be 8 too big. // See bug #1837375 for details on this. const byte *maskPtr = roomptr + READ_LE_UINT16(roomptr + 18); decodeV1Gfx(maskPtr + 2, _V1.maskChar, READ_LE_UINT16(maskPtr) - 8); _objectMode = true; } void GdiV2::roomChanged(byte *roomptr) { _roomStrips = generateStripTable(roomptr + READ_LE_UINT16(roomptr + 0x0A), _vm->_roomWidth, _vm->_roomHeight, _roomStrips); } #pragma mark - #pragma mark #pragma mark - void ScummEngine::initScreens(int b, int h) { int i; int adj = 0; for (i = 0; i < 3; i++) { _res->nukeResource(rtBuffer, i + 1); _res->nukeResource(rtBuffer, i + 5); } #ifndef <API key> if (_townsScreen) { if (!<API key> && (h - b != _virtscr[kMainVirtScreen].h)) _townsScreen->clearLayer(0); if (_game.id != GID_MONKEY) { _textSurface.fillRect(Common::Rect(0, 0, _textSurface.w * <API key>, _textSurface.h * <API key>), 0); _townsScreen->clearLayer(1); } } #endif if (!getResourceAddress(rtBuffer, 4)) { // Since the size of screen 3 is fixed, there is no need to reallocate // it if its size changed. // Not sure what it is good for, though. I think it may have been used // in pre-V7 for the games messages (like 'Pause', Yes/No dialogs, // version display, etc.). I don't know about V7, maybe the same is the // case there. If so, we could probably just remove it completely. if (_game.version >= 7) { initVirtScreen(kUnkVirtScreen, (_screenHeight / 2) - 10, _screenWidth, 13, false, false); } else { initVirtScreen(kUnkVirtScreen, 80, _screenWidth, 13, false, false); } } if ((_game.platform == Common::kPlatformNES) && (h != _screenHeight)) { // This is a hack to shift the whole screen downwards to match the original. // Otherwise we would have to do lots of coordinate adjustments all over // the code. adj = 16; initVirtScreen(kUnkVirtScreen, 0, _screenWidth, adj, false, false); } initVirtScreen(kMainVirtScreen, b + adj, _screenWidth, h - b, true, true); initVirtScreen(kTextVirtScreen, adj, _screenWidth, b, false, false); initVirtScreen(kVerbVirtScreen, h + adj, _screenWidth, _screenHeight - h - adj, false, false); _screenB = b; _screenH = h; _gdi->init(); } void ScummEngine::initVirtScreen(VirtScreenNumber slot, int top, int width, int height, bool twobufs, bool scrollable) { VirtScreen *vs = &_virtscr[slot]; int size; assert(height >= 0); assert((int)slot >= 0 && (int)slot < 4); if (_game.version >= 7) { if (slot == kMainVirtScreen && (_roomHeight != 0)) height = _roomHeight; } vs->number = slot; vs->w = width; vs->topline = top; vs->h = height; vs->hasTwoBuffers = twobufs; vs->xstart = 0; vs->backBuf = NULL; if (_game.features & GF_16BIT_COLOR) vs->format = Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 0); else vs->format = Graphics::PixelFormat::createFormatCLUT8(); vs->pitch = width * vs->format.bytesPerPixel; if (_game.version >= 7) { // Increase the pitch by one; needed to accomodate the extra screen // strip which we use to implement smooth scrolling. See Gdi::init(). vs->pitch += 8; } size = vs->pitch * vs->h; if (scrollable) { // Allow enough spaces so that rooms can be up to 4 resp. 8 screens // wide. To achieve horizontal scrolling, SCUMM uses a neat trick: // only the offset into the screen buffer (xstart) is changed. That way // very little of the screen has to be redrawn, and we have a very low // memory overhead (namely for every pixel we want to scroll, we need // one additional byte in the buffer). if (_game.version >= 7) { size += vs->pitch * 8; } else { size += vs->pitch * 4; } } _res->createResource(rtBuffer, slot + 1, size); vs->setPixels(getResourceAddress(rtBuffer, slot + 1)); memset(vs->getBasePtr(0, 0), 0, size); // reset background if (twobufs) { vs->backBuf = _res->createResource(rtBuffer, slot + 5, size); } if (slot != 3) { vs->setDirtyRange(0, height); } } VirtScreen *ScummEngine::findVirtScreen(int y) { VirtScreen *vs = _virtscr; int i; for (i = 0; i < 3; i++, vs++) { if (y >= vs->topline && y < vs->topline + vs->h) { return vs; } } return NULL; } void ScummEngine::markRectAsDirty(VirtScreenNumber virt, int left, int right, int top, int bottom, int dirtybit) { VirtScreen *vs = &_virtscr[virt]; int lp, rp; if (left > right || top > bottom) return; if (top > vs->h || bottom < 0) return; if (top < 0) top = 0; if (bottom > vs->h) bottom = vs->h; if (virt == kMainVirtScreen && dirtybit) { lp = left / 8 + _screenStartStrip; if (lp < 0) lp = 0; rp = (right + vs->xstart) / 8; if (_game.version >= 7) { if (rp > 409) rp = 409; } else { if (rp >= 200) rp = 200; } for (; lp <= rp; lp++) setGfxUsageBit(lp, dirtybit); } // The following code used to be in the separate method setVirtscreenDirty lp = left / 8; rp = right / 8; if ((lp >= _gdi->_numStrips) || (rp < 0)) return; if (lp < 0) lp = 0; if (rp >= _gdi->_numStrips) rp = _gdi->_numStrips - 1; while (lp <= rp) { if (top < vs->tdirty[lp]) vs->tdirty[lp] = top; if (bottom > vs->bdirty[lp]) vs->bdirty[lp] = bottom; lp++; } } /** * Update all dirty screen areas. This method blits all of the internal engine * graphics to the actual display, as needed. In addition, the 'shaking' * code in the backend is controlled from here. */ void ScummEngine::<API key>() { // Update verbs updateDirtyScreen(kVerbVirtScreen); // Update the conversation area (at the top of the screen) updateDirtyScreen(kTextVirtScreen); // Update game area ("stage") if (camera._last.x != camera._cur.x || (_game.version >= 7 && (camera._cur.y != camera._last.y))) { // Camera moved: redraw everything VirtScreen *vs = &_virtscr[kMainVirtScreen]; drawStripToScreen(vs, 0, vs->w, 0, vs->h); vs->setDirtyRange(vs->h, 0); } else { updateDirtyScreen(kMainVirtScreen); } // Handle shaking if (_shakeEnabled) { _shakeFrame = (_shakeFrame + 1) % NUM_SHAKE_POSITIONS; _system->setShakePos(shake_positions[_shakeFrame]); } else if (!_shakeEnabled &&_shakeFrame != 0) { _shakeFrame = 0; _system->setShakePos(0); } } void ScummEngine_v6::<API key>() { // For the Full Throttle credits to work properly, the blast // texts have to be drawn before the blast objects. Unless // someone can think of a better way to achieve this effect. if (_game.version >= 7 && VAR(<API key>) == 1) { drawBlastTexts(); drawBlastObjects(); if (_game.version == 8) { // Does this case ever happen? We need to draw the // actor over the blast object, so we're forced to // also draw it over the subtitles. processUpperActors(); } } else { drawBlastObjects(); if (_game.version == 8) { // Do this before drawing blast texts. Subtitles go on // top of the CoMI verb coin, e.g. when Murray is // talking to himself early in the game. processUpperActors(); } drawBlastTexts(); } // Call the original method. ScummEngine::<API key>(); // Remove all blasted objects/text again. removeBlastTexts(); removeBlastObjects(); } /** * Blit the dirty data from the given VirtScreen to the display. If the camera moved, * a full blit is done, otherwise only the visible dirty areas are updated. */ void ScummEngine::updateDirtyScreen(VirtScreenNumber slot) { VirtScreen *vs = &_virtscr[slot]; // Do nothing for unused virtual screens if (vs->h == 0) return; int i; int w = 8; int start = 0; for (i = 0; i < _gdi->_numStrips; i++) { if (vs->bdirty[i]) { const int top = vs->tdirty[i]; const int bottom = vs->bdirty[i]; vs->tdirty[i] = vs->h; vs->bdirty[i] = 0; if (i != (_gdi->_numStrips - 1) && vs->bdirty[i + 1] == bottom && vs->tdirty[i + 1] == top) { // Simple optimizations: if two or more neighboring strips // form one bigger rectangle, coalesce them. w += 8; continue; } drawStripToScreen(vs, start * 8, w, top, bottom); w = 8; } start = i + 1; } } /** * Blit the specified rectangle from the given virtual screen to the display. * Note: t and b are in *virtual screen* coordinates, while x is relative to * the *real screen*. This is due to the way tdirty/vdirty work: they are * arrays which map 'strips' (sections of the real screen) to dirty areas as * specified by top/bottom coordinate in the virtual screen. */ void ScummEngine::drawStripToScreen(VirtScreen *vs, int x, int width, int top, int bottom) { // Short-circuit if nothing has to be drawn if (bottom <= top || top >= vs->h) return; // Some paranoia checks assert(top >= 0 && bottom <= vs->h); assert(x >= 0 && width <= vs->pitch); assert(_textSurface.getPixels()); // Perform some clipping if (width > vs->w - x) width = vs->w - x; if (top < _screenTop) top = _screenTop; if (bottom > _screenTop + _screenHeight) bottom = _screenTop + _screenHeight; // Convert the vertical coordinates to real screen coords int y = vs->topline + top - _screenTop; int height = bottom - top; if (width <= 0 || height <= 0) return; const void *src = vs->getPixels(x, top); int m = <API key>; int vsPitch; int pitch = vs->pitch; vsPitch = vs->pitch - width * vs->format.bytesPerPixel; if (_game.version < 7) { // For The Dig, FT and COMI, we just blit everything to the screen at once. // For older games, things are more complicated. First off, we need to // deal with the _textSurface, which needs to be composited over the // screen contents. Secondly, a rendering mode might be active, which // means a filter has to be applied. // Compute pointer to the text surface assert(_compositeBuf); const void *text = _textSurface.getBasePtr(x * m, y * m); // The values x, width, etc. are all multiples of 8 at this point, // so loop unrolloing might be a good idea... assert(IS_ALIGNED(text, 4)); assert(0 == (width & 3)); // Compose the text over the game graphics #ifndef <API key> if (_game.platform == Common::kPlatformFMTowns) { <API key>(vs, x, y, x, top, width, height); return; } else #endif if (_outputPixelFormat.bytesPerPixel == 2) { const byte *srcPtr = (const byte *)src; const byte *textPtr = (byte *)_textSurface.getBasePtr(x * m, y * m); byte *dstPtr = _compositeBuf; for (int h = 0; h < height * m; ++h) { for (int w = 0; w < width * m; ++w) { uint16 tmp = *textPtr++; if (tmp == <API key>) { tmp = READ_UINT16(srcPtr); WRITE_UINT16(dstPtr, tmp); dstPtr += 2; } else if (_game.heversion != 0) { error ("16Bit Color HE Game using old charset"); } else { WRITE_UINT16(dstPtr, _16BitPalette[tmp]); dstPtr += 2; } srcPtr += vs->format.bytesPerPixel; } srcPtr += vsPitch; textPtr += _textSurface.pitch - width * m; } } else { #ifdef USE_ARM_GFX_ASM <API key>(height, width, text, src, _compositeBuf, vs->pitch, width, _textSurface.pitch); #else // We blit four pixels at a time, for improved performance. const uint32 *src32 = (const uint32 *)src; uint32 *dst32 = (uint32 *)_compositeBuf; vsPitch >>= 2; const uint32 *text32 = (const uint32 *)text; const int textPitch = (_textSurface.pitch - width * m) >> 2; for (int h = height * m; h > 0; --h) { for (int w = width * m; w > 0; w -= 4) { uint32 temp = *text32++; // Generate a byte mask for those text pixels (bytes) with // value <API key>. In the end, each byte // in mask will be either equal to 0x00 or 0xFF. // Doing it this way avoids branches and bytewise operations, // at the cost of readability ;). uint32 mask = temp ^ <API key>; mask = (((mask & 0x7f7f7f7f) + 0x7f7f7f7f) | mask) & 0x80808080; mask = ((mask >> 7) + 0x7f7f7f7f) ^ 0x80808080; // The following line is equivalent to this code: // *dst32++ = (*src32++ & mask) | (temp & ~mask); // However, some compilers can generate somewhat better // machine code for this equivalent statement: *dst32++ = ((temp ^ *src32++) & mask) ^ temp; } src32 += vsPitch; text32 += textPitch; } #endif } src = _compositeBuf; pitch = width * vs->format.bytesPerPixel; if (_renderMode == Common::kRenderHercA || _renderMode == Common::kRenderHercG) { ditherHerc(_compositeBuf, _herculesBuf, width, &x, &y, &width, &height); src = _herculesBuf + x + y * kHercWidth; pitch = kHercWidth; // center image on the screen x += (kHercWidth - _screenWidth * 2) / 2; // (720 - 320*2)/2 = 40 } else if (_useCJKMode && m == 2) { pitch *= m; x *= m; y *= m; width *= m; height *= m; } else { if (_renderMode == Common::kRenderCGA) ditherCGA(_compositeBuf, width, x, y, width, height); // HACK: This is dirty hack which renders narrow NES rooms centered // NES can address negative number strips and that poses problem for // our code. So instead of adding zillions of fixes and potentially // breaking other games, we shift it right at the rendering stage. if ((_game.platform == Common::kPlatformNES) && (((_NESStartStrip > 0) && (vs->number == kMainVirtScreen)) || (vs->number == kTextVirtScreen))) { x += 16; while (x + width >= _screenWidth) width -= 16; if (width <= 0) return; // HACK: In this way we won't get a screen with dirty side strips when // loading a narrow room in a full screen room. if (width == 224 && height == 240 && x == 16) { char blackbuf[16 * 240]; memset(blackbuf, 0, 16 * 240); // Prepare a buffer 16px wide and 240px high, to fit on a lateral strip width = 240; // Fix right strip _system->copyRectToScreen(blackbuf, 16, 0, 0, 16, 240); // Fix left strip } } } } // Finally blit the whole thing to the screen _system->copyRectToScreen(src, pitch, x, y, width, height); } // CGA // indy3 loom maniac monkey1 zak // Herc (720x350) // maniac monkey1 zak // EGA // monkey2 loom maniac monkey1 atlantis indy3 zak loomcd static const byte cgaDither[2][2][16] = { {{0, 1, 0, 1, 2, 2, 0, 0, 3, 1, 3, 1, 3, 2, 1, 3}, {0, 0, 1, 1, 0, 2, 2, 3, 0, 3, 1, 1, 3, 3, 1, 3}}, {{0, 0, 1, 1, 0, 2, 2, 3, 0, 3, 1, 1, 3, 3, 1, 3}, {0, 1, 0, 1, 2, 2, 0, 0, 3, 1, 1, 1, 3, 2, 1, 3}}}; // CGA dithers 4x4 square with direct substitutes // Odd lines have colors swapped, so there will be checkered patterns. // But apparently there is a mistake for 10th color. void ScummEngine::ditherCGA(byte *dst, int dstPitch, int x, int y, int width, int height) const { byte *ptr; int idx1, idx2; for (int y1 = 0; y1 < height; y1++) { ptr = dst + y1 * dstPitch; if (_game.version == 2) idx1 = 0; else idx1 = (y + y1) % 2; for (int x1 = 0; x1 < width; x1++) { idx2 = (x + x1) % 2; *ptr = cgaDither[idx1][idx2][*ptr & 0xF]; ptr++; } } } // Hercules dithering. It uses same dithering tables but output is 1bpp and // it stretches in this way: // aaaa0 // aa aaaa1 // bb bbbb0 Here 0 and 1 mean dithering table row number // cc --> bbbb1 // dd cccc0 // cccc1 // dddd0 void ditherHerc(byte *src, byte *hercbuf, int srcPitch, int *x, int *y, int *width, int *height) { byte *srcptr, *dstptr; const int xo = *x, yo = *y, widtho = *width, heighto = *height; int dsty = yo*2 - yo/4; for (int y1 = 0; y1 < heighto;) { assert(dsty < kHercHeight); srcptr = src + y1 * srcPitch; dstptr = hercbuf + dsty * kHercWidth + xo * 2; const int idx1 = (dsty % 7) % 2; for (int x1 = 0; x1 < widtho; x1++) { const int idx2 = (xo + x1) % 2; const byte tmp = cgaDither[idx1][idx2][*srcptr & 0xF]; *dstptr++ = tmp >> 1; *dstptr++ = tmp & 0x1; srcptr++; } if (idx1 || dsty % 7 == 6) y1++; dsty++; } *x *= 2; *y = yo*2 - yo/4; *width *= 2; *height = dsty - *y; } #pragma mark - #pragma mark #pragma mark - void ScummEngine::initBGBuffers(int height) { const byte *ptr; int size, itemsize, i; byte *room; if (_game.version >= 7) { // Resize main virtual screen in V7 games. This is necessary // because in V7, rooms may be higher than one screen, so we have // to accomodate for that. initVirtScreen(kMainVirtScreen, _virtscr[kMainVirtScreen].topline, _screenWidth, height, true, true); } if (_game.heversion >= 70) room = getResourceAddress(rtRoomImage, _roomResource); else room = getResourceAddress(rtRoom, _roomResource); if (_game.version <= 3) { _gdi->_numZBuffer = 2; } else if (_game.features & GF_SMALL_HEADER) { int off; ptr = findResourceData(MKTAG('S','M','A','P'), room); _gdi->_numZBuffer = 0; if (_game.features & GF_16COLOR) off = READ_LE_UINT16(ptr); else off = READ_LE_UINT32(ptr); while (off && _gdi->_numZBuffer < 4) { _gdi->_numZBuffer++; ptr += off; off = READ_LE_UINT16(ptr); } } else if (_game.version == 8) { // in V8 there is no RMIH and num z buffers is in RMHD ptr = findResource(MKTAG('R','M','H','D'), room); _gdi->_numZBuffer = READ_LE_UINT32(ptr + 24) + 1; } else if (_game.heversion >= 70) { ptr = findResource(MKTAG('R','M','I','H'), room); _gdi->_numZBuffer = READ_LE_UINT16(ptr + 8) + 1; } else { ptr = findResource(MKTAG('R','M','I','H'), findResource(MKTAG('R','M','I','M'), room)); _gdi->_numZBuffer = READ_LE_UINT16(ptr + 8) + 1; } assert(_gdi->_numZBuffer >= 1 && _gdi->_numZBuffer <= 8); if (_game.version >= 7) itemsize = (_roomHeight + 10) * _gdi->_numStrips; else itemsize = (_roomHeight + 4) * _gdi->_numStrips; size = itemsize * _gdi->_numZBuffer; memset(_res->createResource(rtBuffer, 9, size), 0, size); for (i = 0; i < (int)ARRAYSIZE(_gdi->_imgBufOffs); i++) { if (i < _gdi->_numZBuffer) _gdi->_imgBufOffs[i] = i * itemsize; else _gdi->_imgBufOffs[i] = (_gdi->_numZBuffer - 1) * itemsize; } } /** * Redraw background as needed, i.e. the left/right sides if scrolling took place etc. * Note that this only updated the virtual screen, not the actual display. */ void ScummEngine::redrawBGAreas() { int i; int diff; int val = 0; if (_game.id != GID_PASS && _game.version >= 4 && _game.version <= 6) { // Starting with V4 games (with the exception of the PASS demo), text // is drawn over the game graphics (as opposed to be drawn in a // separate region of the screen). So, when scrolling in one of these // games (pre-new camera system), if actor text is visible (as indicated // by the _hasMask flag), we first remove it before proceeding. if (camera._cur.x != camera._last.x && _charset->_hasMask) stopTalk(); } // Redraw parts of the background which are marked as dirty. if (!_fullRedraw && _bgNeedsRedraw) { for (i = 0; i != _gdi->_numStrips; i++) { if (testGfxUsageBit(_screenStartStrip + i, USAGE_BIT_DIRTY)) { redrawBGStrip(i, 1); } } } if (_game.version >= 7) { diff = camera._cur.x / 8 - camera._last.x / 8; if (_fullRedraw || ABS(diff) >= _gdi->_numStrips) { _bgNeedsRedraw = false; redrawBGStrip(0, _gdi->_numStrips); } else if (diff > 0) { val = -diff; redrawBGStrip(_gdi->_numStrips - diff, diff); } else if (diff < 0) { val = -diff; redrawBGStrip(0, -diff); } } else { diff = camera._cur.x - camera._last.x; if (!_fullRedraw && diff == 8) { val = -1; redrawBGStrip(_gdi->_numStrips - 1, 1); } else if (!_fullRedraw && diff == -8) { val = +1; redrawBGStrip(0, 1); } else if (_fullRedraw || diff != 0) { if (_game.version <= 5) { ((ScummEngine_v5 *)this)->clearFlashlight(); } _bgNeedsRedraw = false; redrawBGStrip(0, _gdi->_numStrips); } } drawRoomObjects(val); _bgNeedsRedraw = false; } #ifdef ENABLE_HE void ScummEngine_v71he::redrawBGAreas() { if (camera._cur.x != camera._last.x && _charset->_hasMask) stopTalk(); byte *room = getResourceAddress(rtRoomImage, _roomResource) + _IM00_offs; if (_fullRedraw) { _bgNeedsRedraw = false; _gdi->drawBMAPBg(room, &_virtscr[kMainVirtScreen]); } drawRoomObjects(0); _bgNeedsRedraw = false; } void ScummEngine_v72he::redrawBGAreas() { ScummEngine_v71he::redrawBGAreas(); _wiz->flushWizBuffer(); } #endif void ScummEngine::redrawBGStrip(int start, int num) { byte *room; int s = _screenStartStrip + start; for (int i = 0; i < num; i++) setGfxUsageBit(s + i, USAGE_BIT_DIRTY); if (_game.heversion >= 70) room = getResourceAddress(rtRoomImage, _roomResource); else room = getResourceAddress(rtRoom, _roomResource); _gdi->drawBitmap(room + _IM00_offs, &_virtscr[kMainVirtScreen], s, 0, _roomWidth, _virtscr[kMainVirtScreen].h, s, num, 0); } void ScummEngine::restoreBackground(Common::Rect rect, byte backColor) { VirtScreen *vs; byte *screenBuf; if (rect.top < 0) rect.top = 0; if (rect.left >= rect.right || rect.top >= rect.bottom) return; if ((vs = findVirtScreen(rect.top)) == NULL) return; if (rect.left > vs->w) return; // Indy4 Amiga always uses the room or verb palette map to match colors to // the currently setup palette, thus we need to select it over here too. // Done like the original interpreter. if (_game.platform == Common::kPlatformAmiga && _game.id == GID_INDY4) { if (vs->number == kVerbVirtScreen) backColor = _verbPalette[backColor]; else backColor = _roomPalette[backColor]; } // Convert 'rect' to local (virtual screen) coordinates rect.top -= vs->topline; rect.bottom -= vs->topline; rect.clip(vs->w, vs->h); const int height = rect.height(); const int width = rect.width(); #ifndef <API key> if (_game.platform == Common::kPlatformFMTowns && _game.id == GID_MONKEY && vs->number == kVerbVirtScreen && rect.bottom <= 154) rect.right = 319; #endif markRectAsDirty(vs->number, rect, USAGE_BIT_RESTORED); screenBuf = vs->getPixels(rect.left, rect.top); if (!height) return; if (vs->hasTwoBuffers && _currentRoom != 0 && isLightOn()) { blit(screenBuf, vs->pitch, vs->getBackPixels(rect.left, rect.top), vs->pitch, width, height, vs->format.bytesPerPixel); if (vs->number == kMainVirtScreen && _charset->_hasMask) { #ifndef <API key> if (_game.platform == Common::kPlatformFMTowns) { byte *mask = (byte *)_textSurface.getBasePtr(rect.left * <API key>, (rect.top + vs->topline) * <API key>); fill(mask, _textSurface.pitch, 0, width * <API key>, height * <API key>, _textSurface.format.bytesPerPixel); } else #endif { byte *mask = (byte *)_textSurface.getBasePtr(rect.left, rect.top - _screenTop); fill(mask, _textSurface.pitch, <API key>, width * <API key>, height * <API key>, _textSurface.format.bytesPerPixel); } } } else { #ifndef <API key> if (_game.platform == Common::kPlatformFMTowns) { backColor |= (backColor << 4); byte *mask = (byte *)_textSurface.getBasePtr(rect.left * <API key>, (rect.top + vs->topline) * <API key>); fill(mask, _textSurface.pitch, backColor, width * <API key>, height * <API key>, _textSurface.format.bytesPerPixel); } #endif if (_game.features & GF_16BIT_COLOR) fill(screenBuf, vs->pitch, _16BitPalette[backColor], width, height, vs->format.bytesPerPixel); else fill(screenBuf, vs->pitch, backColor, width, height, vs->format.bytesPerPixel); } } void ScummEngine::restoreCharsetBg() { _nextLeft = _string[0].xpos; _nextTop = _string[0].ypos + _screenTop; if (_charset->_hasMask) { _charset->_hasMask = false; _charset->_str.left = -1; _charset->_left = -1; // Restore background on the whole text area. This code is based on // restoreBackground(), but was changed to only restore those parts which are // currently covered by the charset mask. VirtScreen *vs = &_virtscr[_charset->_textScreenID]; if (!vs->h) return; markRectAsDirty(vs->number, Common::Rect(vs->w, vs->h), USAGE_BIT_RESTORED); byte *screenBuf = vs->getPixels(0, 0); if (vs->hasTwoBuffers && _currentRoom != 0 && isLightOn()) { if (vs->number != kMainVirtScreen) { // Restore from back buffer const byte *backBuf = vs->getBackPixels(0, 0); blit(screenBuf, vs->pitch, backBuf, vs->pitch, vs->w, vs->h, vs->format.bytesPerPixel); } } else { // Clear area memset(screenBuf, 0, vs->h * vs->pitch); } if (vs->hasTwoBuffers) { // Clean out the charset mask clearTextSurface(); } } } void ScummEngine::clearCharsetMask() { memset(getResourceAddress(rtBuffer, 9), 0, _gdi->_imgBufOffs[1]); } void ScummEngine::clearTextSurface() { #ifndef <API key> if (_townsScreen) _townsScreen->fillLayerRect(1, 0, 0, _textSurface.w, _textSurface.h, 0); #endif fill((byte *)_textSurface.getPixels(), _textSurface.pitch, #ifndef <API key> _game.platform == Common::kPlatformFMTowns ? 0 : #endif <API key>, _textSurface.w, _textSurface.h, _textSurface.format.bytesPerPixel); } byte *ScummEngine::getMaskBuffer(int x, int y, int z) { return _gdi->getMaskBuffer((x + _virtscr[kMainVirtScreen].xstart) / 8, y, z); } byte *Gdi::getMaskBuffer(int x, int y, int z) { return _vm->getResourceAddress(rtBuffer, 9) + x + y * _numStrips + _imgBufOffs[z]; } #pragma mark - #pragma mark #pragma mark - static void blit(byte *dst, int dstPitch, const byte *src, int srcPitch, int w, int h, uint8 bitDepth) { assert(w > 0); assert(h > 0); assert(src != NULL); assert(dst != NULL); if ((w * bitDepth == srcPitch) && (w * bitDepth == dstPitch)) { memcpy(dst, src, w * h * bitDepth); } else { do { memcpy(dst, src, w * bitDepth); dst += dstPitch; src += srcPitch; } while (--h); } } static void fill(byte *dst, int dstPitch, uint16 color, int w, int h, uint8 bitDepth) { assert(h > 0); assert(dst != NULL); if (bitDepth == 2) { do { for (int i = 0; i < w; i++) WRITE_UINT16(dst + i * 2, color); dst += dstPitch; } while (--h); } else { if (w == dstPitch) { memset(dst, color, w * h); } else { do { memset(dst, color, w); dst += dstPitch; } while (--h); } } } #ifdef USE_ARM_GFX_ASM #define copy8Col(A,B,C,D,E) asmCopy8Col(A,B,C,D,E) #else static void copy8Col(byte *dst, int dstPitch, const byte *src, int height, uint8 bitDepth) { do { #if defined(<API key>) memcpy(dst, src, 8 * bitDepth); #else ((uint32 *)dst)[0] = ((const uint32 *)src)[0]; ((uint32 *)dst)[1] = ((const uint32 *)src)[1]; if (bitDepth == 2) { ((uint32 *)dst)[2] = ((const uint32 *)src)[2]; ((uint32 *)dst)[3] = ((const uint32 *)src)[3]; } #endif dst += dstPitch; src += dstPitch; } while (--height); } #endif /* USE_ARM_GFX_ASM */ static void clear8Col(byte *dst, int dstPitch, int height, uint8 bitDepth) { do { #if defined(<API key>) memset(dst, 0, 8 * bitDepth); #else ((uint32 *)dst)[0] = 0; ((uint32 *)dst)[1] = 0; if (bitDepth == 2) { ((uint32 *)dst)[2] = 0; ((uint32 *)dst)[3] = 0; } #endif dst += dstPitch; } while (--height); } void ScummEngine::drawBox(int x, int y, int x2, int y2, int color) { int width, height; VirtScreen *vs; byte *backbuff, *bgbuff; if ((vs = findVirtScreen(y)) == NULL) return; // Indy4 Amiga always uses the room or verb palette map to match colors to // the currently setup palette, thus we need to select it over here too. // Done like the original interpreter. if (_game.platform == Common::kPlatformAmiga && _game.id == GID_INDY4) { if (vs->number == kVerbVirtScreen) color = _verbPalette[color]; else color = _roomPalette[color]; } if (x > x2) SWAP(x, x2); if (y > y2) SWAP(y, y2); x2++; y2++; // Adjust for the topline of the VirtScreen y -= vs->topline; y2 -= vs->topline; // Clip the coordinates if (x < 0) x = 0; else if (x >= vs->w) return; if (x2 < 0) return; else if (x2 > vs->w) x2 = vs->w; if (y < 0) y = 0; else if (y > vs->h) return; if (y2 < 0) return; else if (y2 > vs->h) y2 = vs->h; width = x2 - x; height = y2 - y; // This will happen in the Sam & Max intro - see bug #1039162 - where // it would trigger an assertion in blit(). if (width <= 0 || height <= 0) return; markRectAsDirty(vs->number, x, x2, y, y2); backbuff = vs->getPixels(x, y); bgbuff = vs->getBackPixels(x, y); // A check for -1 might be wrong in all cases since o5_drawBox() in its current form // is definitely not capable of passing a parameter of -1 (color range is 0 - 255). // Just to make sure I don't break anything I restrict the code change to FM-Towns // version 5 games where this change is necessary to fix certain long standing bugs. if (color == -1 #ifndef <API key> || (color >= 254 && _game.platform == Common::kPlatformFMTowns && (_game.id == GID_MONKEY2 || _game.id == GID_INDY4)) #endif ) { #ifndef <API key> if (_game.platform == Common::kPlatformFMTowns) { if (color == 254) <API key>(x, y, x2, y2); } else #endif { if (vs->number != kMainVirtScreen) error("can only copy bg to main window"); blit(backbuff, vs->pitch, bgbuff, vs->pitch, width, height, vs->format.bytesPerPixel); if (_charset->_hasMask) { byte *mask = (byte *)_textSurface.getBasePtr(x * <API key>, (y - _screenTop) * <API key>); fill(mask, _textSurface.pitch, <API key>, width * <API key>, height * <API key>, _textSurface.format.bytesPerPixel); } } } else if (_game.heversion >= 72) { // Flags are used for different methods in HE games uint32 flags = color; if ((flags & 0x2000) || (flags & 0x4000000)) { blit(backbuff, vs->pitch, bgbuff, vs->pitch, width, height, vs->format.bytesPerPixel); } else if ((flags & 0x4000) || (flags & 0x2000000)) { blit(bgbuff, vs->pitch, backbuff, vs->pitch, width, height, vs->format.bytesPerPixel); } else if ((flags & 0x8000) || (flags & 0x1000000)) { flags &= (flags & 0x1000000) ? 0xFFFFFF : 0x7FFF; fill(backbuff, vs->pitch, flags, width, height, vs->format.bytesPerPixel); fill(bgbuff, vs->pitch, flags, width, height, vs->format.bytesPerPixel); } else { fill(backbuff, vs->pitch, flags, width, height, vs->format.bytesPerPixel); } } else if (_game.heversion >= 60) { // Flags are used for different methods in HE games uint16 flags = color; if (flags & 0x2000) { blit(backbuff, vs->pitch, bgbuff, vs->pitch, width, height, vs->format.bytesPerPixel); } else if (flags & 0x4000) { blit(bgbuff, vs->pitch, backbuff, vs->pitch, width, height, vs->format.bytesPerPixel); } else if (flags & 0x8000) { flags &= 0x7FFF; fill(backbuff, vs->pitch, flags, width, height, vs->format.bytesPerPixel); fill(bgbuff, vs->pitch, flags, width, height, vs->format.bytesPerPixel); } else { fill(backbuff, vs->pitch, flags, width, height, vs->format.bytesPerPixel); } } else { if (_game.features & GF_16BIT_COLOR) { fill(backbuff, vs->pitch, _16BitPalette[color], width, height, vs->format.bytesPerPixel); } else { #ifndef <API key> if (_game.platform == Common::kPlatformFMTowns) { color = ((color & 0x0f) << 4) | (color & 0x0f); byte *mask = (byte *)_textSurface.getBasePtr(x * <API key>, (y - _screenTop + vs->topline) * <API key>); fill(mask, _textSurface.pitch, color, width * <API key>, height * <API key>, _textSurface.format.bytesPerPixel); if (_game.id == GID_MONKEY2 || _game.id == GID_INDY4 || ((_game.id == GID_INDY3 || _game.id == GID_ZAK) && vs->number != kTextVirtScreen) || (_game.id == GID_LOOM && vs->number == kMainVirtScreen)) return; } #endif fill(backbuff, vs->pitch, color, width, height, vs->format.bytesPerPixel); } } } /** * Moves the screen content by the offset specified via dx/dy. * Only the region from x=0 till x=height-1 is affected. * @param dx the horizontal offset. * @param dy the vertical offset. * @param height the number of lines which in which the move will be done. */ void ScummEngine::moveScreen(int dx, int dy, int height) { // Short circuit check - do we have to do anything anyway? if ((dx == 0 && dy == 0) || height <= 0) return; Graphics::Surface *screen = _system->lockScreen(); if (!screen) return; screen->move(dx, dy, height); _system->unlockScreen(); } void ScummEngine_v5::clearFlashlight() { _flashlight.isDrawn = false; _flashlight.buffer = NULL; } void ScummEngine_v5::drawFlashlight() { int i, j, x, y; VirtScreen *vs = &_virtscr[kMainVirtScreen]; // Remove the flash light first if it was previously drawn if (_flashlight.isDrawn) { markRectAsDirty(kMainVirtScreen, _flashlight.x, _flashlight.x + _flashlight.w, _flashlight.y, _flashlight.y + _flashlight.h, USAGE_BIT_DIRTY); if (_flashlight.buffer) { fill(_flashlight.buffer, vs->pitch, 0, _flashlight.w, _flashlight.h, vs->format.bytesPerPixel); } _flashlight.isDrawn = false; } if (_flashlight.xStrips == 0 || _flashlight.yStrips == 0) return; // Calculate the area of the flashlight if (_game.id == GID_ZAK || _game.id == GID_MANIAC) { x = _mouse.x + vs->xstart; y = _mouse.y - vs->topline; } else { Actor *a = derefActor(VAR(VAR_EGO), "drawFlashlight"); x = a->getPos().x; y = a->getPos().y; } _flashlight.w = _flashlight.xStrips * 8; _flashlight.h = _flashlight.yStrips * 8; _flashlight.x = x - _flashlight.w / 2 - _screenStartStrip * 8; _flashlight.y = y - _flashlight.h / 2; if (_game.id == GID_LOOM) _flashlight.y -= 12; // Clip the flashlight at the borders if (_flashlight.x < 0) _flashlight.x = 0; else if (_flashlight.x + _flashlight.w > _gdi->_numStrips * 8) _flashlight.x = _gdi->_numStrips * 8 - _flashlight.w; if (_flashlight.y < 0) _flashlight.y = 0; else if (_flashlight.y + _flashlight.h> vs->h) _flashlight.y = vs->h - _flashlight.h; // Redraw any actors "under" the flashlight for (i = _flashlight.x / 8; i < (_flashlight.x + _flashlight.w) / 8; i++) { assert(0 <= i && i < _gdi->_numStrips); setGfxUsageBit(_screenStartStrip + i, USAGE_BIT_DIRTY); vs->tdirty[i] = 0; vs->bdirty[i] = vs->h; } byte *bgbak; _flashlight.buffer = vs->getPixels(_flashlight.x, _flashlight.y); bgbak = vs->getBackPixels(_flashlight.x, _flashlight.y); blit(_flashlight.buffer, vs->pitch, bgbak, vs->pitch, _flashlight.w, _flashlight.h, vs->format.bytesPerPixel); // Round the corners. To do so, we simply hard-code a set of nicely // rounded corners. static const int corner_data[] = { 8, 6, 4, 3, 2, 2, 1, 1 }; int minrow = 0; int maxcol = (_flashlight.w - 1) * vs->format.bytesPerPixel; int maxrow = (_flashlight.h - 1) * vs->pitch; for (i = 0; i < 8; i++, minrow += vs->pitch, maxrow -= vs->pitch) { int d = corner_data[i]; for (j = 0; j < d; j++) { if (vs->format.bytesPerPixel == 2) { WRITE_UINT16(&_flashlight.buffer[minrow + 2 * j], 0); WRITE_UINT16(&_flashlight.buffer[minrow + maxcol - 2 * j], 0); WRITE_UINT16(&_flashlight.buffer[maxrow + 2 * j], 0); WRITE_UINT16(&_flashlight.buffer[maxrow + maxcol - 2 * j], 0); } else { _flashlight.buffer[minrow + j] = 0; _flashlight.buffer[minrow + maxcol - j] = 0; _flashlight.buffer[maxrow + j] = 0; _flashlight.buffer[maxrow + maxcol - j] = 0; } } } _flashlight.isDrawn = true; } int ScummEngine_v0::getCurrentLights() const { // V0 Maniac doesn't have a ScummVar for VAR_CURRENT_LIGHTS, and just uses // an internal variable. Emulate this to prevent overwriting script vars... // And V6 games do not use the "lights" at all. There, the whole screen is // always visible, and actors are always colored, so we fake the correct // light value for it. return _currentLights; } int ScummEngine::getCurrentLights() const { if (_game.version >= 6) return <API key> | <API key>; else return VAR(VAR_CURRENT_LIGHTS); } bool ScummEngine::isLightOn() const { return (getCurrentLights() & <API key>) != 0; } void ScummEngine::setShake(int mode) { if (_shakeEnabled != (mode != 0)) _fullRedraw = true; _shakeEnabled = mode != 0; _shakeFrame = 0; _system->setShakePos(0); } #pragma mark - #pragma mark #pragma mark - void Gdi::prepareDrawBitmap(const byte *ptr, VirtScreen *vs, const int x, const int y, const int width, const int height, int stripnr, int numstrip) { // Do nothing by default } void GdiHE::prepareDrawBitmap(const byte *ptr, VirtScreen *vs, const int x, const int y, const int width, const int height, int stripnr, int numstrip) { if (_vm->_game.heversion >= 72) { _tmskPtr = _vm->findResource(MKTAG('T','M','S','K'), ptr); } else _tmskPtr = 0; } void GdiV1::prepareDrawBitmap(const byte *ptr, VirtScreen *vs, const int x, const int y, const int width, const int height, int stripnr, int numstrip) { if (_objectMode) { decodeV1Gfx(ptr, _V1.objectMap, (width / 8) * (height / 8) * 3); } } void GdiNES::prepareDrawBitmap(const byte *ptr, VirtScreen *vs, const int x, const int y, const int width, const int height, int stripnr, int numstrip) { if (_objectMode) { decodeNESObject(ptr, x - stripnr, y, width, height); } } void GdiPCEngine::prepareDrawBitmap(const byte *ptr, VirtScreen *vs, const int x, const int y, const int width, const int height, int stripnr, int numstrip) { if (_objectMode) { <API key>(ptr, x - stripnr, y, width, height); } } void GdiV2::prepareDrawBitmap(const byte *ptr, VirtScreen *vs, const int x, const int y, const int width, const int height, int stripnr, int numstrip) { // Since V3, all graphics data was encoded in strips, which is very efficient // for redrawing only parts of the screen. However, V2 is different: here // the whole graphics are encoded as one big chunk. That makes it rather // difficult to draw only parts of a room/object. We handle the V2 graphics // differently from all other (newer) graphic formats for this reason. StripTable *table = (_objectMode ? 0 : _roomStrips); const int left = (stripnr * 8); const int right = left + (numstrip * 8); byte *dst; byte *mask_ptr; const byte *src; byte color, data = 0; int run; bool dither = false; byte dither_table[128]; byte *ptr_dither_table; int theX, theY, maxX; memset(dither_table, 0, sizeof(dither_table)); if (vs->hasTwoBuffers) dst = vs->backBuf + y * vs->pitch + x * 8; else dst = (byte *)vs->getBasePtr(x * 8, y); mask_ptr = getMaskBuffer(x, y, 1); if (table) { run = table->run[stripnr]; color = table->color[stripnr]; src = ptr + table->offsets[stripnr]; theX = left; maxX = right; } else { run = 1; color = 0; src = ptr; theX = 0; maxX = width; } // Decode and draw the image data. assert(height <= 128); for (; theX < maxX; theX++) { ptr_dither_table = dither_table; for (theY = 0; theY < height; theY++) { if (--run == 0) { data = *src++; if (data & 0x80) { run = data & 0x7f; dither = true; } else { run = data >> 4; dither = false; } color = _roomPalette[data & 0x0f]; if (run == 0) { run = *src++; } } if (!dither) { *ptr_dither_table = color; } if (left <= theX && theX < right) { *dst = *ptr_dither_table++; dst += vs->pitch; } } if (left <= theX && theX < right) { dst -= _vertStripNextInc; } } // Draw mask (zplane) data theY = 0; if (table) { src = ptr + table->zoffsets[stripnr]; run = table->zrun[stripnr]; theX = left; } else { run = *src++; theX = 0; } while (theX < right) { const byte runFlag = run & 0x80; if (runFlag) { run &= 0x7f; data = *src++; } do { if (!runFlag) data = *src++; if (left <= theX) { *mask_ptr = data; mask_ptr += _numStrips; } theY++; if (theY >= height) { if (left <= theX) { mask_ptr -= _numStrips * height - 1; } theY = 0; theX += 8; if (theX >= right) break; } } while (--run); run = *src++; } } int Gdi::getZPlanes(const byte *ptr, const byte *zplane_list[9], bool bmapImage) const { int numzbuf; int i; if ((_vm->_game.features & GF_SMALL_HEADER) || _vm->_game.version == 8) zplane_list[0] = ptr; else if (bmapImage) zplane_list[0] = _vm->findResource(MKTAG('B','M','A','P'), ptr); else zplane_list[0] = _vm->findResource(MKTAG('S','M','A','P'), ptr); if (_zbufferDisabled) numzbuf = 0; else if (_numZBuffer <= 1 || (_vm->_game.version <= 2)) numzbuf = _numZBuffer; else { numzbuf = _numZBuffer; assert(numzbuf <= 9); if (_vm->_game.id == GID_LOOM && _vm->_game.platform == Common::kPlatformPCEngine) { zplane_list[1] = 0; } else if (_vm->_game.features & GF_SMALL_HEADER) { if (_vm->_game.features & GF_16COLOR) zplane_list[1] = ptr + READ_LE_UINT16(ptr); else { zplane_list[1] = ptr + READ_LE_UINT32(ptr); if (_vm->_game.features & GF_OLD256) { if (0 == READ_LE_UINT32(zplane_list[1])) zplane_list[1] = 0; } } for (i = 2; i < numzbuf; i++) { zplane_list[i] = zplane_list[i-1] + READ_LE_UINT16(zplane_list[i-1]); } } else if (_vm->_game.version == 8) { // Find the OFFS chunk of the ZPLN chunk const byte *zplnOffsChunkStart = ptr + 24 + READ_BE_UINT32(ptr + 12); // Each ZPLN contains a WRAP chunk, which has (as always) an OFFS subchunk pointing // at ZSTR chunks. These once more contain a WRAP chunk which contains nothing but // an OFFS chunk. The content of this OFFS chunk contains the offsets to the // Z-planes. // We do not directly make use of this, but rather hard code offsets (like we do // for all other Scumm-versions, too). Clearly this is a bit hackish, but works // well enough, and there is no reason to assume that there are any cases where it // might fail. Still, doing this properly would have the advantage of catching // invalid/damaged data files, and allow us to exit gracefully instead of segfaulting. for (i = 1; i < numzbuf; i++) { zplane_list[i] = zplnOffsChunkStart + READ_LE_UINT32(zplnOffsChunkStart + 4 + i*4) + 16; } } else { const uint32 zplane_tags[] = { MKTAG('Z','P','0','0'), MKTAG('Z','P','0','1'), MKTAG('Z','P','0','2'), MKTAG('Z','P','0','3'), MKTAG('Z','P','0','4') }; for (i = 1; i < numzbuf; i++) { zplane_list[i] = _vm->findResource(zplane_tags[i], ptr); } } } return numzbuf; } /** * Draw a bitmap onto a virtual screen. This is main drawing method for room backgrounds * and objects, used throughout all SCUMM versions. */ void Gdi::drawBitmap(const byte *ptr, VirtScreen *vs, int x, const int y, const int width, const int height, int stripnr, int numstrip, byte flag) { assert(ptr); assert(height > 0); byte *dstPtr; const byte *smap_ptr; const byte *zplane_list[9]; int numzbuf; int sx; bool transpStrip = false; // Check whether lights are turned on or not const bool lightsOn = _vm->isLightOn(); if ((_vm->_game.features & GF_SMALL_HEADER) || _vm->_game.version == 8) { smap_ptr = ptr; } else { smap_ptr = _vm->findResource(MKTAG('S','M','A','P'), ptr); assert(smap_ptr); } numzbuf = getZPlanes(ptr, zplane_list, false); if (y + height > vs->h) { warning("Gdi::drawBitmap, strip drawn to %d below window bottom %d", y + height, vs->h); } #ifndef <API key> if (_vm->_townsPaletteFlags & 2) { int cx = (x - _vm->_screenStartStrip) << 3; _vm->_textSurface.fillRect(Common::Rect(cx * _vm-><API key>, y * _vm-><API key>, (cx + width - 1) * _vm-><API key>, (y + height - 1) * _vm-><API key>), 0); } #endif _vertStripNextInc = height * vs->pitch - 1 * vs->format.bytesPerPixel; _objectMode = (flag & dbObjectMode) == dbObjectMode; prepareDrawBitmap(ptr, vs, x, y, width, height, stripnr, numstrip); sx = x - vs->xstart / 8; if (sx < 0) { numstrip -= -sx; x += -sx; stripnr += -sx; sx = 0; } // Compute the number of strips we have to iterate over. // TODO/FIXME: The computation of its initial value looks very fishy. // It was added as a kind of hack to fix some corner cases, but it compares // the room width to the virtual screen width; but the former should always // be bigger than the latter (except for MM NES, maybe)... strange int limit = MAX(_vm->_roomWidth, (int) vs->w) / 8 - x; if (limit > numstrip) limit = numstrip; if (limit > _numStrips - sx) limit = _numStrips - sx; for (int k = 0; k < limit; ++k, ++stripnr, ++sx, ++x) { if (y < vs->tdirty[sx]) vs->tdirty[sx] = y; if (y + height > vs->bdirty[sx]) vs->bdirty[sx] = y + height; // In the case of a double buffered virtual screen, we draw to // the backbuffer, otherwise to the primary surface memory. if (vs->hasTwoBuffers) dstPtr = vs->backBuf + y * vs->pitch + (x * 8 * vs->format.bytesPerPixel); else dstPtr = (byte *)vs->getBasePtr(x * 8, y); transpStrip = drawStrip(dstPtr, vs, x, y, width, height, stripnr, smap_ptr); // COMI and HE games only uses flag value if (_vm->_game.version == 8 || _vm->_game.heversion >= 60) transpStrip = true; if (vs->hasTwoBuffers) { byte *frontBuf = (byte *)vs->getBasePtr(x * 8, y); if (lightsOn) copy8Col(frontBuf, vs->pitch, dstPtr, height, vs->format.bytesPerPixel); else clear8Col(frontBuf, vs->pitch, height, vs->format.bytesPerPixel); } decodeMask(x, y, width, height, stripnr, numzbuf, zplane_list, transpStrip, flag); #if 0 // HACK: blit mask(s) onto normal screen. Useful to debug masking for (int i = 0; i < numzbuf; i++) { byte *dst1, *dst2; dst1 = dst2 = (byte *)vs->pixels + y * vs->pitch + x * 8; if (vs->hasTwoBuffers) dst2 = vs->backBuf + y * vs->pitch + x * 8; byte *mask_ptr = getMaskBuffer(x, y, i); for (int h = 0; h < height; h++) { int maskbits = *mask_ptr; for (int j = 0; j < 8; j++) { if (maskbits & 0x80) dst1[j] = dst2[j] = 12 + i; maskbits <<= 1; } dst1 += vs->pitch; dst2 += vs->pitch; mask_ptr += _numStrips; } } #endif } } bool Gdi::drawStrip(byte *dstPtr, VirtScreen *vs, int x, int y, const int width, const int height, int stripnr, const byte *smap_ptr) { // Do some input verification and make sure the strip/strip offset // are actually valid. Normally, this should never be a problem, // but if e.g. a savegame gets corrupted, we can easily get into // trouble here. See also bug #795214. int offset = -1, smapLen; if (_vm->_game.features & GF_16COLOR) { smapLen = READ_LE_UINT16(smap_ptr); if (stripnr * 2 + 2 < smapLen) { offset = READ_LE_UINT16(smap_ptr + stripnr * 2 + 2); } } else if (_vm->_game.features & GF_SMALL_HEADER) { smapLen = READ_LE_UINT32(smap_ptr); if (stripnr * 4 + 4 < smapLen) offset = READ_LE_UINT32(smap_ptr + stripnr * 4 + 4); } else if (_vm->_game.version == 8) { smapLen = READ_BE_UINT32(smap_ptr + 4); // Skip to the BSTR->WRAP->OFFS chunk smap_ptr += 24; if (stripnr * 4 + 8 < smapLen) offset = READ_LE_UINT32(smap_ptr + stripnr * 4 + 8); } else { smapLen = READ_BE_UINT32(smap_ptr + 4); if (stripnr * 4 + 8 < smapLen) offset = READ_LE_UINT32(smap_ptr + stripnr * 4 + 8); } assertRange(0, offset, smapLen-1, "screen strip"); // Indy4 Amiga always uses the room or verb palette map to match colors to // the currently setup palette, thus we need to select it over here too. // Done like the original interpreter. if (_vm->_game.platform == Common::kPlatformAmiga && _vm->_game.id == GID_INDY4) { if (vs->number == kVerbVirtScreen) _roomPalette = _vm->_verbPalette; else _roomPalette = _vm->_roomPalette; } return decompressBitmap(dstPtr, vs->pitch, smap_ptr + offset, height); } bool GdiNES::drawStrip(byte *dstPtr, VirtScreen *vs, int x, int y, const int width, const int height, int stripnr, const byte *smap_ptr) { byte *mask_ptr = getMaskBuffer(x, y, 1); drawStripNES(dstPtr, mask_ptr, vs->pitch, stripnr, y, height); return false; } bool GdiPCEngine::drawStrip(byte *dstPtr, VirtScreen *vs, int x, int y, const int width, const int height, int stripnr, const byte *smap_ptr) { byte *mask_ptr = getMaskBuffer(x, y, 1); drawStripPCEngine(dstPtr, mask_ptr, vs->pitch, stripnr, y, height); return false; } bool GdiV1::drawStrip(byte *dstPtr, VirtScreen *vs, int x, int y, const int width, const int height, int stripnr, const byte *smap_ptr) { if (_objectMode) drawStripV1Object(dstPtr, vs->pitch, stripnr, width, height); else <API key>(dstPtr, vs->pitch, stripnr, height); return false; } bool GdiV2::drawStrip(byte *dstPtr, VirtScreen *vs, int x, int y, const int width, const int height, int stripnr, const byte *smap_ptr) { // Do nothing here for V2 games - drawing was already handled. return false; } void Gdi::decodeMask(int x, int y, const int width, const int height, int stripnr, int numzbuf, const byte *zplane_list[9], bool transpStrip, byte flag) { int i; byte *mask_ptr; const byte *z_plane_ptr; if (flag & dbDrawMaskOnAll) { // Sam & Max uses dbDrawMaskOnAll for things like the inventory // box and the speech icons. While these objects only have one // mask, it should be applied to all the Z-planes in the room, // i.e. they should mask every actor. // This flag used to be called dbDrawMaskOnBoth, and all it // would do was to mask Z-plane 0. (Z-plane 1 would also be // masked, because what is now the else-clause used to be run // always.) While this seems to be the only way there is to // mask Z-plane 0, this wasn't good enough since actors in // Z-planes >= 2 would not be masked. // The flag is also used by The Dig and Full Throttle, but I // don't know what for. At the time of writing, these games // are still too unstable for me to investigate. if (_vm->_game.version == 8) z_plane_ptr = zplane_list[1] + READ_LE_UINT32(zplane_list[1] + stripnr * 4 + 8); else z_plane_ptr = zplane_list[1] + READ_LE_UINT16(zplane_list[1] + stripnr * 2 + 8); for (i = 0; i < numzbuf; i++) { mask_ptr = getMaskBuffer(x, y, i); if (transpStrip && (flag & dbAllowMaskOr)) decompressMaskImgOr(mask_ptr, z_plane_ptr, height); else decompressMaskImg(mask_ptr, z_plane_ptr, height); } } else { for (i = 1; i < numzbuf; i++) { uint32 offs; if (!zplane_list[i]) continue; if (_vm->_game.features & GF_OLD_BUNDLE) offs = READ_LE_UINT16(zplane_list[i] + stripnr * 2); else if (_vm->_game.features & GF_OLD256) offs = READ_LE_UINT16(zplane_list[i] + stripnr * 2 + 4); else if (_vm->_game.features & GF_SMALL_HEADER) offs = READ_LE_UINT16(zplane_list[i] + stripnr * 2 + 2); else if (_vm->_game.version == 8) offs = READ_LE_UINT32(zplane_list[i] + stripnr * 4 + 8); else offs = READ_LE_UINT16(zplane_list[i] + stripnr * 2 + 8); mask_ptr = getMaskBuffer(x, y, i); if (offs) { z_plane_ptr = zplane_list[i] + offs; if (transpStrip && (flag & dbAllowMaskOr)) { decompressMaskImgOr(mask_ptr, z_plane_ptr, height); } else { decompressMaskImg(mask_ptr, z_plane_ptr, height); } } else { if (!(transpStrip && (flag & dbAllowMaskOr))) for (int h = 0; h < height; h++) mask_ptr[h * _numStrips] = 0; } } } } void GdiHE::decodeMask(int x, int y, const int width, const int height, int stripnr, int numzbuf, const byte *zplane_list[9], bool transpStrip, byte flag) { int i; byte *mask_ptr; const byte *z_plane_ptr; for (i = 1; i < numzbuf; i++) { uint32 offs; if (!zplane_list[i]) continue; offs = READ_LE_UINT16(zplane_list[i] + stripnr * 2 + 8); mask_ptr = getMaskBuffer(x, y, i); if (offs) { z_plane_ptr = zplane_list[i] + offs; if (_tmskPtr) { const byte *tmsk = _tmskPtr + READ_LE_UINT16(_tmskPtr + stripnr * 2 + 8); decompressTMSK(mask_ptr, tmsk, z_plane_ptr, height); } else if (transpStrip && (flag & dbAllowMaskOr)) { decompressMaskImgOr(mask_ptr, z_plane_ptr, height); } else { decompressMaskImg(mask_ptr, z_plane_ptr, height); } } else { if (!(transpStrip && (flag & dbAllowMaskOr))) for (int h = 0; h < height; h++) mask_ptr[h * _numStrips] = 0; } } } void GdiNES::decodeMask(int x, int y, const int width, const int height, int stripnr, int numzbuf, const byte *zplane_list[9], bool transpStrip, byte flag) { byte *mask_ptr = getMaskBuffer(x, y, 1); drawStripNESMask(mask_ptr, stripnr, y, height); } void GdiPCEngine::decodeMask(int x, int y, const int width, const int height, int stripnr, int numzbuf, const byte *zplane_list[9], bool transpStrip, byte flag) { byte *mask_ptr = getMaskBuffer(x, y, 1); <API key>(mask_ptr, stripnr, y, height); } void GdiV1::decodeMask(int x, int y, const int width, const int height, int stripnr, int numzbuf, const byte *zplane_list[9], bool transpStrip, byte flag) { byte *mask_ptr = getMaskBuffer(x, y, 1); drawStripV1Mask(mask_ptr, stripnr, width, height); } void GdiV2::decodeMask(int x, int y, const int width, const int height, int stripnr, int numzbuf, const byte *zplane_list[9], bool transpStrip, byte flag) { // Do nothing here for V2 games - zplane was already handled. } #ifdef ENABLE_HE /** * Draw a bitmap onto a virtual screen. This is main drawing method for room backgrounds * used throughout HE71+ versions. * * @note This function essentially is a stripped down & special cased version of * the generic Gdi::drawBitmap() method. */ void Gdi::drawBMAPBg(const byte *ptr, VirtScreen *vs) { const byte *z_plane_ptr; byte *mask_ptr; const byte *zplane_list[9]; const byte *bmap_ptr = _vm->findResourceData(MKTAG('B','M','A','P'), ptr); assert(bmap_ptr); byte code = *bmap_ptr++; byte *dst = vs->getBackPixels(0, 0); // The following few lines more or less duplicate decompressBitmap(), only // for an area spanning multiple strips. In particular, the codecs 13 & 14 // in decompressBitmap call drawStripHE() _decomp_shr = code % 10; _decomp_mask = 0xFF >> (8 - _decomp_shr); switch (code) { case 134: case 135: case 136: case 137: case 138: drawStripHE(dst, vs->pitch, bmap_ptr, vs->w, vs->h, false); break; case 144: case 145: case 146: case 147: case 148: drawStripHE(dst, vs->pitch, bmap_ptr, vs->w, vs->h, true); break; case 150: fill(dst, vs->pitch, *bmap_ptr, vs->w, vs->h, vs->format.bytesPerPixel); break; default: // Alternative russian freddi3 uses badly formatted bitmaps debug(0, "Gdi::drawBMAPBg: default case %d", code); } ((ScummEngine_v71he *)_vm)->restoreBackgroundHE(Common::Rect(vs->w, vs->h)); int numzbuf = getZPlanes(ptr, zplane_list, true); if (numzbuf <= 1) return; uint32 offs; for (int stripnr = 0; stripnr < _numStrips; stripnr++) { for (int i = 1; i < numzbuf; i++) { if (!zplane_list[i]) continue; offs = READ_LE_UINT16(zplane_list[i] + stripnr * 2 + 8); mask_ptr = getMaskBuffer(stripnr, 0, i); if (offs) { z_plane_ptr = zplane_list[i] + offs; decompressMaskImg(mask_ptr, z_plane_ptr, vs->h); } } #if 0 // HACK: blit mask(s) onto normal screen. Useful to debug masking for (int i = 0; i < numzbuf; i++) { byte *dst1 = (byte *)vs->pixels + stripnr * 8; byte *dst2 = vs->backBuf + stripnr * 8; mask_ptr = getMaskBuffer(stripnr, 0, i); for (int h = 0; h < vs->h; h++) { int maskbits = *mask_ptr; for (int j = 0; j < 8; j++) { if (maskbits & 0x80) dst1[j] = dst2[j] = 12 + i; maskbits <<= 1; } dst1 += vs->pitch; dst2 += vs->pitch; mask_ptr += _numStrips; } } #endif } } void Gdi::drawBMAPObject(const byte *ptr, VirtScreen *vs, int obj, int x, int y, int w, int h) { const byte *bmap_ptr = _vm->findResourceData(MKTAG('B','M','A','P'), ptr); assert(bmap_ptr); byte code = *bmap_ptr++; int scrX = _vm->_screenStartStrip * 8 * _vm->_bytesPerPixel; if (code == 8 || code == 9) { Common::Rect rScreen(0, 0, vs->w, vs->h); byte *dst = (byte *)_vm->_virtscr[kMainVirtScreen].backBuf + scrX; Wiz::copyWizImage(dst, bmap_ptr, vs->pitch, kDstScreen, vs->w, vs->h, x - scrX, y, w, h, &rScreen, 0, 0, 0, _vm->_bytesPerPixel); } Common::Rect rect1(x, y, x + w, y + h); Common::Rect rect2(scrX, 0, vs->w + scrX, vs->h); if (rect1.intersects(rect2)) { rect1.clip(rect2); rect1.left -= rect2.left; rect1.right -= rect2.left; rect1.top -= rect2.top; rect1.bottom -= rect2.top; ((ScummEngine_v71he *)_vm)->restoreBackgroundHE(rect1); } } void ScummEngine_v70he::restoreBackgroundHE(Common::Rect rect, int dirtybit) { byte *src, *dst; VirtScreen *vs = &_virtscr[kMainVirtScreen]; if (rect.top > vs->h || rect.bottom < 0) return; if (rect.left > vs->w || rect.right < 0) return; rect.left = MAX(0, (int)rect.left); rect.left = MIN((int)rect.left, (int)vs->w - 1); rect.right = MAX(0, (int)rect.right); rect.right = MIN((int)rect.right, (int)vs->w); rect.top = MAX(0, (int)rect.top); rect.top = MIN((int)rect.top, (int)vs->h - 1); rect.bottom = MAX(0, (int)rect.bottom); rect.bottom = MIN((int)rect.bottom, (int)vs->h); const int rw = rect.width(); const int rh = rect.height(); if (rw == 0 || rh == 0) return; src = _virtscr[kMainVirtScreen].getBackPixels(rect.left, rect.top); dst = _virtscr[kMainVirtScreen].getPixels(rect.left, rect.top); assert(rw <= _screenWidth && rw > 0); assert(rh <= _screenHeight && rh > 0); blit(dst, _virtscr[kMainVirtScreen].pitch, src, _virtscr[kMainVirtScreen].pitch, rw, rh, vs->format.bytesPerPixel); markRectAsDirty(kMainVirtScreen, rect, dirtybit); } #endif /** * Reset the background behind an actor or blast object. */ void Gdi::resetBackground(int top, int bottom, int strip) { VirtScreen *vs = &_vm->_virtscr[kMainVirtScreen]; byte *backbuff_ptr, *bgbak_ptr; int numLinesToProcess; if (top < 0) top = 0; if (bottom > vs->h) bottom = vs->h; if (top >= bottom) return; assert(0 <= strip && strip < _numStrips); if (top < vs->tdirty[strip]) vs->tdirty[strip] = top; if (bottom > vs->bdirty[strip]) vs->bdirty[strip] = bottom; bgbak_ptr = (byte *)vs->backBuf + top * vs->pitch + (strip + vs->xstart/8) * 8 * vs->format.bytesPerPixel; backbuff_ptr = (byte *)vs->getBasePtr((strip + vs->xstart/8) * 8, top); numLinesToProcess = bottom - top; if (numLinesToProcess) { if (_vm->isLightOn()) { copy8Col(backbuff_ptr, vs->pitch, bgbak_ptr, numLinesToProcess, vs->format.bytesPerPixel); } else { clear8Col(backbuff_ptr, vs->pitch, numLinesToProcess, vs->format.bytesPerPixel); } } } bool Gdi::decompressBitmap(byte *dst, int dstPitch, const byte *src, int numLinesToProcess) { assert(numLinesToProcess); if (_vm->_game.features & GF_16COLOR) { drawStripEGA(dst, dstPitch, src, numLinesToProcess); return false; } if ((_vm->_game.platform == Common::kPlatformAmiga) && (_vm->_game.version >= 4)) _paletteMod = 16; else _paletteMod = 0; byte code = *src++; bool transpStrip = false; _decomp_shr = code % 10; _decomp_mask = 0xFF >> (8 - _decomp_shr); switch (code) { case 1: drawStripRaw(dst, dstPitch, src, numLinesToProcess, false); break; case 2: unkDecode8(dst, dstPitch, src, numLinesToProcess); /* Ender - Zak256/Indy256 */ break; case 3: unkDecode9(dst, dstPitch, src, numLinesToProcess); /* Ender - Zak256/Indy256 */ break; case 4: unkDecode10(dst, dstPitch, src, numLinesToProcess); /* Ender - Zak256/Indy256 */ break; case 7: unkDecode11(dst, dstPitch, src, numLinesToProcess); /* Ender - Zak256/Indy256 */ break; case 8: // Used in 3DO versions of HE games transpStrip = true; drawStrip3DO(dst, dstPitch, src, numLinesToProcess, true); break; case 9: drawStrip3DO(dst, dstPitch, src, numLinesToProcess, false); break; case 10: // Used in Amiga version of Monkey Island 1 drawStripEGA(dst, dstPitch, src, numLinesToProcess); break; case 14: case 15: case 16: case 17: case 18: drawStripBasicV(dst, dstPitch, src, numLinesToProcess, false); break; case 24: case 25: case 26: case 27: case 28: drawStripBasicH(dst, dstPitch, src, numLinesToProcess, false); break; case 34: case 35: case 36: case 37: case 38: transpStrip = true; drawStripBasicV(dst, dstPitch, src, numLinesToProcess, true); break; case 44: case 45: case 46: case 47: case 48: transpStrip = true; drawStripBasicH(dst, dstPitch, src, numLinesToProcess, true); break; case 64: case 65: case 66: case 67: case 68: case 104: case 105: case 106: case 107: case 108: drawStripComplex(dst, dstPitch, src, numLinesToProcess, false); break; case 84: case 85: case 86: case 87: case 88: case 124: case 125: case 126: case 127: case 128: transpStrip = true; drawStripComplex(dst, dstPitch, src, numLinesToProcess, true); break; case 134: case 135: case 136: case 137: case 138: drawStripHE(dst, dstPitch, src, 8, numLinesToProcess, false); break; case 143: // Triggered by Russian water case 144: case 145: case 146: case 147: case 148: transpStrip = true; drawStripHE(dst, dstPitch, src, 8, numLinesToProcess, true); break; case 149: drawStripRaw(dst, dstPitch, src, numLinesToProcess, true); break; default: error("Gdi::decompressBitmap: default case %d", code); } return transpStrip; } void Gdi::decompressMaskImg(byte *dst, const byte *src, int height) const { byte b, c; while (height) { b = *src++; if (b & 0x80) { b &= 0x7F; c = *src++; do { *dst = c; dst += _numStrips; --height; } while (--b && height); } else { do { *dst = *src++; dst += _numStrips; --height; } while (--b && height); } } } void GdiHE::decompressTMSK(byte *dst, const byte *tmsk, const byte *src, int height) const { byte srcbits = 0; byte srcFlag = 0; byte maskFlag = 0; byte srcCount = 0; byte maskCount = 0; byte maskbits = 0; while (height) { if (srcCount == 0) { srcCount = *src++; srcFlag = srcCount & 0x80; if (srcFlag) { srcCount &= 0x7F; srcbits = *src++; } } if (srcFlag == 0) { srcbits = *src++; } srcCount if (maskCount == 0) { maskCount = *tmsk++; maskFlag = maskCount & 0x80; if (maskFlag) { maskCount &= 0x7F; maskbits = *tmsk++; } } if (maskFlag == 0) { maskbits = *tmsk++; } maskCount *dst |= srcbits; *dst &= ~maskbits; dst += _numStrips; height } } void Gdi::decompressMaskImgOr(byte *dst, const byte *src, int height) const { byte b, c; while (height) { b = *src++; if (b & 0x80) { b &= 0x7F; c = *src++; do { *dst |= c; dst += _numStrips; --height; } while (--b && height); } else { do { *dst |= *src++; dst += _numStrips; --height; } while (--b && height); } } } static void decodeNESTileData(const byte *src, byte *dest) { int len = READ_LE_UINT16(src); src += 2; const byte *end = src + len; src++; // skip number-of-tiles byte, assume it is correct while (src < end) { byte data = *src++; for (int j = 0; j < (data & 0x7F); j++) *dest++ = (data & 0x80) ? (*src++) : (*src); if (!(data & 0x80)) src++; } } void ScummEngine::decodeNESBaseTiles() { byte *basetiles = getResourceAddress(rtCostume, 37); _NESBaseTiles = basetiles[2]; decodeNESTileData(basetiles, _NESPatTable[1]); } static const int v1MMNEScostTables[2][6] = { /* desc lens offs data gfx pal */ { 25, 27, 29, 31, 33, 35}, { 26, 28, 30, 32, 34, 36} }; void ScummEngine::NES_loadCostumeSet(int n) { int i; _NESCostumeSet = n; _NEScostdesc = getResourceAddress(rtCostume, v1MMNEScostTables[n][0]) + 2; _NEScostlens = getResourceAddress(rtCostume, v1MMNEScostTables[n][1]) + 2; _NEScostoffs = getResourceAddress(rtCostume, v1MMNEScostTables[n][2]) + 2; _NEScostdata = getResourceAddress(rtCostume, v1MMNEScostTables[n][3]) + 2; decodeNESTileData(getResourceAddress(rtCostume, v1MMNEScostTables[n][4]), _NESPatTable[0]); byte *palette = getResourceAddress(rtCostume, v1MMNEScostTables[n][5]) + 2; for (i = 0; i < 16; i++) { byte c = *palette++; if (c == 0x1D) // HACK - switch around colors 0x00 and 0x1D c = 0; // so we don't need a zillion extra checks else if (c == 0)// for determining the proper background color c = 0x1D; _NESPalette[1][i] = c; } } void GdiNES::decodeNESGfx(const byte *room) { const byte *gdata = room + READ_LE_UINT16(room + 0x0A); int tileset = *gdata++; int width = READ_LE_UINT16(room + 0x04); // int height = READ_LE_UINT16(room + 0x06); int i, j, n; // We have narrow room. so expand it if (width < 32) { _vm->_NESStartStrip = (32 - width) >> 1; } else { _vm->_NESStartStrip = 0; } decodeNESTileData(_vm->getResourceAddress(rtCostume, 37 + tileset), _vm->_NESPatTable[1] + _vm->_NESBaseTiles * 16); for (i = 0; i < 16; i++) { byte c = *gdata++; if (c == 0x0D) c = 0x1D; if (c == 0x1D) // HACK - switch around colors 0x00 and 0x1D c = 0; // so we don't need a zillion extra checks else if (c == 0) // for determining the proper background color c = 0x1D; _vm->_NESPalette[0][i] = c; } for (i = 0; i < 16; i++) { _NES.nametable[i][0] = _NES.nametable[i][1] = 0; n = 0; while (n < width) { byte data = *gdata++; for (j = 0; j < (data & 0x7F); j++) _NES.nametable[i][2 + n++] = (data & 0x80) ? (*gdata++) : (*gdata); if (!(data & 0x80)) gdata++; } _NES.nametable[i][width+2] = _NES.nametable[i][width+3] = 0; } memcpy(_NES.nametableObj,_NES.nametable, 16*64); const byte *adata = room + READ_LE_UINT16(room + 0x0C); for (n = 0; n < 64;) { byte data = *adata++; for (j = 0; j < (data & 0x7F); j++) _NES.attributes[n++] = (data & 0x80) ? (*adata++) : (*adata); if (!(n & 7) && (width == 0x1C)) n += 8; if (!(data & 0x80)) adata++; } memcpy(_NES.attributesObj, _NES.attributes, 64); const byte *mdata = room + READ_LE_UINT16(room + 0x0E); int mask = *mdata++; if (mask == 0) { _NES.hasmask = false; return; } _NES.hasmask = true; if (mask != 1) debug(0,"NES room %i has irregular mask count %i",_vm->_currentRoom,mask); int mwidth = *mdata++; for (i = 0; i < 16; i++) { n = 0; while (n < mwidth) { byte data = *mdata++; for (j = 0; j < (data & 0x7F); j++) _NES.masktable[i][n++] = (data & 0x80) ? (*mdata++) : (*mdata); if (!(data & 0x80)) mdata++; } } memcpy(_NES.masktableObj, _NES.masktable, 16*8); } void GdiNES::decodeNESObject(const byte *ptr, int xpos, int ypos, int width, int height) { int x, y; _NES.objX = xpos; // decode tile update data width /= 8; ypos /= 8; height /= 8; for (y = ypos; y < ypos + height; y++) { x = xpos; while (x < xpos + width) { byte len = *ptr++; for (int i = 0; i < (len & 0x7F); i++) _NES.nametableObj[y][2 + x++] = (len & 0x80) ? (*ptr++) : (*ptr); if (!(len & 0x80)) ptr++; } } int ax, ay; // decode attribute update data y = height / 2; ay = ypos; while (y) { ax = xpos + 2; x = 0; int adata = 0; while (x < (width >> 1)) { if (!(x & 3)) adata = *ptr++; byte *dest = &_NES.attributesObj[((ay << 2) & 0x30) | ((ax >> 2) & 0xF)]; int aand = 3; int aor = adata & 3; if (ay & 0x02) { aand <<= 4; aor <<= 4; } if (ax & 0x02) { aand <<= 2; aor <<= 2; } *dest = ((~aand) & *dest) | aor; adata >>= 2; ax += 2; x++; } ay += 2; y } // decode mask update data if (!_NES.hasmask) return; int mx, mwidth; int lmask, rmask; mx = *ptr++; mwidth = *ptr++; lmask = *ptr++; rmask = *ptr++; for (y = 0; y < height; ++y) { byte *dest = &_NES.masktableObj[y + ypos][mx]; *dest = (*dest & lmask) | *ptr++; dest++; for (x = 1; x < mwidth; x++) { if (x + 1 == mwidth) *dest = (*dest & rmask) | *ptr++; else *dest = *ptr++; dest++; } } } void GdiNES::drawStripNES(byte *dst, byte *mask, int dstPitch, int stripnr, int top, int height) { top /= 8; height /= 8; int x = stripnr + 2; // NES version has a 2 tile gap on each edge if (_objectMode) x += _NES.objX; // for objects, need to start at the left edge of the object, not the screen if (x > 63) { debug(0,"NES tried to render invalid strip %i",stripnr); return; } for (int y = top; y < top + height; y++) { int palette = ((_objectMode ? _NES.attributesObj : _NES.attributes)[((y << 2) & 0x30) | ((x >> 2) & 0xF)] >> (((y & 2) << 1) | (x & 2))) & 0x3; int tile = (_objectMode ? _NES.nametableObj : _NES.nametable)[y][x]; for (int i = 0; i < 8; i++) { byte c0 = _vm->_NESPatTable[1][tile * 16 + i]; byte c1 = _vm->_NESPatTable[1][tile * 16 + i + 8]; for (int j = 0; j < 8; j++) dst[j] = _vm->_NESPalette[0][((c0 >> (7 - j)) & 1) | (((c1 >> (7 - j)) & 1) << 1) | (palette << 2)]; dst += dstPitch; *mask = c0 | c1; mask += _numStrips; } } } void GdiNES::drawStripNESMask(byte *dst, int stripnr, int top, int height) const { top /= 8; height /= 8; int x = stripnr; // masks, unlike room graphics, should NOT be adjusted if (_objectMode) x += _NES.objX; // for objects, need to start at the left edge of the object, not the screen if (x > 63) { debug(0,"NES tried to mask invalid strip %i",stripnr); return; } for (int y = top; y < top + height; y++) { byte c; if (_NES.hasmask) c = (((_objectMode ? _NES.masktableObj : _NES.masktable)[y][x >> 3] >> (x & 7)) & 1) ? 0xFF : 0x00; else c = 0; for (int i = 0; i < 8; i++) { *dst &= c; dst += _numStrips; } } } void readOffsetTable(const byte *ptr, uint16 **table, int *count) { int pos = 0; *count = READ_LE_UINT16(ptr) / 2 + 1; *table = (uint16 *)malloc(*count * sizeof(uint16)); for (int i = 0; i < *count; i++) { (*table)[i] = READ_LE_UINT16(ptr + pos) + pos + 2; pos += 2; } } void decodeTileColor(byte cmd, byte *colors, int *rowIndex, int numRows) { colors[(*rowIndex)++] = ((cmd) >> 4) & 0xF; if (*rowIndex < numRows) colors[(*rowIndex)++] = (cmd) & 0xF; } void GdiPCEngine::decodeStrip(const byte *ptr, uint16 *tiles, byte *colors, uint16 *masks, int numRows, bool isObject) { int loopCnt; uint16 lastTileData; /* * read tiles indices */ int rowIndex = 0; if (isObject) { loopCnt = numRows; } else { tiles[rowIndex++] = 0; tiles[numRows - 1] = 0; loopCnt = numRows - 1; } while (true) { uint16 cmd = READ_LE_UINT16(ptr); ptr += 2; if (cmd & 0x8000) { tiles[rowIndex - 1] = cmd & 0x0FFF; } else if (cmd & 0x4000) { tiles[numRows - 1] = cmd & 0x0FFF; } else { tiles[rowIndex++] = cmd; lastTileData = cmd; break; } } while (rowIndex < loopCnt) { byte cmd = *ptr++; int cnt = cmd & 0x1F; if (cmd & 0x80) { for (int i = 0; i < cnt; ++i) { tiles[rowIndex++] = lastTileData; } } else if (cmd & 0x40) { for (int i = 0; i < cnt; ++i) { ++lastTileData; tiles[rowIndex++] = lastTileData; } } else { for (int i = 0; i < cnt; ++i) { lastTileData = READ_LE_UINT16(ptr); ptr += 2; tiles[rowIndex++] = lastTileData; } } } /* * read palette data */ rowIndex = 0; byte cmd = *ptr++; if (cmd == 0xFE) { while (rowIndex < numRows) { decodeTileColor(*ptr++, colors, &rowIndex, numRows); } } else { byte lastCmd = cmd; decodeTileColor(cmd, colors, &rowIndex, numRows); while (rowIndex < numRows) { cmd = *ptr++; int cnt = cmd & 0x1F; if (cmd & 0x80) { for (int j = 0; j < cnt; ++j) { decodeTileColor(lastCmd, colors, &rowIndex, numRows); } } else { for (int j = 0; j < cnt; ++j) { cmd = *ptr++; decodeTileColor(cmd, colors, &rowIndex, numRows); } lastCmd = cmd; } } } /* * read mask indices */ if (_distaff || _PCE.maskIDSize == 0 || numRows > 18) { return; } rowIndex = 0; while (rowIndex < numRows) { cmd = *ptr++; int cnt = cmd & 0x1F; if (cmd & 0x80) { uint16 value; if (cmd & 0x60) { value = (cmd & 0x40) ? 0 : 0xFF; } else if (_PCE.maskIDSize == 1) { value = *ptr++; } else { value = READ_LE_UINT16(ptr); ptr += 2; } for (int i = 0; i < cnt; ++i) { masks[rowIndex++] = value; } } else { for (int i = 0; i < cnt; ++i) { if (_PCE.maskIDSize == 1) { masks[rowIndex++] = *ptr++; } else { masks[rowIndex++] = READ_LE_UINT16(ptr); ptr += 2; } } } } } void GdiPCEngine::decodePCEngineGfx(const byte *room) { uint16* stripOffsets; <API key>(_vm->findResourceData(MKTAG('T','I','L','E'), room)); <API key>(_vm->findResourceData(MKTAG('Z','P','0','0'), room)); const byte* smap_ptr = _vm->findResourceData(MKTAG('I','M','0','0'), room); smap_ptr++; // roomID int numStrips = *smap_ptr++; int numRows = *smap_ptr++; _PCE.maskIDSize = *smap_ptr++; smap_ptr++; // unknown memset(_PCE.nametable, 0, sizeof(_PCE.nametable)); memset(_PCE.colortable, 0, sizeof(_PCE.colortable)); readOffsetTable(smap_ptr, &stripOffsets, &numStrips); for (int i = 0; i < numStrips; ++i) { const byte *tilePtr = smap_ptr + stripOffsets[i]; decodeStrip(tilePtr, &_PCE.nametable[i * numRows], &_PCE.colortable[i * numRows], &_PCE.masktable[i * numRows], numRows, false); } free(stripOffsets); } void GdiPCEngine::<API key>(const byte *ptr, int xpos, int ypos, int width, int height) { uint16 *stripOffsets; int numStrips; int numRows = height / 8; memset(_PCE.nametableObj, 0, sizeof(_PCE.nametableObj)); memset(_PCE.colortableObj, 0, sizeof(_PCE.colortableObj)); readOffsetTable(ptr, &stripOffsets, &numStrips); for (int i = 0; i < numStrips; ++i) { const byte *tilePtr = ptr + stripOffsets[i]; decodeStrip(tilePtr, &_PCE.nametableObj[i * numRows], &_PCE.colortableObj[i * numRows], &_PCE.masktableObj[i * numRows], numRows, true); } free(stripOffsets); } void GdiPCEngine::setTileData(byte *tile, int index, byte byte0, byte byte1) { int row = index % 8; int plane = (index / 8) * 2; int plane02Bit, plane13Bit; for (int col = 0; col < 8; ++col) { plane02Bit = (byte0 >> (7-col)) & 0x1; // plane=0: bit0, plane=2: bit2 plane13Bit = (byte1 >> (7-col)) & 0x1; // plane=0: bit1, plane=2: bit3 tile[row * 8 + col] |= plane02Bit << (plane + 0); tile[row * 8 + col] |= plane13Bit << (plane + 1); } } void GdiPCEngine::<API key>(const byte *ptr) { const byte *tilePtr; byte* tile; uint16* tileOffsets; byte byte0, byte1; readOffsetTable(ptr, &tileOffsets, &_PCE.numTiles); if (_distaff) { free(_PCE.staffTiles); _PCE.staffTiles = (byte *)calloc(_PCE.numTiles * 8 * 8, sizeof(byte)); } else { free(_PCE.roomTiles); _PCE.roomTiles = (byte *)calloc(_PCE.numTiles * 8 * 8, sizeof(byte)); } for (int i = 0; i < _PCE.numTiles; ++i) { tile = (_distaff) ? &_PCE.staffTiles[i * 64] : &_PCE.roomTiles[i * 64]; tilePtr = ptr + tileOffsets[i]; int index = 0; while (index < 16) { byte cmd = *tilePtr++; byte cnt = (cmd & 0x0F) + 1; if (cmd & 0x80) { byte0 = (cmd & 0x10) ? 0 : *tilePtr++; byte1 = (cmd & 0x40) ? 0 : *tilePtr++; while (cnt setTileData(tile, index++, byte0, byte1); } } else { while (cnt byte0 = (cmd & 0x10) ? 0 : *tilePtr++; byte1 = (cmd & 0x40) ? 0 : *tilePtr++; setTileData(tile, index++, byte0, byte1); } } } } free(tileOffsets); } void GdiPCEngine::<API key>(const byte *ptr) { const byte *maskPtr; byte* mask; uint16* maskOffsets; if (!ptr) { _PCE.numMasks = 0; return; } readOffsetTable(ptr, &maskOffsets, &_PCE.numMasks); free(_PCE.masks); _PCE.masks = (byte *)malloc(_PCE.numMasks * 8 * sizeof(byte)); for (int i = 0; i < _PCE.numMasks; ++i) { mask = &_PCE.masks[i * 8]; maskPtr = ptr + maskOffsets[i]; int index = 0; while (index < 8) { byte cmd = *maskPtr++; int cnt = cmd & 0x1F; if (cmd & 0x80) { byte value; if (cmd & 0x60) value = (cmd & 0x40) ? 0x00 : 0xFF; else value = *maskPtr++; for (int j = 0; j < cnt; ++j) mask[index++] = ~value; } else { for (int j = 0; j < cnt; ++j) mask[index++] = ~*maskPtr++; } } } free(maskOffsets); } void GdiPCEngine::drawStripPCEngine(byte *dst, byte *mask, int dstPitch, int stripnr, int top, int height) { uint16 tileIdx; byte *tile; int paletteIdx, paletteOffset, paletteEntry; height /= 8; for (int y = 0; y < height; y++) { tileIdx = (_objectMode ? _PCE.nametableObj : _PCE.nametable)[stripnr * height + y]; tile = (_distaff) ? &_PCE.staffTiles[tileIdx * 64] : &_PCE.roomTiles[tileIdx * 64]; paletteIdx = (_objectMode ? _PCE.colortableObj : _PCE.colortable)[stripnr * height + y]; paletteOffset = paletteIdx * 16; for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { paletteEntry = tile[row * 8 + col]; WRITE_UINT16(dst + col * 2, _vm->_16BitPalette[paletteOffset + paletteEntry]); } dst += dstPitch; } } } void GdiPCEngine::<API key>(byte *dst, int stripnr, int top, int height) const { uint16 maskIdx; height /= 8; for (int y = 0; y < height; y++) { maskIdx = (_objectMode ? _PCE.masktableObj : _PCE.masktable)[stripnr * height + y]; for (int row = 0; row < 8; row++) { if (_PCE.numMasks > 0) *dst = _PCE.masks[maskIdx * 8 + row]; else *dst = 0; dst += _numStrips; } } } void GdiV1::<API key>(byte *dst, int dstPitch, int stripnr, int height) { int charIdx; height /= 8; for (int y = 0; y < height; y++) { _V1.colors[3] = (_V1.colorMap[y + stripnr * height] & 7); // Check for room color change in V1 zak if (_roomPalette[0] == 255) { _V1.colors[2] = _roomPalette[2]; _V1.colors[1] = _roomPalette[1]; } charIdx = _V1.picMap[y + stripnr * height] * 8; for (int i = 0; i < 8; i++) { byte c = _V1.charMap[charIdx + i]; dst[0] = dst[1] = _V1.colors[(c >> 6) & 3]; dst[2] = dst[3] = _V1.colors[(c >> 4) & 3]; dst[4] = dst[5] = _V1.colors[(c >> 2) & 3]; dst[6] = dst[7] = _V1.colors[(c >> 0) & 3]; dst += dstPitch; } } } void GdiV1::drawStripV1Object(byte *dst, int dstPitch, int stripnr, int width, int height) { int charIdx; height /= 8; width /= 8; for (int y = 0; y < height; y++) { _V1.colors[3] = (_V1.objectMap[(y + height) * width + stripnr] & 7); charIdx = _V1.objectMap[y * width + stripnr] * 8; for (int i = 0; i < 8; i++) { byte c = _V1.charMap[charIdx + i]; dst[0] = dst[1] = _V1.colors[(c >> 6) & 3]; dst[2] = dst[3] = _V1.colors[(c >> 4) & 3]; dst[4] = dst[5] = _V1.colors[(c >> 2) & 3]; dst[6] = dst[7] = _V1.colors[(c >> 0) & 3]; dst += dstPitch; } } } void GdiV1::drawStripV1Mask(byte *dst, int stripnr, int width, int height) const { int maskIdx; height /= 8; width /= 8; for (int y = 0; y < height; y++) { if (_objectMode) maskIdx = _V1.objectMap[(y + 2 * height) * width + stripnr] * 8; else maskIdx = _V1.maskMap[y + stripnr * height] * 8; for (int i = 0; i < 8; i++) { byte c = _V1.maskChar[maskIdx + i]; // V1/V0 masks are inverted compared to what ScummVM expects *dst = c ^ 0xFF; dst += _numStrips; } } } void GdiV1::decodeV1Gfx(const byte *src, byte *dst, int size) const { int x, z; byte color, run, common[4]; for (z = 0; z < 4; z++) { common[z] = *src++; } x = 0; while (x < size) { run = *src++; if (run & 0x80) { color = common[(run >> 5) & 3]; run &= 0x1F; for (z = 0; z <= run; z++) { dst[x++] = color; } } else if (run & 0x40) { run &= 0x3F; color = *src++; for (z = 0; z <= run; z++) { dst[x++] = color; } } else { for (z = 0; z <= run; z++) { dst[x++] = *src++; } } } } /** * Create and fill a table with offsets to the graphic and mask strips in the * given V2 EGA bitmap. * @param src the V2 EGA bitmap * @param width the width of the bitmap * @param height the height of the bitmap * @param table the strip table to fill * @return filled strip table */ StripTable *GdiV2::generateStripTable(const byte *src, int width, int height, StripTable *table) const { // If no strip table was given to use, allocate a new one if (table == 0) table = (StripTable *)calloc(1, sizeof(StripTable)); const byte *bitmapStart = src; byte color = 0, data = 0; int x, y, length = 0; byte run = 1; // Decode the graphics strips, and memorize the run/color values // as well as the byte offset. for (x = 0; x < width; x++) { if ((x % 8) == 0) { assert(x / 8 < 160); table->run[x / 8] = run; table->color[x / 8] = color; table->offsets[x / 8] = src - bitmapStart; } for (y = 0; y < height; y++) { if (--run == 0) { data = *src++; if (data & 0x80) { run = data & 0x7f; } else { run = data >> 4; } if (run == 0) { run = *src++; } color = data & 0x0f; } } } // The mask data follows immediately after the graphics. x = 0; y = height; width /= 8; for (;;) { length = *src++; const byte runFlag = length & 0x80; if (runFlag) { length &= 0x7f; data = *src++; } do { if (!runFlag) data = *src++; if (y == height) { assert(x < 120); table->zoffsets[x] = src - bitmapStart - 1; table->zrun[x] = length | runFlag; } if (--y == 0) { if (--width == 0) return table; x++; y = height; } } while (--length); } return table; } void Gdi::drawStripEGA(byte *dst, int dstPitch, const byte *src, int height) const { byte color = 0; int run = 0, x = 0, y = 0, z; while (x < 8) { color = *src++; if (color & 0x80) { run = color & 0x3f; if (color & 0x40) { color = *src++; if (run == 0) { run = *src++; } for (z = 0; z < run; z++) { *(dst + y * dstPitch + x) = (z & 1) ? _roomPalette[(color & 0xf) + _paletteMod] : _roomPalette[(color >> 4) + _paletteMod]; y++; if (y >= height) { y = 0; x++; } } } else { if (run == 0) { run = *src++; } for (z = 0; z < run; z++) { *(dst + y * dstPitch + x) = *(dst + y * dstPitch + x - 1); y++; if (y >= height) { y = 0; x++; } } } } else { run = color >> 4; if (run == 0) { run = *src++; } for (z = 0; z < run; z++) { *(dst + y * dstPitch + x) = _roomPalette[(color & 0xf) + _paletteMod]; y++; if (y >= height) { y = 0; x++; } } } } } #define READ_BIT (shift--, dataBit = data & 1, data >>= 1, dataBit) #define FILL_BITS(n) do { \ if (shift < n) { \ data |= *src++ << shift; \ shift += 8; \ } \ } while (0) // NOTE: drawStripHE is actually very similar to drawStripComplex void Gdi::drawStripHE(byte *dst, int dstPitch, const byte *src, int width, int height, const bool transpCheck) const { static const int delta_color[] = { -4, -3, -2, -1, 1, 2, 3, 4 }; uint32 dataBit, data; byte color; int shift; color = *src++; data = READ_LE_UINT24(src); src += 3; shift = 24; int x = width; while (1) { if (!transpCheck || color != _transparentColor) writeRoomColor(dst, color); dst += _vm->_bytesPerPixel; --x; if (x == 0) { x = width; dst += dstPitch - width * _vm->_bytesPerPixel; --height; if (height == 0) return; } FILL_BITS(1); if (READ_BIT) { FILL_BITS(1); if (READ_BIT) { FILL_BITS(3); color += delta_color[data & 7]; shift -= 3; data >>= 3; } else { FILL_BITS(_decomp_shr); color = data & _decomp_mask; shift -= _decomp_shr; data >>= _decomp_shr; } } } } #undef READ_BIT #undef FILL_BITS void Gdi::drawStrip3DO(byte *dst, int dstPitch, const byte *src, int height, const bool transpCheck) const { if (height == 0) return; int decSize = height * 8; int curSize = 0; do { uint8 data = *src++; uint8 rle = data & 1; int len = (data >> 1) + 1; len = MIN(decSize, len); decSize -= len; if (!rle) { for (; len > 0; len--, src++, dst++) { if (!transpCheck || *src != _transparentColor) *dst = _roomPalette[*src]; curSize++; if (!(curSize & 7)) dst += dstPitch - 8; // Next row } } else { byte color = *src++; for (; len > 0; len--, dst++) { if (!transpCheck || color != _transparentColor) *dst = _roomPalette[color]; curSize++; if (!(curSize & 7)) dst += dstPitch - 8; // Next row } } } while (decSize > 0); } #define READ_BIT (cl--, bit = bits & 1, bits >>= 1, bit) #define FILL_BITS do { \ if (cl <= 8) { \ bits |= (*src++ << cl); \ cl += 8; \ } \ } while (0) void Gdi::drawStripComplex(byte *dst, int dstPitch, const byte *src, int height, const bool transpCheck) const { byte color = *src++; uint bits = *src++; byte cl = 8; byte bit; byte incm, reps; do { int x = 8; do { FILL_BITS; if (!transpCheck || color != _transparentColor) writeRoomColor(dst, color); dst += _vm->_bytesPerPixel; againPos: if (!READ_BIT) { } else if (!READ_BIT) { FILL_BITS; color = bits & _decomp_mask; bits >>= _decomp_shr; cl -= _decomp_shr; } else { incm = (bits & 7) - 4; cl -= 3; bits >>= 3; if (incm) { color += incm; } else { FILL_BITS; reps = bits & 0xFF; do { if (!--x) { x = 8; dst += dstPitch - 8 * _vm->_bytesPerPixel; if (!--height) return; } if (!transpCheck || color != _transparentColor) writeRoomColor(dst, color); dst += _vm->_bytesPerPixel; } while (--reps); bits >>= 8; bits |= (*src++) << (cl - 8); goto againPos; } } } while (--x); dst += dstPitch - 8 * _vm->_bytesPerPixel; } while (--height); } void Gdi::drawStripBasicH(byte *dst, int dstPitch, const byte *src, int height, const bool transpCheck) const { byte color = *src++; uint bits = *src++; byte cl = 8; byte bit; int8 inc = -1; do { int x = 8; do { FILL_BITS; if (!transpCheck || color != _transparentColor) writeRoomColor(dst, color); dst += _vm->_bytesPerPixel; if (!READ_BIT) { } else if (!READ_BIT) { FILL_BITS; color = bits & _decomp_mask; bits >>= _decomp_shr; cl -= _decomp_shr; inc = -1; } else if (!READ_BIT) { color += inc; } else { inc = -inc; color += inc; } } while (--x); dst += dstPitch - 8 * _vm->_bytesPerPixel; } while (--height); } void Gdi::drawStripBasicV(byte *dst, int dstPitch, const byte *src, int height, const bool transpCheck) const { byte color = *src++; uint bits = *src++; byte cl = 8; byte bit; int8 inc = -1; int x = 8; do { int h = height; do { FILL_BITS; if (!transpCheck || color != _transparentColor) writeRoomColor(dst, color); dst += dstPitch; if (!READ_BIT) { } else if (!READ_BIT) { FILL_BITS; color = bits & _decomp_mask; bits >>= _decomp_shr; cl -= _decomp_shr; inc = -1; } else if (!READ_BIT) { color += inc; } else { inc = -inc; color += inc; } } while (--h); dst -= _vertStripNextInc; } while (--x); } #undef READ_BIT #undef FILL_BITS /* Ender - Zak256/Indy256 decoders */ #define READ_BIT_256 \ do { \ if ((mask <<= 1) == 256) { \ buffer = *src++; \ mask = 1; \ } \ bits = ((buffer & mask) != 0); \ } while (0) #define READ_N_BITS(n, c) \ do { \ c = 0; \ for (int b = 0; b < n; b++) { \ READ_BIT_256; \ c += (bits << b); \ } \ } while (0) #define NEXT_ROW \ do { \ dst += dstPitch; \ if (--h == 0) { \ if (!--x) \ return; \ dst -= _vertStripNextInc; \ h = height; \ } \ } while (0) void Gdi::drawStripRaw(byte *dst, int dstPitch, const byte *src, int height, const bool transpCheck) const { int x; if (_vm->_game.features & GF_OLD256) { uint h = height; x = 8; for (;;) { *dst = _roomPalette[*src++]; NEXT_ROW; } } else { do { for (x = 0; x < 8; x ++) { byte color = *src++; if (!transpCheck || color != _transparentColor) writeRoomColor(dst + x * _vm->_bytesPerPixel, color); } dst += dstPitch; } while (--height); } } void Gdi::unkDecode8(byte *dst, int dstPitch, const byte *src, int height) const { uint h = height; int x = 8; for (;;) { uint run = (*src++) + 1; byte color = *src++; do { *dst = _roomPalette[color]; NEXT_ROW; } while (--run); } } void Gdi::unkDecode9(byte *dst, int dstPitch, const byte *src, int height) const { byte c, bits, color, run; int i; uint buffer = 0, mask = 128; int h = height; run = 0; int x = 8; for (;;) { READ_N_BITS(4, c); switch (c >> 2) { case 0: READ_N_BITS(4, color); for (i = 0; i < ((c & 3) + 2); i++) { *dst = _roomPalette[run * 16 + color]; NEXT_ROW; } break; case 1: for (i = 0; i < ((c & 3) + 1); i++) { READ_N_BITS(4, color); *dst = _roomPalette[run * 16 + color]; NEXT_ROW; } break; case 2: READ_N_BITS(4, run); break; } } } void Gdi::unkDecode10(byte *dst, int dstPitch, const byte *src, int height) const { int i; byte local_palette[256], numcolors = *src++; uint h = height; for (i = 0; i < numcolors; i++) local_palette[i] = *src++; int x = 8; for (;;) { byte color = *src++; if (color < numcolors) { *dst = _roomPalette[local_palette[color]]; NEXT_ROW; } else { uint run = color - numcolors + 1; color = *src++; do { *dst = _roomPalette[color]; NEXT_ROW; } while (--run); } } } void Gdi::unkDecode11(byte *dst, int dstPitch, const byte *src, int height) const { int bits, i; uint buffer = 0, mask = 128; byte inc = 1, color = *src++; int x = 8; do { int h = height; do { *dst = _roomPalette[color]; dst += dstPitch; for (i = 0; i < 3; i++) { READ_BIT_256; if (!bits) break; } switch (i) { case 1: inc = -inc; color -= inc; break; case 2: color -= inc; break; case 3: inc = 1; READ_N_BITS(8, color); break; } } while (--h); dst -= _vertStripNextInc; } while (--x); } #undef NEXT_ROW #undef READ_BIT_256 void GdiHE16bit::writeRoomColor(byte *dst, byte color) const { WRITE_UINT16(dst, READ_LE_UINT16(_vm->_hePalettes + 2048 + color * 2)); } void Gdi::writeRoomColor(byte *dst, byte color) const { // As described in bug #1294513 "FOA/Amiga: Palette problem (Regression)" // the original AMIGA version of Indy4: The Fate of Atlantis allowed // overflowing of the palette index. To have the same result in our code, // we need to do an logical AND 0xFF here to keep the result in [0, 255]. *dst = _roomPalette[(color + _paletteMod) & 0xFF]; } #pragma mark - #pragma mark #pragma mark - void ScummEngine::fadeIn(int effect) { if (<API key>) { // fadeIn() calls can be disabled in TheDig after a SMUSH movie // has been played. Like the original interpreter, we introduce // an extra flag to handle this. <API key> = false; _doEffect = false; _screenEffectFlag = true; return; } updatePalette(); switch (effect) { case 0: // seems to do nothing break; case 1: case 2: case 3: case 4: case 5: case 6: // Some of the transition effects won't work properly unless // the screen is marked as clean first. At first I thought I // could safely do this every time fadeIn() was called, but // that broke the FOA intro. Probably other things as well. // Hopefully it's safe to do it at this point, at least. _virtscr[kMainVirtScreen].setDirtyRange(0, 0); transitionEffect(effect - 1); break; case 128: unkScreenEffect6(); break; case 129: break; case 130: case 131: case 132: case 133: scrollEffect(133 - effect); break; case 134: dissolveEffect(1, 1); break; case 135: dissolveEffect(1, _virtscr[kMainVirtScreen].h); break; default: error("Unknown screen effect, %d", effect); } _screenEffectFlag = true; } void ScummEngine::fadeOut(int effect) { VirtScreen *vs = &_virtscr[kMainVirtScreen]; vs->setDirtyRange(0, 0); if (_game.version < 7) camera._last.x = camera._cur.x; #ifndef <API key> if (_game.version == 3 && _game.platform == Common::kPlatformFMTowns) _textSurface.fillRect(Common::Rect(0, vs->topline * <API key>, _textSurface.pitch, (vs->topline + vs->h) * <API key>), 0); #endif // TheDig can disable fadeIn(), and may call fadeOut() several times // successively. Disabling the _screenEffectFlag check forces the screen // to get cleared. This fixes glitches, at least, in the first cutscenes // when bypassed of FT and TheDig. if ((_game.version == 7 || _screenEffectFlag) && effect != 0) { // Fill screen 0 with black memset(vs->getPixels(0, 0), 0, vs->pitch * vs->h); // Fade to black with the specified effect, if any. switch (effect) { case 1: case 2: case 3: case 4: case 5: case 6: transitionEffect(effect - 1); break; case 128: unkScreenEffect6(); break; case 129: // Just blit screen 0 to the display (i.e. display will be black) vs->setDirtyRange(0, vs->h); updateDirtyScreen(kMainVirtScreen); #ifndef <API key> if (_townsScreen) _townsScreen->update(); #endif break; case 134: dissolveEffect(1, 1); break; case 135: dissolveEffect(1, _virtscr[kMainVirtScreen].h); break; default: error("fadeOut: default case %d", effect); } } // Update the palette at the end (once we faded to black) to avoid // some nasty effects when the palette is changed updatePalette(); _screenEffectFlag = false; } /** * Perform a transition effect. There are four different effects possible: * 0: Iris effect * 1: Box wipe (a black box expands from the upper-left corner to the lower-right corner) * 2: Box wipe (a black box expands from the lower-right corner to the upper-left corner) * 3: Inverse box wipe * All effects operate on 8x8 blocks of the screen. These blocks are updated * in a certain order; the exact order determines how the effect appears to the user. * @param a the transition effect to perform */ void ScummEngine::transitionEffect(int a) { int delta[16]; // Offset applied during each iteration int tab_2[16]; int i, j; int bottom; int l, t, r, b; const int height = MIN((int)_virtscr[kMainVirtScreen].h, _screenHeight); const int delay = (VAR_FADE_DELAY != 0xFF) ? VAR(VAR_FADE_DELAY) * kFadeDelay : kPictureDelay; for (i = 0; i < 16; i++) { delta[i] = transitionEffects[a].deltaTable[i]; j = transitionEffects[a].stripTable[i]; if (j == 24) j = height / 8 - 1; tab_2[i] = j; } bottom = height / 8; for (j = 0; j < transitionEffects[a].numOfIterations; j++) { for (i = 0; i < 4; i++) { l = tab_2[i * 4]; t = tab_2[i * 4 + 1]; r = tab_2[i * 4 + 2]; b = tab_2[i * 4 + 3]; if (t == b) { while (l <= r) { if (l >= 0 && l < _gdi->_numStrips && t < bottom) { _virtscr[kMainVirtScreen].tdirty[l] = _screenTop + t * 8; _virtscr[kMainVirtScreen].bdirty[l] = _screenTop + (b + 1) * 8; } l++; } } else { if (l < 0 || l >= _gdi->_numStrips || b <= t) continue; if (b > bottom) b = bottom; if (t < 0) t = 0; _virtscr[kMainVirtScreen].tdirty[l] = _screenTop + t * 8; _virtscr[kMainVirtScreen].bdirty[l] = _screenTop + (b + 1) * 8; } updateDirtyScreen(kMainVirtScreen); } for (i = 0; i < 16; i++) tab_2[i] += delta[i]; // Draw the current state to the screen and wait a few secs so the // user can watch the effect taking place. waitForTimer(delay); } } /** * Update width*height areas of the screen, in random order, until the whole * screen has been updated. For instance: * * dissolveEffect(1, 1) produces a pixel-by-pixel dissolve * dissolveEffect(8, 8) produces a square-by-square dissolve * dissolveEffect(virtsrc[0].width, 1) produces a line-by-line dissolve */ void ScummEngine::dissolveEffect(int width, int height) { VirtScreen *vs = &_virtscr[kMainVirtScreen]; int *offsets; int <API key>, blits; int x, y; int w, h; int i; // There's probably some less memory-hungry way of doing this. But // since we're only dealing with relatively small images, it shouldn't // be too bad. w = vs->w / width; h = vs->h / height; // When used correctly, vs->width % width and vs->height % height // should both be zero, but just to be safe... if (vs->w % width) w++; if (vs->h % height) h++; offsets = (int *) malloc(w * h * sizeof(int)); if (offsets == NULL) error("dissolveEffect: out of memory"); // Create a permutation of offsets into the frame buffer if (width == 1 && height == 1) { // Optimized case for pixel-by-pixel dissolve for (i = 0; i < vs->w * vs->h; i++) offsets[i] = i; for (i = 1; i < w * h; i++) { int j; j = _rnd.getRandomNumber(i - 1); offsets[i] = offsets[j]; offsets[j] = i; } } else { int *offsets2; for (i = 0, x = 0; x < vs->w; x += width) for (y = 0; y < vs->h; y += height) offsets[i++] = y * vs->pitch + x; offsets2 = (int *) malloc(w * h * sizeof(int)); if (offsets2 == NULL) error("dissolveEffect: out of memory"); memcpy(offsets2, offsets, w * h * sizeof(int)); for (i = 1; i < w * h; i++) { int j; j = _rnd.getRandomNumber(i - 1); offsets[i] = offsets[j]; offsets[j] = offsets2[i]; } free(offsets2); } // Blit the image piece by piece to the screen. The idea here is that // the whole update should take about a quarter of a second, assuming // most of the time is spent in waitForTimer(). It looks good to me, // but might still need some tuning. blits = 0; <API key> = (3 * w * h) / 25; // Speed up the effect for CD Loom since it uses it so often. I don't // think the original had any delay at all, so on modern hardware it // wasn't even noticeable. if (_game.id == GID_LOOM && (_game.version == 4)) <API key> *= 2; for (i = 0; i < w * h; i++) { x = offsets[i] % vs->pitch; y = offsets[i] / vs->pitch; #ifndef <API key> if (_game.platform == Common::kPlatformFMTowns) <API key>(vs, x, y + vs->topline, x, y, width, height); else #endif _system->copyRectToScreen(vs->getPixels(x, y), vs->pitch, x, y + vs->topline, width, height); if (++blits >= <API key>) { blits = 0; waitForTimer(30); } } free(offsets); if (blits != 0) { waitForTimer(30); } } void ScummEngine::scrollEffect(int dir) { VirtScreen *vs = &_virtscr[kMainVirtScreen]; int x, y; int step; const int delay = (VAR_FADE_DELAY != 0xFF) ? VAR(VAR_FADE_DELAY) * kFadeDelay : kPictureDelay; if ((dir == 0) || (dir == 1)) step = vs->h; else step = vs->w; step = (step * delay) / kScrolltime; byte *src; int m = <API key>; int vsPitch = vs->pitch; switch (dir) { case 0: y = 1 + step; while (y < vs->h) { moveScreen(0, -step, vs->h); #ifndef <API key> if (_townsScreen) { <API key>(vs, 0, vs->topline + vs->h - step, 0, y - step, vs->w, step); } else #endif { src = vs->getPixels(0, y - step); _system->copyRectToScreen(src, vsPitch, 0, (vs->h - step) * m, vs->w * m, step * m); _system->updateScreen(); } waitForTimer(delay); y += step; } break; case 1: // down y = 1 + step; while (y < vs->h) { moveScreen(0, step, vs->h); #ifndef <API key> if (_townsScreen) { <API key>(vs, 0, vs->topline, 0, vs->h - y, vs->w, step); } else #endif { src = vs->getPixels(0, vs->h - y); _system->copyRectToScreen(src, vsPitch, 0, 0, vs->w * m, step * m); _system->updateScreen(); } waitForTimer(delay); y += step; } break; case 2: // left x = 1 + step; while (x < vs->w) { moveScreen(-step, 0, vs->h); #ifndef <API key> if (_townsScreen) { <API key>(vs, vs->w - step, vs->topline, x - step, 0, step, vs->h); } else #endif { src = vs->getPixels(x - step, 0); _system->copyRectToScreen(src, vsPitch, (vs->w - step) * m, 0, step * m, vs->h * m); _system->updateScreen(); } waitForTimer(delay); x += step; } break; case 3: // right x = 1 + step; while (x < vs->w) { moveScreen(step, 0, vs->h); #ifndef <API key> if (_townsScreen) { <API key>(vs, 0, vs->topline, vs->w - x, 0, step, vs->h); } else #endif { src = vs->getPixels(vs->w - x, 0); _system->copyRectToScreen(src, vsPitch, 0, 0, step, vs->h); _system->updateScreen(); } waitForTimer(delay); x += step; } break; } } void ScummEngine::unkScreenEffect6() { // CD Loom (but not EGA Loom!) uses a more fine-grained dissolve if (_game.id == GID_LOOM && (_game.version == 4)) dissolveEffect(1, 1); else dissolveEffect(8, 4); } } // End of namespace Scumm
// This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // invalidate any other reasons why the executable file might be covered by // This exception applies only to the code released under the name GNU // Common C++. If you copy code from other releases into a copy of GNU // not apply to the code that you add in this way. To avoid misleading // anyone as to the status of such modified files, you must delete // this exception notice from them. // If you write modifications of your own for GNU Common C++, it is your choice // whether to permit this exception to apply to your modifications. // If you do not wish that, delete this exception notice. #include <cc++/config.h> #include <cc++/export.h> #include <cc++/thread.h> #include <cc++/slog.h> #ifdef __BORLANDC__ #include <stdio.h> #include <stdarg.h> #else #include <cstdio> #include <cstdarg> #endif #include "../src/private.h" #ifdef HAVE_SYSLOG_H #include <syslog.h> #endif using std::streambuf; using std::ofstream; using std::ostream; using std::clog; using std::endl; using std::ios; #ifdef CCXX_NAMESPACES namespace ost { #endif Slog slog; Slog::Slog(void) : streambuf() #ifdef HAVE_OLD_IOSTREAM ,ostream() #else ,ostream((streambuf *)this) #endif { #ifdef HAVE_OLD_IOSTREAM init((streambuf *)this); #endif _enable = true; _level = levelDebug; _clogEnable = true; #ifndef HAVE_SYSLOG_H syslog = NULL; #endif } Slog::~Slog(void) { #ifdef HAVE_SYSLOG_H closelog(); #else if(syslog) fclose(syslog); #endif } ThreadImpl *Slog::getPriv(void) { Thread *thread = Thread::get(); if(!thread) return NULL; return thread->priv; } void Slog::close(void) { #ifdef HAVE_SYSLOG_H closelog(); #else lock.enterMutex(); if(syslog) fclose(syslog); syslog = NULL; lock.leaveMutex(); #endif } void Slog::open(const char *ident, Class grp) { const char *cp; #ifdef HAVE_SYSLOG_H cp = strrchr(ident, '/'); if(cp) ident = ++cp; int fac; switch(grp) { case classUser: fac = LOG_USER; break; case classDaemon: fac = LOG_DAEMON; break; case classAudit: #ifdef LOG_AUTHPRIV fac = LOG_AUTHPRIV; break; #endif case classSecurity: fac = LOG_AUTH; break; case classLocal0: fac = LOG_LOCAL0; break; case classLocal1: fac = LOG_LOCAL1; break; case classLocal2: fac = LOG_LOCAL2; break; case classLocal3: fac = LOG_LOCAL3; break; case classLocal4: fac = LOG_LOCAL4; break; case classLocal5: fac = LOG_LOCAL5; break; case classLocal6: fac = LOG_LOCAL6; break; case classLocal7: fac = LOG_LOCAL7; break; default: fac = LOG_USER; break; } openlog(ident, 0, fac); #else char *buf; lock.enterMutex(); if(syslog) fclose(syslog); buf = new char[strlen(ident) + 1]; strcpy(buf, ident); cp = (const char *)buf; buf = strrchr(buf, '.'); if(buf) { if(!stricmp(buf, ".exe")) strcpy(buf, ".log"); } syslog = fopen(cp, "a"); delete[] (char *)cp; lock.leaveMutex(); #endif } #ifdef HAVE_SNPRINTF void Slog::error(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; va_start(args, format); overflow(EOF); if(!thread) return; error(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } void Slog::warn(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; if(!thread) return; va_start(args, format); overflow(EOF); warn(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } void Slog::debug(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; if(!thread) return; va_start(args, format); overflow(EOF); debug(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } void Slog::emerg(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; if(!thread) return; va_start(args, format); overflow(EOF); emerg(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } void Slog::alert(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; if(!thread) return; va_start(args, format); overflow(EOF); alert(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } void Slog::critical(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; if(!thread) return; va_start(args, format); overflow(EOF); critical(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } void Slog::notice(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; if(!thread) return; va_start(args, format); overflow(EOF); notice(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } void Slog::info(const char *format, ...) { ThreadImpl *thread = getPriv(); va_list args; if(!thread) return; va_start(args, format); overflow(EOF); info(); vsnprintf(thread->_msgbuf, sizeof(thread->_msgbuf), format, args); thread->_msgpos = strlen(thread->_msgbuf); overflow(EOF); va_end(args); } #endif int Slog::overflow(int c) { ThreadImpl *thread = getPriv(); if(!thread) return c; if(c == '\n' || !c || c == EOF) { if(!thread->_msgpos) return c; thread->_msgbuf[thread->_msgpos] = 0; if (_enable) #ifdef HAVE_SYSLOG_H syslog(priority, "%s", thread->_msgbuf); #else { time_t now; struct tm *dt; time(&now); dt = localtime(&now); char buf[256]; const char *p = "unknown"; switch(priority) { case levelEmergency: p = "emerg"; break; case levelInfo: p = "info"; break; case levelError: p = "error"; break; case levelAlert: p = "alert"; break; case levelDebug: p = "debug"; break; case levelNotice: p = "notice"; break; case levelWarning: p = "warn"; break; case levelCritical: p = "crit"; break; } lock.enterMutex(); snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d [%s] %s\n", dt->tm_year + 1900, dt->tm_mon + 1, dt->tm_mday, dt->tm_hour, dt->tm_min, dt->tm_sec, p, thread->_msgbuf); if(syslog) fputs(buf, syslog); // syslog << "[" << priority << "] " << thread->_msgbuf << endl; lock.leaveMutex(); } #endif thread->_msgpos = 0; if ( _enable && _clogEnable #ifndef WIN32 && (getppid() > 1) #endif ) clog << thread->_msgbuf << endl; _enable = true; return c; } if (thread->_msgpos < (int)(sizeof(thread->_msgbuf) - 1)) thread->_msgbuf[thread->_msgpos++] = c; return c; } Slog &Slog::operator()(const char *ident, Class grp, Level lev) { ThreadImpl *thread = getPriv(); if(!thread) return *this; thread->_msgpos = 0; _enable = true; open(ident, grp); return this->operator()(lev, grp); } Slog &Slog::operator()(Level lev, Class grp) { ThreadImpl *thread = getPriv(); if(!thread) return *this; thread->_msgpos = 0; if(_level >= lev) _enable = true; else _enable = false; #ifdef HAVE_SYSLOG_H switch(lev) { case levelEmergency: priority = LOG_EMERG; break; case levelAlert: priority = LOG_ALERT; break; case levelCritical: priority = LOG_CRIT; break; case levelError: priority = LOG_ERR; break; case levelWarning: priority = LOG_WARNING; break; case levelNotice: priority = LOG_NOTICE; break; case levelInfo: priority = LOG_INFO; break; case levelDebug: priority = LOG_DEBUG; break; } switch(grp) { case classAudit: #ifdef LOG_AUTHPRIV priority |= LOG_AUTHPRIV; break; #endif case classSecurity: priority |= LOG_AUTH; break; case classUser: priority |= LOG_USER; break; case classDaemon: priority |= LOG_DAEMON; break; case classDefault: priority |= LOG_USER; break; case classLocal0: priority |= LOG_LOCAL0; break; case classLocal1: priority |= LOG_LOCAL1; break; case classLocal2: priority |= LOG_LOCAL2; break; case classLocal3: priority |= LOG_LOCAL3; break; case classLocal4: priority |= LOG_LOCAL4; break; case classLocal5: priority |= LOG_LOCAL5; break; case classLocal6: priority |= LOG_LOCAL6; break; case classLocal7: priority |= LOG_LOCAL7; break; } #else priority = lev; #endif return *this; } Slog &Slog::operator()(void) { return *this; } #ifdef CCXX_NAMESPACES } #endif /** EMACS ** * Local variables: * mode: c++ * c-basic-offset: 6 * End: */
class CfgAmmo { class M_PG_AT; class <API key>: M_PG_AT { displayName = "AGM-114K"; displayNameShort = "AGM-114K"; description = "AGM-114K"; descriptionShort = "AGM-114K"; model = "\A3\Weapons_F\Ammo\Missile_AT_03_fly_F"; proxyShape = "\A3\Weapons_F\Ammo\Missile_AT_03_F"; hit = 1400; indirectHit = 71; indirectHitRange = 4.5; effectsMissile = "missile2"; irLock = 0; laserLock = 0; manualControl = 0; maxSpeed = 450; thrustTime = 2.5; // motor burn 2-3 sec thrust = 250; timeToLive = 40; EGVAR(rearm,caliber) = 178; class ace_missileguidance { enabled = 1; minDeflection = 0.0005; // Minium flap deflection for guidance maxDeflection = 0.01; // Maximum flap deflection for guidance incDeflection = 0.0005; // The incrmeent in which deflection adjusts. canVanillaLock = 0; // Can this default vanilla lock? Only applicable to non-cadet mode // Guidance type for munitions defaultSeekerType = "SALH"; seekerTypes[] = { "SALH", "LIDAR", "SARH", "Optic", "Thermal", "GPS", "SACLOS", "MCLOS" }; <API key> = "LOAL"; seekerLockModes[] = { "LOAL", "LOBL" }; seekLastTargetPos = 1; // seek last target position [if seeker loses LOS of target, continue to last known pos] seekerAngle = 70; // Angle in front of the missile which can be searched seekerAccuracy = 1; // seeker accuracy multiplier seekerMinRange = 1; seekerMaxRange = 5000; // Range from the missile which the seeker can visually search // Attack profile type selection <API key> = "hellfire"; attackProfiles[] = {"hellfire", "hellfire_hi", "hellfire_lo"}; }; }; class <API key>: <API key> { displayName = "AGM-114N"; displayNameShort = "AGM-114N"; description = "AGM-114N"; descriptionShort = "AGM-114N"; hit = 1100; indirectHit = 200; indirectHitRange = 10; explosionEffects = "BombExplosion"; class ace_missileguidance: ace_missileguidance { enabled = 1; // Missile Guidance must be explicitly enabled }; }; };
<?php $TRANSLATIONS = array( "First Run Wizard" => " ", "Show First Run Wizard again" => " " );
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using INB302_WDGS.Droid; [assembly: ExportRenderer(typeof(Editor), typeof(<API key>))] namespace INB302_WDGS.Droid { class <API key> : EditorRenderer { protected override void OnElementChanged(<API key><Editor> e) { base.OnElementChanged(e); if (Control != null) { Control.TextSize = 16; } } } }
<html> <head> <title> Grease - xdebugd web interface </title> </head> <body> <script> var xdebug ={ activeSession: false, activeServerId: false, sessions: false, setupEvents: function() { window.onresize = this.event.windowResize; }, event: { windowResize: function(ev) { console.log(ev); } }, ajaxRequest: function(url, cb, params) { request = new XMLHttpRequest(); if(params) { request.open('GET', url+'?'+params, true); } else { request.open('GET', url, true); } var that = this; request.onload = function() { if (request.status >= 200 && request.status < 400) { data = JSON.parse(request.responseText); if(cb) { cb.call(that, data); } } else { //alert('Failed to phone home!'); } }; request.onerror = function() { }; request.send(); }, getSessions: function() { this.ajaxRequest('/getSessions', this.listSessions); }, init: function() { this.ajaxRequest('/init', this.dump, 'serverId='+this.activeServerId+'&idekey='+this.activeSession); }, run: function() { this.ajaxRequest('/run', this.dump, 'serverId='+this.activeServerId+'&idekey='+this.activeSession); }, stepInto: function() { this.ajaxRequest('/stepInto', this.dump, 'serverId='+this.activeServerId+'&idekey='+this.activeSession); }, record: function() { this.ajaxRequest('/record', this.dump, 'serverId='+this.activeServerId+'&idekey='+this.activeSession); }, stepAll: function() { var that = this; setTimeout( function() { that.stepInto(); that.stepAll(); },100 ); }, listSessions: function(sessions) { this.sessions = sessions; var session; var div = document.getElementById('sessions'); div.innerHTML = ''; for(session in sessions) { console.log(session); console.log(sessions[session]); div.innerHTML = div.innerHTML + '<a href="#" onclick="xdebug.setSession(\''+session+'\');">'+session+'</a>&nbsp;|&nbsp;'; }; }, setSession: function(session) { this.activeSession = session; this.activeServerId = this.sessions[session]['connectionId']; this.dump({}); }, dump: function(data) { // get specific session dump!! console.log('here'); this.ajaxRequest('/dump', this.showDump, false); }, showDump: function(data) { var div = document.getElementById('dump'); div.innerHTML = ''; //for(var session in data) data[this.activeSession].reverse(); var i = 0; for(var ctx in data[this.activeSession]) { i++; if(i>=40) break; if(data[this.activeSession][ctx] != null) div.innerHTML = data[this.activeSession][ctx]['filename'] + ' -> ' + data[this.activeSession][ctx]['lineno'] + ' <b>' +data[this.activeSession][ctx]['preview']+ '</b><br>' + div.innerHTML; } } }; xdebug.setupEvents(); </script> <button style="display: inline;" onclick="xdebug.getSessions();"> Refresh Sessions </button> } <div style="display: inline;" id="sessions"></div> <hr> <button style="display: inline;" onclick="xdebug.init();"> Init </button> <button style="display: inline;" onclick="xdebug.run();"> Run </button> <button style="display: inline;" onclick="xdebug.stepInto();"> Step Into </button> <button style="display: inline;" onclick="xdebug.stepAll();"> Step All </button> <button style="display: inline;" onclick="xdebug.record();"> Record </button> <button style="display: inline;" onclick="xdebug.dump();"> Refresh Dump </button> <hr> <div id="content"></div> <hr> <div id="dump"></div> </body> </html>
{% load staticfiles %} {% load custom_filter %}{% load custom_tag %} <!DOCTYPE html> <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <! <link rel="shortcut icon" href='{% static "img/du_favicon.ico" %}'> <title>Remote Visualization</title> <!-- 3rd party CSS --> <link href='{% static "3rdparty/bootstrap-3.3.0/css/bootstrap.min.css" %}' rel="stylesheet"/> <link href='{% static "3rdparty/font-awesome-4.2.0/css/font-awesome.min.css" %}' rel="stylesheet"/> <!-- Base CSS --> <link href='{% static "css/main.css" %}' rel="stylesheet"/> <link href='{% static "css/base.css" %}' rel="stylesheet"/> <!-- World Wind CSS --> <link href='{% static "worldwind/Examples.css" %}' rel="stylesheet"/> <link href='{% static "worldwind/LayerManager/LayerManager.css" %}' rel="stylesheet"/> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src='{% static "3rdparty/html5shiv-3.7.2/html5shiv.min.js" %}'></script> <script src='{% static "3rdparty/respond.js/respond.min.js" %}'></script> <![endif] <style> #requestform {margin-top: 100px;} </style> </head> <body onbeforeunload="stop()" onunload="stop()" class="page"> <nav id="banner" class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class=""> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!--<img src='{% static "img/du_logo.png" %}' class="navbar-logo">--> <a class="navbar-brand" href="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; GeoViz &nbsp;-&nbsp; A Cloud-enabled Remote Visualization Tool for Distributed Time-varying Climate Data Analytics</a> </div> </div> </nav> <div class="row"> <div class="col-sm-2 col-md-2 col-lg-2"></div> <div class="col-sm-8 col-md-8 col-lg-8" id="requestform"> <div class="well"> <p>Please note that currently we only accept the requests of Amazon GPU instances from journal reviewers.</p> <p>If you are anonymous referee, please fill out the form below to submit a request for GPU instances.</p> </div> <br/> <div class="alert alert-danger" id="alert-msg"> Please correct the error below </div> <h1>Request Form</h1> <hr> <form action="" method="post">{% csrf_token %} <div class="form-group"> <div class="form-group"> <label for="id_journal">Name of journal you are reviewing:</label> <div class="alert alert-danger" id="alert-journal"> This field is required. </div> <input id="id_journal" maxlength="500" name="journal" type="text" class="form-control"> <br/> <label for="id_email">Email address to receive a link to access GeoViz application:</label> <div class="alert alert-danger" id="alert-email"> This field is required. </div> <input id="id_email" maxlength="254" name="email" type="email" class="form-control"> <br/> <label for="id_gpu_num">Number of GPU instances you are requesting:</label> <div class="alert alert-danger" id="alert-gpu_num"> This field is required. </div> <select id="id_gpu_num" name="gpu_num" class="form-control"> <option value="" selected="selected"> {% for c in gpu_choices %} <option value="{{c}}">{{c}}</option> {% endfor %} </select> <br/> <label for="id_schedule_time">Scheduled time to launch the GPU cluster:</label> <div class="alert alert-warning"> We will regularly check email between 12pm-4pm Eastern Time. Any time scheduled for before 12pm EST will be pushed to the next day. </div> <div class="alert alert-danger" id="alert-schedule_time"> This field is required. </div> <p class="datetime"> Date(EST) (mm/dd/yyyy): <input id="<API key>" name="schedule_time_date" maxlength="10" size="10" type="text" class="form-control" placeholder="mm/dd/yyyy"> Time(EST) (hh:mm): <input id="<API key>" name="schedule_time_time" maxlength="5" size="5" type="text" class="form-control" placeholder="hh:mm"> <br/> <label for="id_request_hour">Total hours of accessing the application:</label> <div class="alert alert-danger" id="alert-request_hour"> This field is required. </div> <select id="id_request_hour" name="request_hour" class="form-control"> <option value="" selected="selected"> {% for c in hour_choices %} <option value="{{c}}">{{c}}</option> {% endfor %} </select> </div> </div> <button id="btn-requestcluster" type="button" class="btn btn-success btn-lg btn-block" data-toggle="modal">Request Cloud Cluster</button> <input id="url-requestcluster" type="hidden" value="{% setting 'ROOT_APP_URL' %}/requestcluster/"></input> </form> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">GeoViz Cloud GPU</h4> </div> <div class="modal-body"> You will soon receive an email confirmation from GeoViz team about your request.<br/> The GPU cloud cluster (<span id="urlgpunum"></span> instances) you requested will be scheduled to launch at your preferred date and time.<br/> We will send you another emial notification when the GPU cluster is ready for use.<br/> Please follow the link and instructions in the email to access the application. </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> </div> <div class="col-sm-2 col-md-2 col-lg-2"></div> </div><!-- /.container --> <!-- Bottom JavaScript --> <!-- 3rd party JS --> <script src="{% static '3rdparty/jquery-11.1.1/jquery.min.js' %}"></script> <script src='{% static "3rdparty/jquery.cookie/jquery.cookie.js" %}'></script> <script src="{% static '3rdparty/bootstrap-3.3.0/js/bootstrap.min.js' %}"></script> <script src="{% static '3rdparty/bootstrap-3.3.0/js/<API key>.js' %}"></script> <!-- Script for style --> <script> $(".alert-danger").hide(); function requestcluster(){ var error = false; $(".alert-danger").hide(); var csrftoken = $.cookie('csrftoken'); var url=$("#url-requestcluster").val(); var journal = $("#id_journal").val(); if (journal == ""){ error = true; $("#alert-journal").show(); } var email = $("#id_email").val(); if (email == ""){ error = true; $("#alert-email").show(); } var gpunum = $("#id_gpu_num").val(); if (gpunum == ""){ error = true; $("#alert-gpu_num").show(); } var hours = $("#id_request_hour").val(); if (hours == ""){ error = true; $("#alert-request_hour").show(); } var sdate = $("#<API key>").val(); var stime = $("#<API key>").val(); if (sdate == "" || stime == ""){ error = true; $("#alert-schedule_time").show(); } if (!error){ $.ajax({ url : url, // the endpoint type : "POST", // http method data : { csrfmiddlewaretoken: csrftoken, journal: journal, email: email, gpunum: gpunum, hours: hours, sdate: sdate, stime: stime, }, // data sent with the delete request success : function(json) { console.log("email sent!"); console.log("request for "+json.gpunum+" gpu instances."); console.log("return url: http://52.26.239.116/geoviz/geoviz/launchcluster/"+json.gpunum+"-"+json.secretkey+"/"); $("#btn-requestcluster").prop('disabled', true); $("#secretkey").html(json.secretkey); $("#secretgpunum").html(json.gpunum); $("#urlgpunum").html(json.gpunum); $("#myModal").css("top","100px"); $("#myModal").modal('toggle'); $("#myModal").modal('show'); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); } else { $("#alert-msg").show(); } } $("#btn-requestcluster").click(function(){requestcluster();}); </script> </body> </html>
// codec_pass.cpp // Passthrough Codec // This program is free software; you can redistribute it and/or modify // published by the Free Software Foundation. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of the GNU General Public // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include <stdio.h> #include <unistd.h> #include "codec_pass.h" CodecPassthrough::CodecPassthrough(unsigned bitrate,QObject *parent) : Codec(Codec::TypePassthrough,bitrate,parent) { } CodecPassthrough::~CodecPassthrough() { } bool CodecPassthrough::isAvailable() const { return true; } QString CodecPassthrough::defaultExtension() const { return QString("wav"); } void CodecPassthrough::process(const QByteArray &data,bool is_last) { if(!isFramed()) { setFramed(channels(),samplerate(), channels()*samplerate()*sizeof(float)/1000); } writePcm((float *)data.constData(),data.length()/(channels()*sizeof(float)), is_last); } void CodecPassthrough::loadStats(QStringList *hdrs,QStringList *values, bool is_first) { }
<?php /** * The template for displaying the footer * * Contains footer content and the closing of the #main and #page div elements. * * @package WordPress * @subpackage Twenty_Thirteen * @since Twenty Thirteen 1.0 */ ?> </div><!-- #main --> <footer class="site-footer" role="contentinfo"> <?php get_sidebar( 'main' ); ?> </footer><!-- #colophon --> </div><!-- #page --> <?php wp_footer(); ?> </body> </html>
#!/usr/bin/ruby # This script can update the title page from any RSS feed, but concrete # adjustments are done specifically to Fedora Planet. # It replaces the content between <!-- <API key> --> # and <!-- BLOG_HEADLINES_END --> in _site/index.html. The file # path of index.html can be passed as an argument. # Usage: # ./rss.rb _site/index.html if ARGV[0] puts "Setting the index file to: #{ARGV[0]}" index_file = ARGV[0] end require 'rss' # Templating require 'liquid' # For striping HTML tags from post descriptions require 'action_view' # Following adjustments are based on Fedora Planet RSS feed. # If you are changing the feed make sure the changes still apply! FEED_URL = 'http://fedoraplanet.org/rss20.xml'.freeze class Article attr_accessor :author, :title, :description, :date, :url # This is needed because we use liquid templates liquid_methods :author, :title, :description, :date, :url def initialize(author, title, description, date, url) @author = author @title = title @description = description @date = date @url = url end end @articles = [] puts "Fetching #{FEED_URL} feed..." rss = RSS::Parser.parse(FEED_URL, false) rss.items.take(4).each do |item| # Extract name from the title # Original title: NAME: TITLE # Expected title: TITLE # Expected name: NAME author = item.title.gsub(/([^:]*):(.*)/, '\\1').strip title = item.title.gsub(/([^:]*):(.*)/, '\\2').strip # Avoid HTML in description description = ActionView::Base.full_sanitizer.sanitize(item.description) # Shorter description if necessary if description && description.length > 140 # Take whole words rather than xy letters description = description.split[0...25].join(' ') description += '&hellip;' unless ['!', '?', '.'].include? description[-1] end # Adjust date, strip time regexp = /([a-zA-Z]{3}\, [0-9]{2} [a-zA-Z]{3} [0-9]{4}).*/ date = item.pubDate.to_s.gsub(regexp, '\\1') @articles << Article.new(author, title, description, date, item.link) end template = <<TEMPLATE <!-- <API key> --> <div class="container" id="blog-headlines"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2><span>Other headlines from our blog</span></h2> </div> </div> <div class="row"> <div class="col-sm-6 blog-headlines"> <article> <h3><a href="{{ articles[0].url }}">{{ articles[0].title }}</a></h3> <p>{{ articles[0].description }}</p> <p><a href="{{ articles[0].url }}">Read more</a></p> <p class="byline">by <span class="author">{{ articles[0].author }}</span> <span class="date">{{ articles[0].date }}</span></p> </article> <article> <h3><a href="{{ articles[1].url }}">{{ articles[1].title }}</a></h3> <p>{{ articles[1].description }}</p> <p><a href="{{ articles[1].url }}">Read more</a></p> <p class="byline">by <span class="author">{{ articles[1].author }}</span> <span class="date">{{ articles[1].date }}</span></p> </article> </div> <div class="col-sm-6 blog-headlines"> <article> <h3><a href="{{ articles[1].url }}">{{ articles[2].title }}</a></h3> <p>{{ articles[2].description }}</p> <p><a href="{{ articles[2].url }}">Read more</a></p> <p class="byline">by <span class="author">{{ articles[2].author }}</span> <span class="date">{{ articles[2].date }}</span></p> </article> <article> <h3><a href="{{ articles[3].url }}">{{ articles[3].title }}</a></h3> <p>{{ articles[3].description }}</p> <p><a href="{{ articles[3].url }}">Read more</a></p> <p class="byline">by <span class="author">{{ articles[3].author }}</span> <span class="date">{{ articles[3].date }}</span></p> </article> </div> </div> </div> </div> <!-- BLOG_HEADLINES_END --> TEMPLATE blog_posts = Liquid::Template.parse(template).render 'articles' => @articles index_file ||= File.expand_path('_site/index.html', '.') contents = File.open(index_file).read.force_encoding('UTF-8') contents.gsub!(/<!-- <API key> -->.*<!-- BLOG_HEADLINES_END -->/im, "\\1#{blog_posts}\\3") File.open(index_file, 'w') do |file| file.write(contents) end
#ifndef _D_PRECIP_H #define _D_PRECIP_H char *<API key>(char *buf, NIDS_d_precip *r); void <API key>(NIDS_d_precip *r); void <API key>(NIDS_d_precip *r, char *prefix); #endif /* _D_PRECIP_H */
using System; using System.Collections.Generic; using Server.Network; namespace Server.Misc { public class AttackMessage { private const string AggressorFormat = "You are attacking {0}!"; private const string AggressedFormat = "{0} is attacking you!"; private const int Hue = 0x22; private static TimeSpan Delay = TimeSpan.FromMinutes( 1.0 ); public static void Initialize() { EventSink.AggressiveAction += new <API key>( <API key> ); } public static void <API key>( <API key> e ) { Mobile aggressor = e.Aggressor; Mobile aggressed = e.Aggressed; if ( !aggressor.Player || !aggressed.Player ) return; if ( !CheckAggressions( aggressor, aggressed ) ) { aggressor.<API key>( MessageType.Regular, Hue, true, String.Format( AggressorFormat, aggressed.Name ) ); aggressed.<API key>( MessageType.Regular, Hue, true, String.Format( AggressedFormat, aggressor.Name ) ); } } public static bool CheckAggressions( Mobile m1, Mobile m2 ) { List<AggressorInfo> list = m1.Aggressors; for ( int i = 0; i < list.Count; ++i ) { AggressorInfo info = list[i]; if ( info.Attacker == m2 && DateTime.UtcNow < (info.LastCombatTime + Delay) ) return true; } list = m2.Aggressors; for ( int i = 0; i < list.Count; ++i ) { AggressorInfo info = list[i]; if ( info.Attacker == m1 && DateTime.UtcNow < (info.LastCombatTime + Delay) ) return true; } return false; } } }
# -*- coding: utf-8 -*- # modify, copy, or redistribute it subject to the terms and conditions # version. This program is distributed in the hope that it will be # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR # with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Any Red Hat trademarks that are incorporated in the source # code or documentation are not subject to the GNU General Public # of Red Hat, Inc. ''' anitya tests for the custom backend. ''' import json import unittest import anitya.lib.backends.hackage as backend import anitya.lib.model as model from anitya.lib.exceptions import <API key> from anitya.tests.base import Modeltests, create_distro, skip_jenkins BACKEND = 'Hackage' class HackageBackendtests(Modeltests): """ Hackage backend tests. """ @skip_jenkins def setUp(self): """ Set up the environnment, ran before every tests. """ super(HackageBackendtests, self).setUp() create_distro(self.session) self.create_project() def create_project(self): """ Create some basic projects to work with. """ project = model.Project( name='Biobase', homepage='http://hackage.haskell.org/package/Biobase', backend=BACKEND, ) self.session.add(project) self.session.commit() project = model.Project( name='foobar', homepage='http://hackage.haskell.org/package/foobar', backend=BACKEND, ) self.session.add(project) self.session.commit() def test_get_version(self): """ Test the get_version function of the custom backend. """ pid = 1 project = model.Project.get(self.session, pid) exp = '0.3.1.1' obs = backend.HackageBackend.get_version(project) self.assertEqual(obs, exp) pid = 2 project = model.Project.get(self.session, pid) self.assertRaises( <API key>, backend.HackageBackend.get_version, project ) def test_get_versions(self): """ Test the get_versions function of the custom backend. """ pid = 1 project = model.Project.get(self.session, pid) exp = ['0.3.1.1'] obs = backend.HackageBackend.<API key>(project) self.assertEqual(obs, exp) pid = 2 project = model.Project.get(self.session, pid) self.assertRaises( <API key>, backend.HackageBackend.get_version, project ) if __name__ == '__main__': SUITE = unittest.TestLoader().<API key>(HackageBackendtests) unittest.TextTestRunner(verbosity=2).run(SUITE)
require 'rails_helper' RSpec.describe "artifacts/edit", type: :view do before(:each) do @artifact = assign(:artifact, Artifact.create!( :tittle => "MyString", :content => "MyText" )) end it "renders the edit artifact form" do render assert_select "form[action=?][method=?]", artifact_path(@artifact), "post" do assert_select "input[name=?]", "artifact[tittle]" assert_select "textarea[name=?]", "artifact[content]" end end end
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_08) on Thu Jan 25 19:55:35 BRST 2007 --> <TITLE> core.images </TITLE> <META NAME="keywords" CONTENT="core.images package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../core/images/package-summary.html" target="classFrame">core.images</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="CBMPFormat.html" title="class in core.images" target="classFrame">CBMPFormat</A> <BR> <A HREF="CColorPixel.html" title="class in core.images" target="classFrame">CColorPixel</A> <BR> <A HREF="CFormat.html" title="class in core.images" target="classFrame">CFormat</A> <BR> <A HREF="CFormatFactory.html" title="class in core.images" target="classFrame">CFormatFactory</A> <BR> <A HREF="CGIFFormat.html" title="class in core.images" target="classFrame">CGIFFormat</A> <BR> <A HREF="CGrayScalePixel.html" title="class in core.images" target="classFrame">CGrayScalePixel</A> <BR> <A HREF="CImage.html" title="class in core.images" target="classFrame">CImage</A> <BR> <A HREF="CImageObject.html" title="class in core.images" target="classFrame">CImageObject</A> <BR> <A HREF="CJPEGFormat.html" title="class in core.images" target="classFrame">CJPEGFormat</A> <BR> <A HREF="CPixel.html" title="class in core.images" target="classFrame">CPixel</A> <BR> <A HREF="CPNGFormat.html" title="class in core.images" target="classFrame">CPNGFormat</A> <BR> <A HREF="CTIFFFormat.html" title="class in core.images" target="classFrame">CTIFFFormat</A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Enums</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="CFormatFactory.CFormatEnum.html" title="enum in core.images" target="classFrame">CFormatFactory.CFormatEnum</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
/* ScriptData SDName: <API key> SD%Complete: ??% SDComment: based on /dev/rsa SDCategory: Crusader Coliseum EndScriptData */ // Known bugs: // Some visuals aren't appearing right sometimes // TODO: // Redone summon's scripts in SAI // Add immunities to the boss and summons #include "LordJaraxxus.h" enum Yells { SAY_INTRO = -1649030, SAY_AGGRO = -1649031, SAY_DEATH = -1649032, EMOTE_INCINERATE = -1649033, SAY_INCINERATE = -1649034, EMOTE_LEGION_FLAME = -1649035, EMOTE_NETHER_PORTAL = -1649036, SAY_NETHER_PORTAL = -1649037, <API key> = -1649038, <API key> = -1649039, }; enum Equipment { EQUIP_MAIN = 47266, EQUIP_OFFHAND = 46996, EQUIP_RANGED = 47267, EQUIP_DONE = EQUIP_NO_CHANGE, }; enum Summons { NPC_LEGION_FLAME = 34784, <API key> = 34813, NPC_FEL_INFERNAL = 34815, // immune to all CC on Heroic (stuns, banish, interrupt, etc) NPC_NETHER_PORTAL = 34825, }; enum BossSpells { SPELL_LEGION_FLAME = 66197, // player should run away from raid because he triggers Legion Flame <API key> = 66201, // used by trigger npc SPELL_NETHER_POWER = 66228, // +20% of spell damage per stack, stackable up to 5/10 times, must be dispelled/stealed SPELL_FEL_LIGHTING = 66528, // jumps to nearby targets SPELL_FEL_FIREBALL = 66532, // does heavy damage to the tank, interruptable <API key> = 66237, // target must be healed or will trigger Burning Inferno <API key> = 66242, // triggered by Incinerate Flesh <API key> = 66258, // summons Infernal Volcano <API key> = 66252, // summons Felflame Infernal (3 at Normal and inifinity at Heroic) SPELL_NETHER_PORTAL = 66269, // summons Nether Portal <API key> = 66263, // summons Mistress of Pain (1 at Normal and infinity at Heroic) SPELL_BERSERK = 64238, // unused // Mistress of Pain spells SPELL_SHIVAN_SLASH = 67098, <API key> = 66283, SPELL_MISTRESS_KISS = 67077, SPELL_FEL_INFERNO = 67047, SPELL_FEL_STREAK = 66494, }; enum BossEvents { <API key> = 0, <API key>, <API key>, <API key>, <API key>, <API key>, <API key> }; class boss_jaraxxus : public CreatureScript { public: boss_jaraxxus() : CreatureScript("boss_jaraxxus") { } CreatureAI* GetAI(Creature* creature) const { return new boss_jaraxxusAI(creature); } struct boss_jaraxxusAI : public ScriptedAI { boss_jaraxxusAI(Creature* creature) : ScriptedAI(creature), Summons(me) { instance = creature->GetInstanceScript(); Reset(); } void Reset() { SetEquipmentSlots(false, EQUIP_MAIN, EQUIP_OFFHAND, EQUIP_RANGED); Summons.DespawnAll(); m_EventMap.Reset(); } void EnterCombat(Unit* /*victim*/) { me->SetInCombatWithZone(); DoScriptText(SAY_AGGRO, me); m_EventMap.ScheduleEvent(<API key>, 5 * IN_MILLISECONDS); m_EventMap.ScheduleEvent(<API key>, urand(10 * IN_MILLISECONDS, 15 * IN_MILLISECONDS)); m_EventMap.ScheduleEvent(<API key>, urand(20 * IN_MILLISECONDS, 25 * IN_MILLISECONDS)); m_EventMap.ScheduleEvent(<API key>, 40 * IN_MILLISECONDS); m_EventMap.ScheduleEvent(<API key>, 30 * IN_MILLISECONDS); m_EventMap.ScheduleEvent(<API key>, 1 * MINUTE*IN_MILLISECONDS); m_EventMap.ScheduleEvent(<API key>, 2 * MINUTE*IN_MILLISECONDS); if (instance) instance->SetData(<API key>, IN_PROGRESS); } void JustReachedHome() { DoCast(me, <API key>); me->SetFlag(UNIT_FIELD_FLAGS, <API key>); me->SetReactState(REACT_PASSIVE); } void JustDied(Unit* /*killer*/) { Summons.DespawnAll(); DoScriptText(SAY_DEATH, me); if (instance) instance->SetData(<API key>, DONE); } void JustSummoned(Creature* summoned) { Summons.Summon(summoned); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; m_EventMap.Update(diff); ExecuteEvents(); <API key>(); } void ExecuteEvents() { while (uint32 eventId = m_EventMap.ExecuteEvent()) { switch (eventId) { case <API key>: { if (Unit* target = SelectTarget(<API key>)) DoCast(target, SPELL_FEL_LIGHTING); m_EventMap.ScheduleEvent(<API key>, urand(5 * IN_MILLISECONDS, 10 * IN_MILLISECONDS)); }break; case <API key>: { if (Unit* target = SelectTarget(<API key>)) DoCast(target, SPELL_FEL_LIGHTING); m_EventMap.ScheduleEvent(<API key>, urand(5 * IN_MILLISECONDS, 10 * IN_MILLISECONDS)); }break; case <API key>: { if (Unit* target = SelectTarget(<API key>, 1, 0, true)) { DoScriptText(EMOTE_INCINERATE, me, target); DoScriptText(SAY_INCINERATE, me); DoCast(target, <API key>); } m_EventMap.ScheduleEvent(<API key>, 40 * IN_MILLISECONDS); }break; case <API key>: { me->CastCustomSpell(SPELL_NETHER_POWER, <API key>, RAID_MODE<uint32>(5, 10, 5, 10), me, TRIGGERED_FULL_MASK); m_EventMap.ScheduleEvent(<API key>, 40 * IN_MILLISECONDS); }break; case <API key>: { if (Unit* target = SelectTarget(<API key>, 1, 0, true)) { DoScriptText(EMOTE_LEGION_FLAME, me, target); DoCast(target, SPELL_LEGION_FLAME); } m_EventMap.ScheduleEvent(<API key>, 30 * IN_MILLISECONDS); }break; case <API key>: { DoScriptText(EMOTE_NETHER_PORTAL, me); DoScriptText(SAY_NETHER_PORTAL, me); DoCast(SPELL_NETHER_PORTAL); m_EventMap.ScheduleEvent(<API key>, 2 * MINUTE*IN_MILLISECONDS); }break; case <API key>: { DoScriptText(<API key>, me); DoScriptText(<API key>, me); DoCast(<API key>); m_EventMap.ScheduleEvent(<API key>, 2 * MINUTE*IN_MILLISECONDS); }break; } } } private: InstanceScript* instance; EventMap m_EventMap; SummonList Summons; }; }; class mob_legion_flame : public CreatureScript { public: mob_legion_flame() : CreatureScript("mob_legion_flame") { } CreatureAI* GetAI(Creature* creature) const { return new mob_legion_flameAI(creature); } struct mob_legion_flameAI : public <API key> { mob_legion_flameAI(Creature* creature) : <API key>(creature) { Reset(); } void Reset() { me->SetFlag(UNIT_FIELD_FLAGS, <API key> | <API key>); me->SetInCombatWithZone(); DoCast(<API key>); } void UpdateAI(const uint32 /*uiDiff*/) { UpdateVictim(); } }; }; class <API key> : public CreatureScript { public: <API key>() : CreatureScript("<API key>") { } CreatureAI* GetAI(Creature* creature) const { return new <API key>(creature); } struct <API key> : public <API key> { <API key>(Creature* creature) : <API key>(creature), Summons(me) { instance = creature->GetInstanceScript(); Reset(); } InstanceScript* instance; SummonList Summons; void Reset() { me->SetReactState(REACT_PASSIVE); if (!IsHeroic()) me->SetFlag(UNIT_FIELD_FLAGS, <API key> | <API key> | UNIT_FLAG_PACIFIED); else me->RemoveFlag(UNIT_FIELD_FLAGS, <API key> | <API key> | UNIT_FLAG_PACIFIED); Summons.DespawnAll(); } void IsSummonedBy(Unit* /*summoner*/) { DoCast(<API key>); } void JustSummoned(Creature* summoned) { Summons.Summon(summoned); // makes immediate corpse despawn of summoned Felflame Infernals summoned->SetCorpseDelay(0); } void JustDied(Unit* /*killer*/) { // used to despawn corpse immediately me->DespawnOrUnsummon(); } }; }; class mob_fel_infernal : public CreatureScript { public: mob_fel_infernal() : CreatureScript("mob_fel_infernal") { } CreatureAI* GetAI(Creature* creature) const { return new mob_fel_infernalAI(creature); } struct mob_fel_infernalAI : public ScriptedAI { mob_fel_infernalAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); Reset(); } InstanceScript* instance; uint32 m_uiFelStreakTimer; void Reset() { m_uiFelStreakTimer = 30*IN_MILLISECONDS; me->SetInCombatWithZone(); } /*void SpellHitTarget(Unit* target, const SpellInfo* pSpell) { if (pSpell->Id == SPELL_FEL_STREAK) DoCastAOE(SPELL_FEL_INFERNO); //66517 }*/ void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; if (instance && instance->GetData(<API key>) != IN_PROGRESS) me->DespawnOrUnsummon(); if (m_uiFelStreakTimer <= uiDiff) { if (Unit* target = SelectTarget(<API key>, 0)) DoCast(target, SPELL_FEL_STREAK); m_uiFelStreakTimer = 30*IN_MILLISECONDS; } else m_uiFelStreakTimer -= uiDiff; <API key>(); } }; }; class mob_nether_portal : public CreatureScript { public: mob_nether_portal() : CreatureScript("mob_nether_portal") { } CreatureAI* GetAI(Creature* creature) const { return new mob_nether_portalAI(creature); } struct mob_nether_portalAI : public ScriptedAI { mob_nether_portalAI(Creature* creature) : ScriptedAI(creature), Summons(me) { instance = creature->GetInstanceScript(); Reset(); } InstanceScript* instance; SummonList Summons; void Reset() { me->SetReactState(REACT_PASSIVE); if (!IsHeroic()) me->SetFlag(UNIT_FIELD_FLAGS, <API key> | <API key> | UNIT_FLAG_PACIFIED); else me->RemoveFlag(UNIT_FIELD_FLAGS, <API key> | <API key> | UNIT_FLAG_PACIFIED); Summons.DespawnAll(); } void IsSummonedBy(Unit* /*summoner*/) { DoCast(<API key>); } void JustSummoned(Creature* summoned) { Summons.Summon(summoned); // makes immediate corpse despawn of summoned Mistress of Pain summoned->SetCorpseDelay(0); } void JustDied(Unit* /*killer*/) { // used to despawn corpse immediately me->DespawnOrUnsummon(); } }; }; enum MistressEvents { <API key> = 0, <API key>, <API key> }; class <API key> : public CreatureScript { public: <API key>() : CreatureScript("<API key>") { } CreatureAI* GetAI(Creature* creature) const { return new <API key>(creature); } struct <API key> : public ScriptedAI { <API key>(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); Reset(); } void Reset() { m_EventMap.Reset(); me->SetInCombatWithZone(); } void EnterCombat(Unit* /*victim*/) { m_EventMap.ScheduleEvent(<API key>, 30 * IN_MILLISECONDS); m_EventMap.ScheduleEvent(<API key>, 30 * IN_MILLISECONDS); if (IsHeroic()) m_EventMap.ScheduleEvent(<API key>, 15 * IN_MILLISECONDS); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; m_EventMap.Update(diff); ExecuteEvents(); <API key>(); } void ExecuteEvents() { while (uint32 eventId = m_EventMap.ExecuteEvent()) { switch (eventId) { case <API key>: { DoCastVictim(SPELL_SHIVAN_SLASH); m_EventMap.ScheduleEvent(<API key>, 30 * IN_MILLISECONDS); }break; case <API key>: { DoCastVictim(SPELL_SHIVAN_SLASH); m_EventMap.ScheduleEvent(<API key>, 30 * IN_MILLISECONDS); }break; case <API key>: { if (Unit* target = SelectTarget(<API key>, 0, 0, true)) DoCast(target, <API key>); m_EventMap.ScheduleEvent(<API key>, 15 * IN_MILLISECONDS); }break; } } } private: InstanceScript* instance; EventMap m_EventMap; }; }; void AddBossLordJaraxus() { new boss_jaraxxus(); new mob_legion_flame(); new <API key>(); new mob_fel_infernal(); new mob_nether_portal(); new <API key>(); }
<?php namespace PHPExiftool\Driver\Tag\DICOM; use PHPExiftool\Driver\AbstractTag; class <API key> extends AbstractTag { protected $Id = '0029,100A'; protected $Name = '<API key>'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Lower Range Of Pixels 1g'; }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-mac-free-3.3.8/extensions/activeqt/examples/wrapper/wrapper.doc:57 --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Standard Qt widgets as ActiveX controls (in-process)</title> <style type="text/css"><! fn { margin-left: 1cm; text-indent: -1cm; } a:link { color: #004faf; text-decoration: none } a:visited { color: #672967; text-decoration: none } body { background: #ffffff; color: black; } --></style> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr bgcolor="#E5E5E5"> <td valign=center> <a href="index.html"> <font color="#004faf">Home</font></a> | <a href="classes.html"> <font color="#004faf">All&nbsp;Classes</font></a> | <a href="mainclasses.html"> <font color="#004faf">Main&nbsp;Classes</font></a> | <a href="annotated.html"> <font color="#004faf">Annotated</font></a> | <a href="groups.html"> <font color="#004faf">Grouped&nbsp;Classes</font></a> | <a href="functions.html"> <font color="#004faf">Functions</font></a> </td> <td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>Standard Qt widgets as ActiveX controls (in-process)</h1> The ActiveX controls in this example are the standard button classes <a href="qpushbutton.html">QPushButton</a>, <a href="qcheckbox.html">QCheckBox</a> and <a href="qradiobutton.html">QRadioButton</a> as provided by Qt. <p> It demonstrates how to export existing <a href="qwidget.html">QWidget</a> classes as ActiveX controls, and the use of <a href="qaxfactory.html">QAxFactory</a> together with the <a href="qaxfactory.html#QAXFACTORY_EXPORT">QAXFACTORY_EXPORT</a> macro. <p> <pre> class ActiveQtFactory : public <a href="qaxfactory.html">QAxFactory</a> { public: ActiveQtFactory( const <a href="quuid.html">QUuid</a> &amp;lib, const <a href="quuid.html">QUuid</a> &amp;app ) : <a href="qaxfactory.html">QAxFactory</a>( lib, app ) {} <a href="qstringlist.html">QStringList</a> featureList() const { <a href="qstringlist.html">QStringList</a> list; list &lt;&lt; "QButton"; list &lt;&lt; "QCheckBox"; list &lt;&lt; "QRadioButton"; list &lt;&lt; "QPushButton"; list &lt;&lt; "QToolButton"; return list; } <a href="qwidget.html">QWidget</a> *create( const <a href="qstring.html">QString</a> &amp;key, QWidget *parent, const char *name ) { if ( key == "QButton" ) return new <a href="qbutton.html">QButton</a>( parent, name ); if ( key == "QCheckBox" ) return new <a href="qcheckbox.html">QCheckBox</a>( parent, name ); if ( key == "QRadioButton" ) return new <a href="qradiobutton.html">QRadioButton</a>( parent, name ); if ( key == "QPushButton" ) return new <a href="qpushbutton.html">QPushButton</a>( parent, name ); if ( key == "QToolButton" ) { <a href="qtoolbutton.html">QToolButton</a> *tb = new <a href="qtoolbutton.html">QToolButton</a>( parent, name ); <a name="x2463"></a> tb-&gt;<a href="qbutton.html#setPixmap">setPixmap</a>( QPixmap(fileopen) ); return tb; } return 0; } <a href="qmetaobject.html">QMetaObject</a> *metaObject( const <a href="qstring.html">QString</a> &amp;key ) const { if ( key == "QButton" ) return QButton::staticMetaObject(); if ( key == "QCheckBox" ) return QCheckBox::staticMetaObject(); if ( key == "QRadioButton" ) return QRadioButton::staticMetaObject(); if ( key == "QPushButton" ) return QPushButton::staticMetaObject(); if ( key == "QToolButton" ) return QToolButton::staticMetaObject(); return 0; } <a href="quuid.html">QUuid</a> classID( const <a href="qstring.html">QString</a> &amp;key ) const { if ( key == "QButton" ) return "{<API key>}"; if ( key == "QCheckBox" ) return "{<API key>}"; if ( key == "QRadioButton" ) return "{<API key>}"; if ( key == "QPushButton" ) return "{<API key>}"; if ( key == "QToolButton" ) return "{<API key>}"; return QUuid(); } <a href="quuid.html">QUuid</a> interfaceID( const <a href="qstring.html">QString</a> &amp;key ) const { if ( key == "QButton" ) return "{<API key>}"; if ( key == "QCheckBox" ) return "{<API key>}"; if ( key == "QRadioButton" ) return "{<API key>}"; if ( key == "QPushButton" ) return "{<API key>}"; if ( key == "QToolButton" ) return "{<API key>}"; return QUuid(); } <a href="quuid.html">QUuid</a> eventsID( const <a href="qstring.html">QString</a> &amp;key ) const { if ( key == "QButton" ) return "{<API key>}"; if ( key == "QCheckBox" ) return "{<API key>}"; if ( key == "QRadioButton" ) return "{<API key>}"; if ( key == "QPushButton" ) return "{<API key>}"; if ( key == "QToolButton" ) return "{<API key>}"; return QUuid(); } }; </pre>The factory implementation returns the list of supported controls, creates controls on request and provides information about the unique IDs of the COM classes and interfaces for each control. <p> <pre> QAXFACTORY_EXPORT( ActiveQtFactory, "{<API key>}", "{<API key>}" ) </pre>The factory is exported using the QAXFACTORY_EXPORT macro. <p> To build the example you must first build the <a href="qaxserver.html">QAxServer</a> library. Then run qmake and your make tool in <tt>examples/wrapper</tt>. <p> <hr> <p> The <a href="<API key>.html">demonstration</a> requires your WebBrowser to support ActiveX controls, and scripting to be enabled. <p> <pre> &lt;SCRIPT LANGUAGE=VBScript&gt; Sub ToolButton_Clicked() RadioButton.text = InputBox( "Enter something", "Wrapper Demo" ) End Sub Sub PushButton_clicked() MsgBox( "Thank you!" ) End Sub Sub CheckBox_toggled( state ) if state = 0 then CheckBox.text = "Check me!" else CheckBox.text = "Uncheck me!" end if End Sub &lt;/SCRIPT&gt; &lt;p&gt; A QPushButton:&lt;br&gt; &lt;object ID="PushButton" CLASSID="CLSID:<API key>" CODEBASE=http: &lt;PARAM NAME="text" VALUE="Click me!"&gt; [Object not available! Did you forget to build and register the server?] &lt;/object&gt;&lt;br&gt; &lt;p&gt; A QCheckBox:&lt;br&gt; &lt;object ID="CheckBox" CLASSID="CLSID:<API key>" CODEBASE=http: &lt;PARAM NAME="text" VALUE="Check me!"&gt; [Object not available! Did you forget to build and register the server?] &lt;/object&gt;&lt;br&gt; &lt;p&gt; A QToolButton:&lt;br&gt; &lt;object ID="ToolButton" CLASSID="CLSID:<API key>" CODEBASE=http: [Object not available! Did you forget to build and register the server?] &lt;/object&gt;&lt;br&gt; &lt;p&gt; A QRadioButton:&lt;br&gt; &lt;object ID="RadioButton" CLASSID="CLSID:<API key>" CODEBASE=http: &lt;PARAM NAME="text" VALUE="Tune me!"&gt; [Object not available! Did you forget to build and register the server?] &lt;/object&gt;&lt;br&gt; </pre><p>See also <a href="qaxserver-examples.html">The QAxServer Examples</a>. <!-- eof --> <p><address><hr><div align=center> <table width=100% cellspacing=0 border=0><tr> <td>Copyright &copy; 2007 <a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a> <td align=right><div align=right>Qt 3.3.8</div> </table></div></address></body> </html>
module.exports = angular.module('unitConv', []) .config(route) .name; route.$inject = ['$stateProvider']; function route($stateProvider) { $stateProvider.state('unitConv', { parent: 'tabs', url: '/unitConv', template: require('../doctorType/doctorType.html'), controller: require('./unitConv.controller') }); }
# Twig --vv # The theming layer ![Flow diagram of theming data](assets/images/theme-data-diagram.png) <!-- .element: style="width: 35%;" --> --vv # block.html.twig twig {% set classes = [ 'block', 'block-' ~ configuration.provider|clean_class, ] %} <div{{ attributes.addClass(classes) }}> {{ title_prefix }} {% if label %} <h2{{ title_attributes }}>{{ label }}</h2> {% endif %} {{ title_suffix }} {% block content %} {{ content }} {% endblock %} </div> --vv # breadcrumb.html.twig twig {% if breadcrumb %} <nav class="breadcrumb" role="navigation" aria-labelledby="system-breadcrumb"> <h2 id="system-breadcrumb" class="visually-hidden">{{ 'Breadcrumb'|t }}</h2> <ol> {% for item in breadcrumb %} <li> {% if item.url %} <a href="{{ item.url }}">{{ item.text }}</a> {% else %} {{ item.text }} {% endif %} </li> {% endfor %} </ol> </nav> {% endif %} --vv # Syntax - {{ ... }} Provides output <br>Outputs a render array, plain text, a variable or (twig) function result. - {% ... %} Controls <br>Examples: if, else, endif, for .. in .. - {# ... #} Does nothing <br>This is where your documentation goes. --vv # twig magic When parsing `{{ sandwich.cheese }}` Twig will try to get data using these methods (in this order): php $sandwich['cheese']; $sandwich->cheese; $sandwich->cheese(); $sandwich->getCheese(); $sandwich->isCheese(); $sandwich->__isset('cheese'); $sandwich->__get('cheese'); Examples: twig {% if node.isPublished() %} id="node-{{ node.id }}” 'node--type-' ~ node.bundle|clean_class --vv # Functions <!-- .slide: class="layout-two-col"--> twig {{ example(...) }} - Twig functions: - addClass() - removeClass() - parent() - cycle() - constant() - ~ - Drupal functions: - url() - link() - path() - url_from_path() - public methods More: http://twig.sensiolabs.org/doc/functions/index.html --vv # Filters <!-- .slide: class="layout-two-col"--> twig {{ ...|example }} - Twig filters: - join() - escape - replace() - default - abs - length - Drupal filters: - t, t() - raw - safe_join() - without() - clean_class - clean_id More: http://twig.sensiolabs.org/doc/filters/index.html --vv # node.html.twig twig {% set classes = [ 'node', 'node--type-' ~ node.bundle|clean_class, node.isPromoted() ? 'node--promoted', node.isSticky() ? 'node--sticky', not node.isPublished() ? 'node--unpublished', view_mode ? 'node--view-mode-' ~ view_mode|clean_class, ] %} <article{{ attributes.addClass(classes) }}> {{ title_prefix }} {% if not page %} <h2{{ title_attributes }}> <a href="{{ url }}" rel="bookmark">{{ label }}</a> </h2> {% endif %} {{ title_suffix }} --vv # node.html.twig twig {% if display_submitted %} <footer class="node__meta"> {{ author_picture }} <div{{ author_attributes.addClass('node__submitted') }}> {% trans %}Submitted by {{ author_name|passthrough }} on {{ date|passthrough }}{% endtrans %} {{ metadata }} </div> </footer> {% endif %} <div{{ content_attributes.addClass('node__content') }}> {{ content|without('links') }} </div> {% if content.links %} <div class="node__links"> {{ content.links }} </div> {% endif %} </article> --vv # Translation - `{{ ...|t }}` - `'...'|t({'@var': var})` - `{% trans %} ... {% endtrans %}` twig <body{{ attributes }}> <a href="#main-content" class="visually-hidden focusable"> {{ 'Skip to main content'|t }} </a> twig <div{{ author_attributes }}> {% trans %}Submitted by {{ author_name|passthrough }} on {{ date|passthrough }}{% endtrans %} {{ metadata }} </div> --vv # (Template) override ![Diagram of template override](assets/images/<API key>.png) <!-- .element: style="width: 60%;" -->
package tests.crawler; import algorithms.search.BreadthFirstSearch; import algorithms.search.UninformedSearch; import core.stocks.StockEdge; import core.stocks.StockVertex; import core.webcrawler.Crawler; import core.webcrawler.StockGraphBuilder; import edu.uci.ics.jung.graph.Graph; public class TestCrawler { public void runExample() { Crawler crawler = new Crawler(); crawler.crawl(); StockGraphBuilder sgb = new StockGraphBuilder(); Graph<StockVertex, StockEdge> graph = sgb.buildGraph(); // System.out.println(graph.getVertexCount()); // System.out.println(graph.getEdgeCount()); UninformedSearch<StockVertex, StockEdge> bfs = new BreadthFirstSearch<>(); bfs.visualizeSearch(graph, graph.getVertices().iterator().next()); } }
#include <stdio.h> #include <stdbool.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "sdlFunc.h" #include "bmp.xpm" #define MAX_POINTS 5 int main (void) { //DEGREES int mousePos[2]; //DEGREES int WidthBack, HeightBack, i, j; bool quit = 0; //const Uint8 *kbState = <API key>(NULL); char **imgFromSrc; SDL_Event e; SDL_Window *win; SDL_Renderer *ren; SDL_Texture *background; SDL_Texture *arrow; if (SDL_Init(SDL_INIT_VIDEO) != 0 || (IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG) { logSDLError("Init"); return 1; } win = SDL_CreateWindow( "Arrow click n stuffs", WINDOW_OFFSET_X, WINDOW_OFFSET_Y, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL | <API key> | <API key> | <API key> ); if (win == NULL) { logSDLError("CreateWindow"); return 2; } ren = SDL_CreateRenderer(win, -1, <API key> | <API key>); if (ren == NULL) { logSDLError("CreateRenderer"); return 3; } imgFromSrc = bmp_xpm; background = loadHeader(imgFromSrc, ren); arrow = loadTexture("arrow.png", ren); if (background == NULL || arrow == NULL) { logSDLError("loadTexture"); return 4; } SDL_RenderClear(ren); SDL_QueryTexture(background, NULL, NULL, &WidthBack, &HeightBack); WidthBack /= 2; HeightBack /= 2; for (i = 0; i < WINDOW_WIDTH / WidthBack; i++) { for (j = 0; j <= WINDOW_HEIGHT / HeightBack; j++) { renderTextureS(background, ren, i * WidthBack, j * HeightBack, WidthBack, HeightBack); } } SDL_RenderPresent(ren); while (!quit) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) quit = 1; if (e.type == SDL_MOUSEBUTTONDOWN) { //quit = 1; mousePos[0] = e.motion.x; mousePos[1] = e.motion.y; } } SDL_RenderClear(ren); for (i = 0; i < WINDOW_WIDTH / WidthBack; i++) { for (j = 0; j <= WINDOW_HEIGHT / HeightBack; j++) { renderTextureS(background, ren, i * WidthBack, j * HeightBack, WidthBack, HeightBack); } } renderTextureR(arrow, ren, mousePos, WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); SDL_RenderPresent(ren); } SDL_DestroyTexture(background); SDL_DestroyTexture(arrow); cleanUp(win, ren); return 0; }
#ifndef MANGOS_TOTEMAI_H #define MANGOS_TOTEMAI_H #include "CreatureAI.h" #include "ObjectGuid.h" #include "Timer.h" class Creature; class Totem; class TotemAI : public CreatureAI { public: explicit TotemAI(Creature* c); void MoveInLineOfSight(Unit*) override; void AttackStart(Unit*) override; void EnterEvadeMode() override; bool IsVisible(Unit*) const override; void UpdateAI(const uint32) override; static int Permissible(const Creature*); protected: Totem& getTotem(); private: ObjectGuid i_victimGuid; }; #endif
<?php define('<API key>', 'Sous-total'); define('<API key>', 'Sous-total, net'); define('<API key>', 'Sous-total de la commande'); define('<API key>','Afficher sous-total'); define('<API key>','Voulez-vous afficher le coût total partiel de la commande ?'); define('<API key>','Ordre de tri'); define('<API key>','séquence de présentation'); ?>
TODO = * Handle multiple users i.e. allow disabling scrobbling for some users
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>Milo: nodes.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Milo &#160;<span id="projectnumber">0.1</span> </div> <div id="projectbrief">Milo:<API key></div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> </div> <div class="headertitle"> <div class="title">nodes.h File Reference</div> </div> </div><!--header <div class="contents"> <div class="textblock"><code>#include &lt;vector&gt;</code><br /> <code>#include &lt;exception&gt;</code><br /> <code>#include &lt;unordered_map&gt;</code><br /> <code>#include &quot;<a class="el" href="milo_8h_source.html">milo.h</a>&quot;</code><br /> </div><div class="textblock"><div class="dynheader"> Include dependency graph for nodes.h:</div> <div class="dyncontent"> <div class="center"><img src="nodes_8h__incl.png" border="0" usemap="#nodes_8h" alt=""/></div> <map name="nodes_8h" id="nodes_8h"> <area shape="rect" id="node5" href="milo_8h.html" title="milo.h" alt="" coords="605,80,663,107"/> <area shape="rect" id="node15" href="util_8h.html" title="util.h" alt="" coords="839,155,890,181"/> <area shape="rect" id="node18" href="xml_8h.html" title="xml.h" alt="" coords="191,155,245,181"/> <area shape="rect" id="node21" href="smart_8h.html" title="smart.h" alt="" coords="1030,155,1097,181"/> </map> </div> </div><div class="textblock"><div class="dynheader"> This graph shows which files directly or indirectly include this file:</div> <div class="dyncontent"> <div class="center"><img src="nodes_8h__dep__incl.png" border="0" usemap="#nodes_8hdep" alt=""/></div> <map name="nodes_8hdep" id="nodes_8hdep"> <area shape="rect" id="node2" href="nodes_8cpp.html" title="nodes.cpp" alt="" coords="5,80,88,107"/> <area shape="rect" id="node3" href="parser_8cpp.html" title="parser.cpp" alt="" coords="112,80,195,107"/> </map> </div> </div> <p><a href="nodes_8h_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classBinary.html">Binary</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classDivide.html">Divide</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classPower.html">Power</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classConstant.html">Constant</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classVariable.html">Variable</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classNumber.html">Number</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFunction.html">Function</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classDifferential.html">Differential</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>This file defines the classes that make up the nodes in an equation tree. They derive from the abstract base class <a class="el" href="classNode.html">Node</a> and need to implement the virtual member functions. This header file is not part of the external interface. </p> </div></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
pyfix == Pyfix is still very much a work in progress. The goal is to have it be a small but usable FIX (Financial Information eXchange) engine written in python. The purpose of the engine is to handle the FIX protocol logic and overhead between a financial exchange and local trading application or interface. Pyfix is intended to be suitable for amatuer/hobbiest usage, not necessarily full compliance with the FIX protocol. I am currently targeting FIX4.4. The engine is written in Python 3 using the asyncio framework.
<!DOCTYPE html> <html> <head> <title>Horse Quest: The Dawn of Beasts [BETA]</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script src="lib/crafty.js"></script> <script src="src/horseRacer.js.php"></script> <script> window.addEventListener('load', Game.start); </script> <style type="text/css" media="screen"> body { background: black; } #log { position:absolute; right: 20px; width:200px; background-color: white; height:700px; overflow: auto; } .choice{ color:#CCC; } .dialogChoice{ cursor: pointer; color:#CCC; } .dialogChoice:hover, .chosenDialogChoice{ color:#FFF; } </style> </head> <body> <div id="log"></div> </body> </html>
<?php define('NAVBAR_TITLE', 'Registro de afiliado'); define('HEADING_TITLE', '¡Enhorabuena!'); define('<API key>', '¡Enhorabuena! Su petición para una cuenta de nuevo afiliado ha sido enviada. En breve recibirá un email conteniendo información importante acerca de su cuenta de afiliado, incluyendo detalles sobre el inicio de sesión de afiliado. Si no recibiera este email en una hora, por favor '); define('TEXT_CONTACT_US', 'contacte con nosotros'); ?>
<?php //<API key>(TIME_ZONE_SET); $format = '%Y-%m-%d %H:%M:%S'; $database->setDatetime( strftime($format) ); ?>
import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): # __unicode__ on Python 2 return self.question_text def <API key>(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now <API key>.admin_order_field = 'pub_date' <API key>.boolean = True <API key>.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __unicode__(self): # __unicode__ on Python 2 return self.choice_text
<?php defined('_JEXEC') or die; $classes = "azp_iconbox iconbox_imageicon2"; $animationData = ''; if($animationArgs['animation'] == '1'){ $classes .= ' animate-in'; $animationData = 'data-anim-type="'.$animationArgs['animationtype'].'" data-anim-delay="'.$animationArgs['animationdelay'].'"'; } if(!empty($extraclass)){ $classes .= ' '.$extraclass; } if($isactive === '1'){ $classes .= ' active'; } $classes = 'class="'.$classes.'"'; ?> <div <?php echo $classes.' '.$iconboxstyle.' '.$animationData;?>> <?php if(!empty($link)) :?> <a href="<?php echo $link;?>"> <?php else :?> <a href="javascript:void(0);"> <?php endif;?> <?php if(!empty($iconclass)) :?> <i class="<?php echo $iconclass;?>"></i> <?php elseif(!empty($image)) :?> <img src="<?php echo JURI::root(true).'/'.$image;?>" class="hoxa-img-icon" alt="<?php echo $title;?>"> <?php endif;?> <?php if(!empty($title)) :?> <strong><?php echo $title;?></strong> <?php endif;?> <?php echo $content;?> </a> </div>
/* ScriptData SDName: Boss_Hakkar SD%Complete: 95 SDComment: Blood siphon spell buggy cause of Core Issue. SDCategory: Zul'Gurub EndScriptData */ #include "precompiled.h" #include "zulgurub.h" enum { SAY_AGGRO = -1309020, SAY_FLEEING = -1309021, SPELL_BLOOD_SIPHON = 24324, // Related Spells 24322, 24323, 24324, likely starting spell is 24324 (disabled until proper fixed) <API key> = 24328, <API key> = 24327, <API key> = 24178, SPELL_ENRAGE = 24318, // The Aspects of all High Priests <API key> = 24687, <API key> = 24688, <API key> = 24686, <API key> = 24689, <API key> = 24690 }; struct MANGOS_DLL_DECL boss_hakkarAI : public ScriptedAI { boss_hakkarAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; uint32 <API key>; uint32 <API key>; uint32 <API key>; uint32 <API key>; uint32 m_uiEnrageTimer; uint32 <API key>; uint32 <API key>; uint32 <API key>; uint32 <API key>; uint32 <API key>; void Reset() { <API key> = 90000; <API key> = 25000; <API key> = 17000; <API key> = 17000; m_uiEnrageTimer = 10*MINUTE*IN_MILLISECONDS; <API key> = 4000; <API key> = 7000; <API key> = 12000; <API key> = 8000; <API key> = 18000; } void Aggro(Unit *who) { DoScriptText(SAY_AGGRO, m_creature); // check if the priest encounters are done if (m_pInstance) { if (m_pInstance->GetData(TYPE_JEKLIK) == DONE) <API key> = 0; if (m_pInstance->GetData(TYPE_VENOXIS) == DONE) <API key> = 0; if (m_pInstance->GetData(TYPE_MARLI) == DONE) <API key> = 0; if (m_pInstance->GetData(TYPE_THEKAL) == DONE) <API key> = 0; if (m_pInstance->GetData(TYPE_ARLOKK) == DONE) <API key> = 0; } } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; /* Disabled as needs core fix// Blood Siphon Timer * This also will requre spells 24320 24321 to be implemented (and used by the "Son of Hakkar" npcs) if (<API key> < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_BLOOD_SIPHON) == CAST_OK) <API key> = 90000; } else <API key> -= uiDiff; */ // Corrupted Blood Timer if (<API key> < uiDiff) { if (Unit* pTarget = m_creature-><API key>(<API key>, 0)) { if (DoCastSpellIfCan(pTarget, <API key>) == CAST_OK) <API key> = urand(30000, 45000); } } else <API key> -= uiDiff; // Cause Insanity Timer if (<API key> < uiDiff) { if (m_creature->getThreatManager().getThreatList().size() > 1) { if (DoCastSpellIfCan(m_creature->getVictim(), <API key>) == CAST_OK) <API key> = urand(10000, 15000); } else // Solo case, check again later <API key> = urand(35000, 43000); } else <API key> -= uiDiff; // Will Of Hakkar Timer if (<API key> < uiDiff) { if (Unit* pTarget = m_creature-><API key>(<API key>, 1)) { if (DoCastSpellIfCan(pTarget, <API key>) == CAST_OK) <API key> = urand(25000, 35000); } else // solo attempt, try again later <API key> = 25000; } else <API key> -= uiDiff; if (m_uiEnrageTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE) == CAST_OK) m_uiEnrageTimer = 10*MINUTE*IN_MILLISECONDS; } else m_uiEnrageTimer -= uiDiff; // Checking if Jeklik is dead. If not we cast her Aspect if (<API key>) { if (<API key> <= uiDiff) { if (DoCastSpellIfCan(m_creature, <API key>) == CAST_OK) <API key> = urand(10000, 14000); } else <API key> -= uiDiff; } // Checking if Venoxis is dead. If not we cast his Aspect if (<API key>) { if (<API key> <= uiDiff) { if (DoCastSpellIfCan(m_creature, <API key>) == CAST_OK) <API key> = 8000; } else <API key> -= uiDiff; } // Checking if Marli is dead. If not we cast her Aspect if (<API key>) { if (<API key> <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), <API key>) == CAST_OK) <API key> = 10000; } else <API key> -= uiDiff; } // Checking if Thekal is dead. If not we cast his Aspect if (<API key>) { if (<API key> <= uiDiff) { if (DoCastSpellIfCan(m_creature, <API key>) == CAST_OK) <API key> = 15000; } else <API key> -= uiDiff; } // Checking if Arlokk is dead. If yes we cast her Aspect if (<API key>) { if (<API key> <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), <API key>) == CAST_OK) { DoResetThreat(); <API key> = urand(10000, 15000); } } else <API key> -= uiDiff; } <API key>(); } }; CreatureAI* GetAI_boss_hakkar(Creature* pCreature) { return new boss_hakkarAI(pCreature); } void AddSC_boss_hakkar() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_hakkar"; pNewScript->GetAI = &GetAI_boss_hakkar; pNewScript->RegisterSelf(); }
<?php $gacode = vp_option('joption.<API key>'); if(!empty($gacode)) { ?> <script> var _gaq = _gaq || []; _gaq.push(['_setAccount', '<?php echo esc_js( $gacode ); ?>']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https: var s = document.<API key>('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <?php } ?>
<?php /** * Tests updating a points reaction. * * @package WordPoints\Codeception * @since 2.1.0 */ use WordPoints\Tests\Codeception\Element\Reaction; $I = new AcceptanceTester( $scenario ); $I->wantTo( 'Update a points reaction' ); $the_reaction = $I-><API key>(); $reaction = new Reaction( $I, $the_reaction ); $I-><API key>( 'wp-admin/admin.php?page=<API key>' ); $I->see( 'Test description.', "{$reaction} .title" ); $reaction->edit(); $I->canSeeInFormFields( "{$reaction} form" , array( 'description' => 'Test description.', 'log_text' => 'Test log text.', 'points' => '10', ) ); $I->fillField( "{$reaction} [name=description]", 'Registering.' ); $I->fillField( "{$reaction} [name=log_text]", 'Registration.' ); $I->fillField( "{$reaction} [name=points]", '50' ); $reaction->save(); $I->canSeeInFormFields( "{$reaction} form" , array( 'description' => 'Registering.', 'log_text' => 'Registration.', 'points' => '50', ) ); $I->see( 'Registering.', "{$reaction} .title" ); // EOF
<?php include 'session_login.php'; /* Database connection start */ include 'db.php'; include 'sanitasi.php'; // storing request (ie, get/post) global array to a variable $requestData= $_REQUEST; $columns = array( // datatable column index => database column name 0 => 'url_data_pasien', 1 => 'url_cari_pasien', 2 => 'id' ); // getting total number records without any search $sql = "SELECT id, url_cari_pasien, url_data_pasien "; $sql.=" FROM <API key>"; $query=mysqli_query($conn, $sql) or die("<API key>.php: get employees"); $totalData = mysqli_num_rows($query); $totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows. $sql = "SELECT id, url_cari_pasien, url_data_pasien "; $sql.=" FROM <API key> WHERE 1=1"; if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter $sql.=" AND ( url_data_pasien LIKE '".$requestData['search']['value']."%' "; $sql.=" OR url_cari_pasien LIKE '".$requestData['search']['value']."%' )"; } $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. $sql.=" ORDER BY id ASC LIMIT ".$requestData['start']." ,".$requestData['length']." "; /* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */ $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); $data = array(); $no_urut = 1; while( $row=mysqli_fetch_array($query) ) { // preparing an array $nestedData=array(); $nestedData[] = $no_urut++."."; $nestedData[] = "<p class='edit-cari' data-id='".$row['id']."'><span id='text-cari-".$row['id']."'>". $row['url_cari_pasien'] ."</span> <input type='hidden' id='input-cari-".$row['id']."' value='".$row['url_cari_pasien']."' class='input_cari' data-id='".$row['id']."' data-cari='".$row['url_cari_pasien']."' autofocus=''></p>"; $nestedData[] = "<p class='edit-data' data-id='".$row['id']."'><span id='text-data-".$row['id']."'>". $row['url_data_pasien'] ."</span> <input type='hidden' id='input-data-".$row['id']."' value='".$row['url_data_pasien']."' class='input_data' data-id='".$row['id']."' data-data='".$row['url_data_pasien']."' autofocus=''></p>"; $nestedData[] = $row["id"]; $data[] = $nestedData; } $json_data = array( "draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. "recordsTotal" => intval( $totalData ), // total number of records "recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData "data" => $data // total data array ); echo json_encode($json_data); // send data as json format ?>
import {LogEngine} from "../../../../../lib/log/LogEngine"; import {Logger} from "../../../../../lib/log/Logger"; import {IChatEvent} from "../../../../events/IChatEvent"; import {ISoapEventObject} from "../SoapEventParser"; export abstract class SoapEventDecoder<T extends IChatEvent> { public Log: Logger; private mEventCode: number; constructor(eventCode: number) { this.mEventCode = eventCode; this.Log = LogEngine.getLogger(LogEngine.CHAT); } public getEventCode(): number { return this.mEventCode; } public abstract decodeEvent(eventObj: ISoapEventObject, originEvent?: IChatEvent): T; }
OCCModule.factory('EpochService', function ($resource, Settings) { return OCCModule.CrudService($resource, 'epoch', Settings); });
#ifndef <API key> #define <API key> #include "gui/widgets/window.h" #include "listeners/actionlistener.h" #include "listeners/selectionlistener.h" class Button; class Item; class Label; class ScrollArea; class ShopItems; class ShopListBox; class Slider; /** * The sell dialog. * * \ingroup Interface */ class SellDialog notfinal : public Window, public ActionListener, private SelectionListener { public: /** * Constructor. */ explicit SellDialog(const bool isSell); A_DELETE_COPY(SellDialog) /** * Destructor */ ~SellDialog(); /** * Resets the dialog, clearing inventory. */ void reset(); /** * Adds an item to the inventory. */ void addItem(const Item *const item, const int price); /** * Called when receiving actions from the widgets. */ void action(const ActionEvent &event) override final; /** * Updates labels according to selected item. * * @see SelectionListener::selectionChanged */ void valueChanged(const SelectionEvent &event) override final; /** * Gives Player's Money amount */ void setMoney(const int amount); /** * Sets the visibility of this window. */ void setVisible(Visible visible) override final; void addItem(const int id, const int type, const unsigned char color, const int amount, const int price); /** * Returns true if any instances exist. */ static bool isActive() A_WARN_UNUSED { return !instances.empty(); } /** * Closes all instances. */ static void closeAll(); void postInit() override; protected: typedef std::list<SellDialog*> DialogList; static DialogList instances; /** * Updates the state of buttons and labels. */ void <API key>(); virtual void sellAction(const ActionEvent &event) = 0; virtual void initButtons() { } Button *mSellButton; Button *mQuitButton; Button *mAddMaxButton; Button *mIncreaseButton; Button *mDecreaseButton; ShopListBox *mShopItemList; ScrollArea *mScrollArea; Label *mMoneyLabel; Label *mQuantityLabel; Slider *mSlider; ShopItems *mShopItems; int mPlayerMoney; int mMaxItems; int mAmountItems; bool mIsSell; }; #endif // <API key>
<?php namespace Steve\FrontendBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class <API key> extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
#include <linux/fs.h> #include <linux/module.h> #include <linux/miscdevice.h> #include <linux/mutex.h> #include <linux/sched.h> #include <linux/uaccess.h> #include <linux/wait.h> #include <linux/msm_audio.h> #include <linux/debugfs.h> #include <linux/list.h> #include <linux/slab.h> #include <linux/ion.h> #include <asm/ioctls.h> #include <asm/atomic.h> #include "q6audio_common.h" #define TUNNEL_MODE 0x0000 #define NON_TUNNEL_MODE 0x0001 #define <API key> 0x00000001 /* AIO interface */ #define ADRV_STATUS_FSYNC 0x00000008 #define ADRV_STATUS_PAUSE 0x00000010 #define AUDIO_DEC_EOS_SET 0x00000001 #define AUDIO_EVENT_NUM 10 #define __CONTAINS(r, v, l) ({ \ typeof(r) __r = r; \ typeof(v) __v = v; \ typeof(v) __e = __v + l; \ int res = ((__v >= __r->vaddr) && \ (__e <= __r->vaddr + __r->len)); \ res; \ }) #define CONTAINS(r1, r2) ({ \ typeof(r2) __r2 = r2; \ __CONTAINS(r1, __r2->vaddr, __r2->len); \ }) #define IN_RANGE(r, v) ({ \ typeof(r) __r = r; \ typeof(v) __vv = v; \ int res = ((__vv >= __r->vaddr) && \ (__vv < (__r->vaddr + __r->len))); \ res; \ }) #define OVERLAPS(r1, r2) ({ \ typeof(r1) __r1 = r1; \ typeof(r2) __r2 = r2; \ typeof(__r2->vaddr) __v = __r2->vaddr; \ typeof(__v) __e = __v + __r2->len - 1; \ int res = (IN_RANGE(__r1, __v) || IN_RANGE(__r1, __e)); \ res; \ }) struct timestamp { unsigned long lowpart; unsigned long highpart; } __packed; struct meta_out_dsp { u32 offset_to_frame; u32 frame_size; u32 encoded_pcm_samples; u32 msw_ts; u32 lsw_ts; u32 nflags; } __packed; struct dec_meta_in { unsigned char reserved[18]; unsigned short offset; struct timestamp ntimestamp; unsigned int nflags; } __packed; struct dec_meta_out { unsigned int reserved[7]; unsigned int num_of_frames; struct meta_out_dsp meta_out_dsp[]; } __packed; /* General meta field to store meta info locally */ union meta_data { struct dec_meta_out meta_out; struct dec_meta_in meta_in; } __packed; #define PCM_BUF_COUNT (2) /* Buffer with meta */ #define PCM_BUFSZ_MIN ((4*1024) + sizeof(struct dec_meta_out)) /* FRAME_NUM must be a power of two */ #define FRAME_NUM (2) #define FRAME_SIZE ((4*1536) + sizeof(struct dec_meta_in)) struct <API key> { struct list_head list; struct ion_handle *handle; int fd; void *vaddr; unsigned long paddr; unsigned long kvaddr; unsigned long len; unsigned ref_cnt; }; struct audio_aio_event { struct list_head list; int event_type; union <API key> payload; }; struct <API key> { struct list_head list; struct msm_audio_aio_buf buf; unsigned long paddr; unsigned long token; void *kvaddr; union meta_data meta_info; }; struct q6audio_aio; struct <API key> { void (*out_flush) (struct q6audio_aio *); void (*in_flush) (struct q6audio_aio *); }; struct q6audio_aio { atomic_t in_bytes; atomic_t in_samples; struct <API key> str_cfg; struct msm_audio_buf_cfg buf_cfg; struct msm_audio_config pcm_cfg; void *codec_cfg; struct audio_client *ac; struct mutex lock; struct mutex read_lock; struct mutex write_lock; struct mutex get_event_lock; wait_queue_head_t cmd_wait; wait_queue_head_t write_wait; wait_queue_head_t event_wait; spinlock_t dsp_lock; spinlock_t event_queue_lock; #ifdef CONFIG_DEBUG_FS struct dentry *dentry; #endif struct list_head out_queue; /* queue to retain output buffers */ struct list_head in_queue; /* queue to retain input buffers */ struct list_head free_event_queue; struct list_head event_queue; struct list_head ion_region_queue; /* protected by lock */ struct ion_client *client; struct <API key> drv_ops; union <API key> eos_write_payload; uint32_t drv_status; int event_abort; int eos_rsp; int eos_flag; int opened; int enabled; int stopped; int feedback; int rflush; /* Read flush */ int wflush; /* Write flush */ long (*codec_ioctl)(struct file *, unsigned int, unsigned long); }; void <API key>(struct q6audio_aio *audio, uint32_t token, uint32_t *payload); void <API key>(struct q6audio_aio *audio, uint32_t token, uint32_t *payload); int insert_eos_buf(struct q6audio_aio *audio, struct <API key> *buf_node); void <API key>(struct q6audio_aio *audio, struct <API key> *buf_node, int dir); int audio_aio_open(struct q6audio_aio *audio, struct file *file); int audio_aio_enable(struct q6audio_aio *audio); void <API key>(struct q6audio_aio *audio, int type, union <API key> payload); int audio_aio_release(struct inode *inode, struct file *file); long audio_aio_ioctl(struct file *file, unsigned int cmd, unsigned long arg); int audio_aio_fsync(struct file *file, loff_t start, loff_t end, int datasync); void <API key>(struct q6audio_aio *audio); void <API key>(struct q6audio_aio *audio); #if 1 void <API key>(struct q6audio_aio *audio); #endif #ifdef CONFIG_DEBUG_FS ssize_t <API key>(struct inode *inode, struct file *file); ssize_t <API key>(struct file *file, char __user *buf, size_t count, loff_t *ppos); #endif
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-7078796-5']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https: var s = document.<API key>('script')[0]; s.parentNode.insertBefore(ga, s); })();
<?php /** * Register all actions and filters for the plugin. * * Maintain a list of all hooks that are registered throughout * the plugin, and register them with the WordPress API. Call the * run function to execute the list of actions and filters. * * @package Wsi * @subpackage Wsi/includes * @author Damian Logghe <info@timersys.com> */ class Wsi_Loader { /** * The array of actions registered with WordPress. * * @since 2.5.0 * @access protected * @var array $actions The actions registered with WordPress to fire when the plugin loads. */ protected $actions; /** * The array of filters registered with WordPress. * * @since 2.5.0 * @access protected * @var array $filters The filters registered with WordPress to fire when the plugin loads. */ protected $filters; /** * Initialize the collections used to maintain the actions and filters. * * @since 2.5.0 */ public function __construct() { $this->actions = array(); $this->filters = array(); } /** * Add a new action to the collection to be registered with WordPress. * * @since 2.5.0 * @var string $hook The name of the WordPress action that is being registered. * @var object $component A reference to the instance of the object on which the action is defined. * @var string $callback The name of the function definition on the $component. * @var int Optional $priority The priority at which the function should be fired. * @var int Optional $accepted_args The number of arguments that should be passed to the $callback. */ public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args ); } /** * Add a new filter to the collection to be registered with WordPress. * * @since 2.5.0 * @var string $hook The name of the WordPress filter that is being registered. * @var object $component A reference to the instance of the object on which the filter is defined. * @var string $callback The name of the function definition on the $component. * @var int Optional $priority The priority at which the function should be fired. * @var int Optional $accepted_args The number of arguments that should be passed to the $callback. */ public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args ); } /** * A utility function that is used to register the actions and hooks into a single * collection. * * @since 2.5.0 * @access private * @var array $hooks The collection of hooks that is being registered (that is, actions or filters). * @var string $hook The name of the WordPress filter that is being registered. * @var object $component A reference to the instance of the object on which the filter is defined. * @var string $callback The name of the function definition on the $component. * @var int Optional $priority The priority at which the function should be fired. * @var int Optional $accepted_args The number of arguments that should be passed to the $callback. * @return type The collection of actions and filters registered with WordPress. */ private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) { $hooks[] = array( 'hook' => $hook, 'component' => $component, 'callback' => $callback, 'priority' => $priority, 'accepted_args' => $accepted_args ); return $hooks; } /** * Register the filters and actions with WordPress. * * @since 2.5.0 */ public function run() { foreach ( $this->filters as $hook ) { add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } foreach ( $this->actions as $hook ) { add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } } }
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. # Use Unicode::UCD::prop_invlist() to access the contents of this file. # This file returns the 1246 code points in Unicode Version 6.1.0 that match # any of the following regular expression constructs: # \p{Script_Extensions=Yi} # \p{Scx=Yiii} # perluniprops.pod should be consulted for the syntax rules for any of these, # including if adding or subtracting white space, underscore, and hyphen # characters matters or doesn't matter, and other permissible syntactic # variants. Upper/lower case distinctions never matter. # A colon can be substituted for the equals sign, and anything to the left of # the equals (or colon) can be combined with anything to the right. Thus, # for example, # \p{Scx: Yi} # is also valid. # The format of the lines of this file is: START\tSTOP\twhere START is the # starting code point of the range, in hex; STOP is the ending point, or if # omitted, the range has just one code point. Numbers in comments in # [brackets] indicate how many code points are in the range. return <<'END'; 3001 3002 3008 3011 3014 301B 30FB A000 A48C # [1165] A490 A4C6 FF61 FF65 END
<?php defined('MOLAJO') or die; /** * Component Display Model * * <API key> extends MolajoModelDisplay extends JModel extends JObject * * @package Molajo * @subpackage Model * @since 1.6 */ class <API key> extends MolajoModelDisplay {}
<?php if ( !defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } do_action( '<API key>' ); <API key>( array( "crm-entity-" . $entity->logicalname ), $form->uid ); <API key>( apply_filters( "<API key>", $form->errors ) ); <API key>( apply_filters( "<API key>", $form->notices ) ); do_action( '<API key>' ); if ( $form->showform ) { foreach ( $form->controls as $column ) { if ( !empty( $column["controls"] ) ) { foreach ( $column["controls"] as $control ) { if ( $mode == "readonly" ) { <API key>( $control ); } else { wordpresscrm_field( $control ); } } } } if ( $mode != "readonly" ) { if ( $captcha && $form->captcha->enable_captcha ) { <API key>(); ?><div class="g-recaptcha" data-sitekey="<?php echo $form->captcha->sitekey ?>"></div><?php <API key>(); } <API key>(); <API key>( array( "form" => $form, 'entity' => $entity ) ); <API key>(); } } do_action( '<API key>' ); <API key>(); <API key>( $form->uid, $form ); do_action( '<API key>', $form );
# Searches through files in file browser by name. # This program is free software; you can redistribute it and/or # as published by the Free Software Foundation; either version 2 # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. bl_info = { "name": "Add-ons Tools", "author": "Jakub Zolcik", "version": (0, 0, 1), "blender": (2, 72, 0), "location": "File", "description": "Allows enabling add-ons according to *.blend files.", "warning": "", "wiki_url": "https://studio.allblue.pl/wiki/wikis/blender/addons-tools", "tracker_url": "https://github.com/sftd/<API key>", "category": "System" } import bpy import addon_utils from bpy.app.handlers import persistent class <API key>(bpy.types.AddonPreferences): bl_idname = __name__ load = bpy.props.BoolProperty('Load Add-ons automatically', default=True) def draw(self, context): layout = self.layout layout.label('Addons Tools Preferences') layout.prop(self, 'load', text='Load Add-ons automatically') class ADTAddonItem(bpy.types.PropertyGroup): module = bpy.props.StringProperty(name="Module", default='') def adt_enable_addons(): context = bpy.context scene = bpy.data.scenes[0] enabled_addons = context.user_preferences.addons.keys() for adt_addon in scene.adt_addons: if (adt_addon.module not in enabled_addons): bpy.ops.wm.addon_enable(module=adt_addon.module) class <API key>(bpy.types.Operator): bl_idname = "wm.adt_enable_addons" bl_label = "ADT Enable Add-ons" def execute(self, context): adt_enable_addons() return {"FINISHED"} def adt_menu_draw(self, context): self.layout.operator("wm.adt_enable_addons", icon='LOAD_FACTORY') if (context.window_manager.adt_save): self.layout.prop(context.window_manager, "adt_save", text="ADT Save Add-ons", icon='CHECKBOX_HLT') else: self.layout.prop(context.window_manager, "adt_save", text="ADT Save Add-ons", icon='CHECKBOX_DEHLT') self.layout.separator() def adt_save_update(self, context): scene = bpy.data.scenes[0] scene.adt_save = context.window_manager.adt_save @persistent def <API key>(dummy): context = bpy.context scene = bpy.data.scenes[0] scene.adt_save = context.window_manager.adt_save scene.adt_addons.clear() if (not context.window_manager.adt_save): return for addon in context.user_preferences.addons: adt_addon = scene.adt_addons.add() adt_addon.module = addon.module @persistent def <API key>(dummy): context = bpy.context adt_preferences = context.user_preferences.addons['ab_addons_tools'].preferences context.window_manager.adt_save = bpy.data.scenes[0].adt_save if (adt_preferences.load): adt_enable_addons() def register(): # Apparently need to register does classes before Add-on registers them. bpy.utils.register_class(<API key>) bpy.utils.register_class(ADTAddonItem) bpy.utils.register_class(<API key>) bpy.types.INFO_MT_file.prepend(adt_menu_draw) adt_preferences = bpy.context.user_preferences.addons[__name__].preferences # Properties bpy.types.Scene.adt_addons = bpy.props.CollectionProperty(type=ADTAddonItem) bpy.types.Scene.adt_save = bpy.props.BoolProperty('ADT Save Add-ons', default=True) bpy.types.WindowManager.adt_save = bpy.props.BoolProperty('ADT Save Add-ons', default=True, update=adt_save_update) bpy.app.handlers.save_pre.append(<API key>); bpy.app.handlers.load_post.append(<API key>) def unregister(): bpy.utils.unregister_class(<API key>) bpy.utils.unregister_class(ADTAddonItem) bpy.utils.unregister_class(<API key>) bpy.types.INFO_MT_file.remove(adt_menu_draw) bpy.app.handlers.save_pre.remove(<API key>); bpy.app.handlers.load_post.remove(<API key>) del bpy.types.Scene.adt_addons del bpy.types.Scene.adt_save del bpy.types.WindowManager.adt_save
/** @file * * VirtualBox API class wrapper header for IGuestSession. * * DO NOT EDIT! This is a generated file. * Generated from: src/VBox/Main/idl/VirtualBox.xidl * Generator: src/VBox/Main/idl/apiwrap-server.xsl */ #ifndef GuestSessionWrap_H_ #define GuestSessionWrap_H_ #include "VirtualBoxBase.h" #include "Wrapper.h" class ATL_NO_VTABLE GuestSessionWrap: public VirtualBoxBase, <API key>(IGuestSession) { Q_OBJECT public: <API key>(GuestSessionWrap, IGuestSession) <API key>(GuestSessionWrap) <API key>() BEGIN_COM_MAP(GuestSessionWrap) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IGuestSession) <API key>(IDispatch, IGuestSession) END_COM_MAP() <API key>(GuestSessionWrap) // public IGuestSession properties STDMETHOD(COMGETTER(User))(BSTR *aUser); STDMETHOD(COMGETTER(Domain))(BSTR *aDomain); STDMETHOD(COMGETTER(Name))(BSTR *aName); STDMETHOD(COMGETTER(Id))(ULONG *aId); STDMETHOD(COMGETTER(Timeout))(ULONG *aTimeout); STDMETHOD(COMSETTER(Timeout))(ULONG aTimeout); STDMETHOD(COMGETTER(ProtocolVersion))(ULONG *aProtocolVersion); STDMETHOD(COMGETTER(Status))(<API key> *aStatus); STDMETHOD(COMGETTER(Environment))(ComSafeArrayOut(BSTR, aEnvironment)); STDMETHOD(COMSETTER(Environment))(ComSafeArrayIn(IN_BSTR, aEnvironment)); STDMETHOD(COMGETTER(Processes))(ComSafeArrayOut(IGuestProcess *, aProcesses)); STDMETHOD(COMGETTER(Directories))(ComSafeArrayOut(IGuestDirectory *, aDirectories)); STDMETHOD(COMGETTER(Files))(ComSafeArrayOut(IGuestFile *, aFiles)); STDMETHOD(COMGETTER(EventSource))(IEventSource **aEventSource); // public IGuestSession methods STDMETHOD(Close)(); STDMETHOD(CopyFrom)(IN_BSTR aSource, IN_BSTR aDest, ComSafeArrayIn(CopyFileFlag_T, aFlags), IProgress **aProgress); STDMETHOD(CopyTo)(IN_BSTR aSource, IN_BSTR aDest, ComSafeArrayIn(CopyFileFlag_T, aFlags), IProgress **aProgress); STDMETHOD(DirectoryCreate)(IN_BSTR aPath, ULONG aMode, ComSafeArrayIn(<API key>, aFlags)); STDMETHOD(DirectoryCreateTemp)(IN_BSTR aTemplateName, ULONG aMode, IN_BSTR aPath, BOOL aSecure, BSTR *aDirectory); STDMETHOD(DirectoryExists)(IN_BSTR aPath, BOOL *aExists); STDMETHOD(DirectoryOpen)(IN_BSTR aPath, IN_BSTR aFilter, ComSafeArrayIn(DirectoryOpenFlag_T, aFlags), IGuestDirectory **aDirectory); STDMETHOD(DirectoryQueryInfo)(IN_BSTR aPath, IGuestFsObjInfo **aInfo); STDMETHOD(DirectoryRemove)(IN_BSTR aPath); STDMETHOD(<API key>)(IN_BSTR aPath, ComSafeArrayIn(<API key>, aFlags), IProgress **aProgress); STDMETHOD(DirectoryRename)(IN_BSTR aSource, IN_BSTR aDest, ComSafeArrayIn(PathRenameFlag_T, aFlags)); STDMETHOD(DirectorySetACL)(IN_BSTR aPath, IN_BSTR aAcl); STDMETHOD(EnvironmentClear)(); STDMETHOD(EnvironmentGet)(IN_BSTR aName, BSTR *aValue); STDMETHOD(EnvironmentSet)(IN_BSTR aName, IN_BSTR aValue); STDMETHOD(EnvironmentUnset)(IN_BSTR aName); STDMETHOD(FileCreateTemp)(IN_BSTR aTemplateName, ULONG aMode, IN_BSTR aPath, BOOL aSecure, IGuestFile **aFile); STDMETHOD(FileExists)(IN_BSTR aPath, BOOL *aExists); STDMETHOD(FileRemove)(IN_BSTR aPath); STDMETHOD(FileOpen)(IN_BSTR aPath, IN_BSTR aOpenMode, IN_BSTR aDisposition, ULONG aCreationMode, IGuestFile **aFile); STDMETHOD(FileOpenEx)(IN_BSTR aPath, IN_BSTR aOpenMode, IN_BSTR aDisposition, IN_BSTR aSharingMode, ULONG aCreationMode, LONG64 aOffset, IGuestFile **aFile); STDMETHOD(FileQueryInfo)(IN_BSTR aPath, IGuestFsObjInfo **aInfo); STDMETHOD(FileQuerySize)(IN_BSTR aPath, LONG64 *aSize); STDMETHOD(FileRename)(IN_BSTR aSource, IN_BSTR aDest, ComSafeArrayIn(PathRenameFlag_T, aFlags)); STDMETHOD(FileSetACL)(IN_BSTR aFile, IN_BSTR aAcl); STDMETHOD(ProcessCreate)(IN_BSTR aCommand, ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment), ComSafeArrayIn(ProcessCreateFlag_T, aFlags), ULONG aTimeoutMS, IGuestProcess **aGuestProcess); STDMETHOD(ProcessCreateEx)(IN_BSTR aCommand, ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment), ComSafeArrayIn(ProcessCreateFlag_T, aFlags), ULONG aTimeoutMS, ProcessPriority_T aPriority, ComSafeArrayIn(LONG, aAffinity), IGuestProcess **aGuestProcess); STDMETHOD(ProcessGet)(ULONG aPid, IGuestProcess **aGuestProcess); STDMETHOD(SymlinkCreate)(IN_BSTR aSource, IN_BSTR aTarget, SymlinkType_T aType); STDMETHOD(SymlinkExists)(IN_BSTR aSymlink, BOOL *aExists); STDMETHOD(SymlinkRead)(IN_BSTR aSymlink, ComSafeArrayIn(SymlinkReadFlag_T, aFlags), BSTR *aTarget); STDMETHOD(<API key>)(IN_BSTR aPath); STDMETHOD(SymlinkRemoveFile)(IN_BSTR aFile); STDMETHOD(WaitFor)(ULONG aWaitFor, ULONG aTimeoutMS, <API key> *aReason); STDMETHOD(WaitForArray)(ComSafeArrayIn(<API key>, aWaitFor), ULONG aTimeoutMS, <API key> *aReason); private: // wrapped IGuestSession properties virtual HRESULT getUser(com::Utf8Str &aUser) = 0; virtual HRESULT getDomain(com::Utf8Str &aDomain) = 0; virtual HRESULT getName(com::Utf8Str &aName) = 0; virtual HRESULT getId(ULONG *aId) = 0; virtual HRESULT getTimeout(ULONG *aTimeout) = 0; virtual HRESULT setTimeout(ULONG aTimeout) = 0; virtual HRESULT getProtocolVersion(ULONG *aProtocolVersion) = 0; virtual HRESULT getStatus(<API key> *aStatus) = 0; virtual HRESULT getEnvironment(std::vector<com::Utf8Str> &aEnvironment) = 0; virtual HRESULT setEnvironment(const std::vector<com::Utf8Str> &aEnvironment) = 0; virtual HRESULT getProcesses(std::vector<ComPtr<IGuestProcess> > &aProcesses) = 0; virtual HRESULT getDirectories(std::vector<ComPtr<IGuestDirectory> > &aDirectories) = 0; virtual HRESULT getFiles(std::vector<ComPtr<IGuestFile> > &aFiles) = 0; virtual HRESULT getEventSource(ComPtr<IEventSource> &aEventSource) = 0; // wrapped IGuestSession methods virtual HRESULT close() = 0; virtual HRESULT copyFrom(const com::Utf8Str &aSource, const com::Utf8Str &aDest, const std::vector<CopyFileFlag_T> &aFlags, ComPtr<IProgress> &aProgress) = 0; virtual HRESULT copyTo(const com::Utf8Str &aSource, const com::Utf8Str &aDest, const std::vector<CopyFileFlag_T> &aFlags, ComPtr<IProgress> &aProgress) = 0; virtual HRESULT directoryCreate(const com::Utf8Str &aPath, ULONG aMode, const std::vector<<API key>> &aFlags) = 0; virtual HRESULT directoryCreateTemp(const com::Utf8Str &aTemplateName, ULONG aMode, const com::Utf8Str &aPath, BOOL aSecure, com::Utf8Str &aDirectory) = 0; virtual HRESULT directoryExists(const com::Utf8Str &aPath, BOOL *aExists) = 0; virtual HRESULT directoryOpen(const com::Utf8Str &aPath, const com::Utf8Str &aFilter, const std::vector<DirectoryOpenFlag_T> &aFlags, ComPtr<IGuestDirectory> &aDirectory) = 0; virtual HRESULT directoryQueryInfo(const com::Utf8Str &aPath, ComPtr<IGuestFsObjInfo> &aInfo) = 0; virtual HRESULT directoryRemove(const com::Utf8Str &aPath) = 0; virtual HRESULT <API key>(const com::Utf8Str &aPath, const std::vector<<API key>> &aFlags, ComPtr<IProgress> &aProgress) = 0; virtual HRESULT directoryRename(const com::Utf8Str &aSource, const com::Utf8Str &aDest, const std::vector<PathRenameFlag_T> &aFlags) = 0; virtual HRESULT directorySetACL(const com::Utf8Str &aPath, const com::Utf8Str &aAcl) = 0; virtual HRESULT environmentClear() = 0; virtual HRESULT environmentGet(const com::Utf8Str &aName, com::Utf8Str &aValue) = 0; virtual HRESULT environmentSet(const com::Utf8Str &aName, const com::Utf8Str &aValue) = 0; virtual HRESULT environmentUnset(const com::Utf8Str &aName) = 0; virtual HRESULT fileCreateTemp(const com::Utf8Str &aTemplateName, ULONG aMode, const com::Utf8Str &aPath, BOOL aSecure, ComPtr<IGuestFile> &aFile) = 0; virtual HRESULT fileExists(const com::Utf8Str &aPath, BOOL *aExists) = 0; virtual HRESULT fileRemove(const com::Utf8Str &aPath) = 0; virtual HRESULT fileOpen(const com::Utf8Str &aPath, const com::Utf8Str &aOpenMode, const com::Utf8Str &aDisposition, ULONG aCreationMode, ComPtr<IGuestFile> &aFile) = 0; virtual HRESULT fileOpenEx(const com::Utf8Str &aPath, const com::Utf8Str &aOpenMode, const com::Utf8Str &aDisposition, const com::Utf8Str &aSharingMode, ULONG aCreationMode, LONG64 aOffset, ComPtr<IGuestFile> &aFile) = 0; virtual HRESULT fileQueryInfo(const com::Utf8Str &aPath, ComPtr<IGuestFsObjInfo> &aInfo) = 0; virtual HRESULT fileQuerySize(const com::Utf8Str &aPath, LONG64 *aSize) = 0; virtual HRESULT fileRename(const com::Utf8Str &aSource, const com::Utf8Str &aDest, const std::vector<PathRenameFlag_T> &aFlags) = 0; virtual HRESULT fileSetACL(const com::Utf8Str &aFile, const com::Utf8Str &aAcl) = 0; virtual HRESULT processCreate(const com::Utf8Str &aCommand, const std::vector<com::Utf8Str> &aArguments, const std::vector<com::Utf8Str> &aEnvironment, const std::vector<ProcessCreateFlag_T> &aFlags, ULONG aTimeoutMS, ComPtr<IGuestProcess> &aGuestProcess) = 0; virtual HRESULT processCreateEx(const com::Utf8Str &aCommand, const std::vector<com::Utf8Str> &aArguments, const std::vector<com::Utf8Str> &aEnvironment, const std::vector<ProcessCreateFlag_T> &aFlags, ULONG aTimeoutMS, ProcessPriority_T aPriority, const std::vector<LONG> &aAffinity, ComPtr<IGuestProcess> &aGuestProcess) = 0; virtual HRESULT processGet(ULONG aPid, ComPtr<IGuestProcess> &aGuestProcess) = 0; virtual HRESULT symlinkCreate(const com::Utf8Str &aSource, const com::Utf8Str &aTarget, SymlinkType_T aType) = 0; virtual HRESULT symlinkExists(const com::Utf8Str &aSymlink, BOOL *aExists) = 0; virtual HRESULT symlinkRead(const com::Utf8Str &aSymlink, const std::vector<SymlinkReadFlag_T> &aFlags, com::Utf8Str &aTarget) = 0; virtual HRESULT <API key>(const com::Utf8Str &aPath) = 0; virtual HRESULT symlinkRemoveFile(const com::Utf8Str &aFile) = 0; virtual HRESULT waitFor(ULONG aWaitFor, ULONG aTimeoutMS, <API key> *aReason) = 0; virtual HRESULT waitForArray(const std::vector<<API key>> &aWaitFor, ULONG aTimeoutMS, <API key> *aReason) = 0; }; #endif // !GuestSessionWrap_H_
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <helper/time_support.h> #include <jtag/jtag.h> #include "target/target.h" #include "target/target_type.h" #include "rtos.h" #include "helper/log.h" #include "helper/types.h" #include "<API key>.h" #include "target/armv7m.h" #include "target/cortex_m.h" #define <API key> 63 #define FreeRTOS_STRUCT(int_type, ptr_type, list_prev_offset) struct FreeRTOS_params { const char *target_name; const unsigned char thread_count_width; const unsigned char pointer_width; const unsigned char list_next_offset; const unsigned char list_width; const unsigned char <API key>; const unsigned char <API key>; const unsigned char thread_stack_offset; const unsigned char thread_name_offset; const struct <API key> *stacking_info_cm3; const struct <API key> *stacking_info_cm4f; const struct <API key> *<API key>; }; static const struct FreeRTOS_params <API key>[] = { { "cortex_m", /* target_name */ 4, /* thread_count_width; */ 4, /* pointer_width; */ 16, /* list_next_offset; */ 20, /* list_width; */ 8, /* <API key>; */ 12, /* <API key> */ 0, /* thread_stack_offset; */ 52, /* thread_name_offset; */ &<API key>, /* stacking_info */ &<API key>, &<API key>, }, { "hla_target", /* target_name */ 4, /* thread_count_width; */ 4, /* pointer_width; */ 16, /* list_next_offset; */ 20, /* list_width; */ 8, /* <API key>; */ 12, /* <API key> */ 0, /* thread_stack_offset; */ 52, /* thread_name_offset; */ &<API key>, /* stacking_info */ &<API key>, &<API key>, }, { "nds32_v3", /* target_name */ 4, /* thread_count_width; */ 4, /* pointer_width; */ 16, /* list_next_offset; */ 20, /* list_width; */ 8, /* <API key>; */ 12, /* <API key> */ 0, /* thread_stack_offset; */ 52, /* thread_name_offset; */ &<API key>, /* stacking_info */ &<API key>, &<API key>, }, }; #define FREERTOS_NUM_PARAMS ((int)(sizeof(<API key>)/sizeof(struct FreeRTOS_params))) static int <API key>(struct target *target); static int FreeRTOS_create(struct target *target); static int <API key>(struct rtos *rtos); static int <API key>(struct rtos *rtos, int64_t thread_id, char **hex_reg_list); static int <API key>(symbol_table_elem_t *symbol_list[]); struct rtos_type FreeRTOS_rtos = { .name = "FreeRTOS", .detect_rtos = <API key>, .create = FreeRTOS_create, .update_threads = <API key>, .get_thread_reg_list = <API key>, .<API key> = <API key>, }; enum <API key> { <API key> = 0, <API key> = 1, <API key> = 2, <API key> = 3, <API key> = 4, <API key> = 5, <API key> = 6, <API key> = 7, <API key> = 8, <API key> = 9, <API key> = 10, }; struct symbols { const char *name; bool optional; }; static const struct symbols <API key>[] = { { "pxCurrentTCB", false }, { "pxReadyTasksLists", false }, { "xDelayedTaskList1", false }, { "xDelayedTaskList2", false }, { "pxDelayedTaskList", false }, { "<API key>", false }, { "xPendingReadyList", false }, { "<API key>", true }, /* Only if INCLUDE_vTaskDelete */ { "xSuspendedTaskList", true }, /* Only if <API key> */ { "<API key>", false }, { "uxTopUsedPriority", true }, /* Unavailable since v7.5.3 */ { NULL, false } }; /* TODO: */ /* this is not safe for little endian yet */ /* may be problems reading if sizes are not 32 bit long integers. */ /* test mallocs for failure */ static int <API key>(struct rtos *rtos) { int i = 0; int retval; int tasks_found = 0; const struct FreeRTOS_params *param; if (rtos-><API key> == NULL) return -1; param = (const struct FreeRTOS_params *) rtos-><API key>; if (rtos->symbols == NULL) { LOG_ERROR("No symbols for FreeRTOS"); return -3; } if (rtos->symbols[<API key>].address == 0) { LOG_ERROR("Don't have the number of threads in FreeRTOS"); return -2; } int thread_list_size = 0; retval = target_read_buffer(rtos->target, rtos->symbols[<API key>].address, param->thread_count_width, (uint8_t *)&thread_list_size); LOG_DEBUG("FreeRTOS: Read <API key> at 0x%" PRIx64 ", value %d\r\n", rtos->symbols[<API key>].address, thread_list_size); if (retval != ERROR_OK) { LOG_ERROR("Could not read FreeRTOS thread count from target"); return retval; } /* wipe out previous thread details if any */ <API key>(rtos); /* read the current thread */ retval = target_read_buffer(rtos->target, rtos->symbols[<API key>].address, param->pointer_width, (uint8_t *)&rtos->current_thread); if (retval != ERROR_OK) { LOG_ERROR("Error reading current thread in FreeRTOS thread list"); return retval; } LOG_DEBUG("FreeRTOS: Read pxCurrentTCB at 0x%" PRIx64 ", value 0x%" PRIx64 "\r\n", rtos->symbols[<API key>].address, rtos->current_thread); if ((thread_list_size == 0) || (rtos->current_thread == 0)) { /* Either : No RTOS threads - there is always at least the current execution though */ /* OR : No current thread - all threads suspended - show the current execution * of idling */ char tmp_str[] = "Current Execution"; thread_list_size++; tasks_found++; rtos->thread_details = malloc( sizeof(struct thread_detail) * thread_list_size); if (!rtos->thread_details) { LOG_ERROR("Error allocating memory for %d threads", thread_list_size); return ERROR_FAIL; } rtos->thread_details->threadid = 1; rtos->thread_details->exists = true; rtos->thread_details->display_str = NULL; rtos->thread_details->extra_info_str = NULL; rtos->thread_details->thread_name_str = malloc(sizeof(tmp_str)); strcpy(rtos->thread_details->thread_name_str, tmp_str); if (thread_list_size == 1) { rtos->thread_count = 1; return ERROR_OK; } } else { /* create space for new thread details */ rtos->thread_details = malloc( sizeof(struct thread_detail) * thread_list_size); if (!rtos->thread_details) { LOG_ERROR("Error allocating memory for %d threads", thread_list_size); return ERROR_FAIL; } } /* Find out how many lists are needed to be read from pxReadyTasksLists, */ if (rtos->symbols[<API key>].address == 0) { LOG_ERROR("FreeRTOS: uxTopUsedPriority is not defined, consult the OpenOCD manual for a work-around"); return ERROR_FAIL; } int64_t max_used_priority = 0; retval = target_read_buffer(rtos->target, rtos->symbols[<API key>].address, param->pointer_width, (uint8_t *)&max_used_priority); if (retval != ERROR_OK) return retval; LOG_DEBUG("FreeRTOS: Read uxTopUsedPriority at 0x%" PRIx64 ", value %" PRId64 "\r\n", rtos->symbols[<API key>].address, max_used_priority); if (max_used_priority > <API key>) { LOG_ERROR("FreeRTOS maximum used priority is unreasonably big, not proceeding: %" PRId64 "", max_used_priority); return ERROR_FAIL; } symbol_address_t *list_of_lists = malloc(sizeof(symbol_address_t) * (max_used_priority+1 + 5)); if (!list_of_lists) { LOG_ERROR("Error allocating memory for %" PRId64 " priorities", max_used_priority); return ERROR_FAIL; } int num_lists; for (num_lists = 0; num_lists <= max_used_priority; num_lists++) list_of_lists[num_lists] = rtos->symbols[<API key>].address + num_lists * param->list_width; list_of_lists[num_lists++] = rtos->symbols[<API key>].address; list_of_lists[num_lists++] = rtos->symbols[<API key>].address; list_of_lists[num_lists++] = rtos->symbols[<API key>].address; list_of_lists[num_lists++] = rtos->symbols[<API key>].address; list_of_lists[num_lists++] = rtos->symbols[<API key>].address; for (i = 0; i < num_lists; i++) { if (list_of_lists[i] == 0) continue; /* Read the number of threads in this list */ int64_t list_thread_count = 0; retval = target_read_buffer(rtos->target, list_of_lists[i], param->thread_count_width, (uint8_t *)&list_thread_count); if (retval != ERROR_OK) { LOG_ERROR("Error reading number of threads in FreeRTOS thread list"); free(list_of_lists); return retval; } LOG_DEBUG("FreeRTOS: Read thread count for list %d at 0x%" PRIx64 ", value %" PRId64 "\r\n", i, list_of_lists[i], list_thread_count); if (list_thread_count == 0) continue; /* Read the location of first list item */ uint64_t prev_list_elem_ptr = -1; uint64_t list_elem_ptr = 0; retval = target_read_buffer(rtos->target, list_of_lists[i] + param->list_next_offset, param->pointer_width, (uint8_t *)&list_elem_ptr); if (retval != ERROR_OK) { LOG_ERROR("Error reading first thread item location in FreeRTOS thread list"); free(list_of_lists); return retval; } LOG_DEBUG("FreeRTOS: Read first item for list %d at 0x%" PRIx64 ", value 0x%" PRIx64 "\r\n", i, list_of_lists[i] + param->list_next_offset, list_elem_ptr); while ((list_thread_count > 0) && (list_elem_ptr != 0) && (list_elem_ptr != prev_list_elem_ptr) && (tasks_found < thread_list_size)) { /* Get the location of the thread structure. */ rtos->thread_details[tasks_found].threadid = 0; retval = target_read_buffer(rtos->target, list_elem_ptr + param-><API key>, param->pointer_width, (uint8_t *)&(rtos->thread_details[tasks_found].threadid)); if (retval != ERROR_OK) { LOG_ERROR("Error reading thread list item object in FreeRTOS thread list"); free(list_of_lists); return retval; } LOG_DEBUG("FreeRTOS: Read Thread ID at 0x%" PRIx64 ", value 0x%" PRIx64 "\r\n", list_elem_ptr + param-><API key>, rtos->thread_details[tasks_found].threadid); /* get thread name */ #define <API key> (200) char tmp_str[<API key>]; /* Read the thread name */ retval = target_read_buffer(rtos->target, rtos->thread_details[tasks_found].threadid + param->thread_name_offset, <API key>, (uint8_t *)&tmp_str); if (retval != ERROR_OK) { LOG_ERROR("Error reading first thread item location in FreeRTOS thread list"); free(list_of_lists); return retval; } tmp_str[<API key>] = '\x00'; LOG_DEBUG("FreeRTOS: Read Thread Name at 0x%" PRIx64 ", value \"%s\"\r\n", rtos->thread_details[tasks_found].threadid + param->thread_name_offset, tmp_str); if (tmp_str[0] == '\x00') strcpy(tmp_str, "No Name"); rtos->thread_details[tasks_found].thread_name_str = malloc(strlen(tmp_str)+1); strcpy(rtos->thread_details[tasks_found].thread_name_str, tmp_str); rtos->thread_details[tasks_found].display_str = NULL; rtos->thread_details[tasks_found].exists = true; if (rtos->thread_details[tasks_found].threadid == rtos->current_thread) { char running_str[] = "Running"; rtos->thread_details[tasks_found].extra_info_str = malloc( sizeof(running_str)); strcpy(rtos->thread_details[tasks_found].extra_info_str, running_str); } else rtos->thread_details[tasks_found].extra_info_str = NULL; tasks_found++; list_thread_count prev_list_elem_ptr = list_elem_ptr; list_elem_ptr = 0; retval = target_read_buffer(rtos->target, prev_list_elem_ptr + param-><API key>, param->pointer_width, (uint8_t *)&list_elem_ptr); if (retval != ERROR_OK) { LOG_ERROR("Error reading next thread item location in FreeRTOS thread list"); free(list_of_lists); return retval; } LOG_DEBUG("FreeRTOS: Read next thread location at 0x%" PRIx64 ", value 0x%" PRIx64 "\r\n", prev_list_elem_ptr + param-><API key>, list_elem_ptr); } } free(list_of_lists); rtos->thread_count = tasks_found; return 0; } static int <API key>(struct rtos *rtos, int64_t thread_id, char **hex_reg_list) { int retval; const struct FreeRTOS_params *param; int64_t stack_ptr = 0; *hex_reg_list = NULL; if (rtos == NULL) return -1; if (thread_id == 0) return -2; if (rtos-><API key> == NULL) return -1; param = (const struct FreeRTOS_params *) rtos-><API key>; /* Read the stack pointer */ retval = target_read_buffer(rtos->target, thread_id + param->thread_stack_offset, param->pointer_width, (uint8_t *)&stack_ptr); if (retval != ERROR_OK) { LOG_ERROR("Error reading stack frame from FreeRTOS thread"); return retval; } LOG_DEBUG("FreeRTOS: Read stack pointer at 0x%" PRIx64 ", value 0x%" PRIx64 "\r\n", thread_id + param->thread_stack_offset, stack_ptr); /* Check for armv7m with *enabled* FPU, i.e. a Cortex-M4F */ int cm4_fpu_enabled = 0; struct armv7m_common *armv7m_target = target_to_armv7m(rtos->target); if (is_armv7m(armv7m_target)) { if (armv7m_target->fp_feature == FPv4_SP) { /* Found ARM v7m target which includes a FPU */ uint32_t cpacr; retval = target_read_u32(rtos->target, FPU_CPACR, &cpacr); if (retval != ERROR_OK) { LOG_ERROR("Could not read CPACR register to check FPU state"); return -1; } /* Check if CP10 and CP11 are set to full access. */ if (cpacr & 0x00F00000) { /* Found target with enabled FPU */ cm4_fpu_enabled = 1; } } } if (cm4_fpu_enabled == 1) { /* Read the LR to decide between stacking with or without FPU */ uint32_t LR_svc = 0; retval = target_read_buffer(rtos->target, stack_ptr + 0x20, param->pointer_width, (uint8_t *)&LR_svc); if (retval != ERROR_OK) { LOG_OUTPUT("Error reading stack frame from FreeRTOS thread\r\n"); return retval; } if ((LR_svc & 0x10) == 0) return <API key>(rtos->target, param-><API key>, stack_ptr, hex_reg_list); else return <API key>(rtos->target, param->stacking_info_cm4f, stack_ptr, hex_reg_list); } else return <API key>(rtos->target, param->stacking_info_cm3, stack_ptr, hex_reg_list); } static int <API key>(symbol_table_elem_t *symbol_list[]) { unsigned int i; *symbol_list = calloc( ARRAY_SIZE(<API key>), sizeof(symbol_table_elem_t)); for (i = 0; i < ARRAY_SIZE(<API key>); i++) { (*symbol_list)[i].symbol_name = <API key>[i].name; (*symbol_list)[i].optional = <API key>[i].optional; } return 0; } #if 0 static int <API key>(struct rtos *rtos, threadid_t thread_id) { return 0; } static int <API key>(struct rtos *rtos, threadid_t thread_id, char **info) { int retval; const struct FreeRTOS_params *param; if (rtos == NULL) return -1; if (thread_id == 0) return -2; if (rtos-><API key> == NULL) return -3; param = (const struct FreeRTOS_params *) rtos-><API key>; #define <API key> (200) char tmp_str[<API key>]; /* Read the thread name */ retval = target_read_buffer(rtos->target, thread_id + param->thread_name_offset, <API key>, (uint8_t *)&tmp_str); if (retval != ERROR_OK) { LOG_ERROR("Error reading first thread item location in FreeRTOS thread list"); return retval; } tmp_str[<API key>] = '\x00'; if (tmp_str[0] == '\x00') strcpy(tmp_str, "No Name"); *info = malloc(strlen(tmp_str)+1); strcpy(*info, tmp_str); return 0; } #endif static int <API key>(struct target *target) { if ((target->rtos->symbols != NULL) && (target->rtos->symbols[<API key>].address != 0)) { /* looks like FreeRTOS */ return 1; } return 0; } static int FreeRTOS_create(struct target *target) { int i = 0; while ((i < FREERTOS_NUM_PARAMS) && (0 != strcmp(<API key>[i].target_name, target->type->name))) { i++; } if (i >= FREERTOS_NUM_PARAMS) { LOG_ERROR("Could not find target in FreeRTOS compatibility list"); return -1; } target->rtos-><API key> = (void *) &<API key>[i]; return 0; }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; using System.Windows.Forms; using LJH.Inventory.BusinessModel; using LJH.Inventory.BusinessModel.SearchCondition; using LJH.Inventory.WebAPIClient; using LJH.GeneralLibrary.Core.DAL; using LJH.GeneralLibrary.Core.UI; using LJH.GeneralLibrary; using LJH.Inventory.UI.Forms.General; using LJH.Inventory.UI.Forms.Inventory.View; namespace LJH.Inventory.UI.Forms.Sale { public partial class FrmDetail : FrmSheetDetailBase { public FrmDetail() { InitializeComponent(); } #region private void <API key>(Order sheet) { ItemsGrid.Rows.Clear(); if (sheet.Items == null || sheet.Items.Count == 0) return; var items = sheet.Items.Where(it => it.Product.ClassID == ProductClass.).ToList(); if (items != null) { items = (from it in items orderby it.AddDate ascending select it).ToList(); foreach (OrderItem item in items) { int row = ItemsGrid.Rows.Add(); ShowSheetItemOnRow(ItemsGrid.Rows[row], item); } int r = ItemsGrid.Rows.Add(); ItemsGrid.Rows[r].Cells["colPrice"].Value = ""; ItemsGrid.Rows[r].Cells["colCount"].Value = items.Sum(it => it.Count); ItemsGrid.Rows[r].Cells["col"].Value = items.Sum(it => it.Sqare()); ItemsGrid.Rows[r].Cells["colTotal"].Value = items.Sum(it => it.CalAmount()); } ItemsGrid.Columns["col"].Visible = items.Exists(it => it.Product.<API key>(ProductNote.) > 0); ItemsGrid.Columns["col"].Visible = items.Exists(it => it.Product.GetPropertyByInt(ProductNote.) > 0); <API key> con = new <API key>(); con.SheetIDs = new List<string>() { sheet.ID }; List<OrderItemRecord> states = (new OrderBLL(AppSettings.Current.ConnStr)).GetRecords(con).QueryObjects; if (states != null && states.Count > 0) { int shipped = 0; int inventory = 0; int = 0; foreach (DataGridViewRow row in ItemsGrid.Rows) { OrderItem oi = row.Tag as OrderItem; if (oi != null) { OrderItemRecord st = states.SingleOrDefault(item => item.ID == oi.ID); row.Cells["colShipped"].Value = st != null ? st.Shipped.Trim().ToString() : null; row.Cells["colInventory"].Value = st != null ? st.Inventory.Trim().ToString() : null; row.Cells["col"].Value = st != null ? st.OnWay.Trim().ToString() : null; shipped += st != null ? (int)st.Shipped : 0; inventory += st != null ? (int)st.Inventory : 0; += st != null ? (int)st.OnWay : 0; } } if (ItemsGrid.Rows.Count > 1) { ItemsGrid.Rows[ItemsGrid.Rows.Count - 1].Cells["colShipped"].Value = shipped; ItemsGrid.Rows[ItemsGrid.Rows.Count - 1].Cells["colInventory"].Value = inventory; ItemsGrid.Rows[ItemsGrid.Rows.Count - 1].Cells["col"].Value = ; } } if (!states.Exists(it => it.Product.ClassID == ProductClass. && it.NotHandled > 0)) mnu_.Enabled = false; } private void ShowSheetItemOnRow(DataGridViewRow row, OrderItem item) { Product p = item.Product; row.Tag = item; row.Cells["colHeader"].Value = this.ItemsGrid.Rows.Count; row.Cells["colProductID"].Value = item.ProductID; row.Cells["colProductName"].Value = p != null ? p.Name : string.Empty; row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["colModel"].Value = p != null ? p.Model : null; row.Cells["colColor"].Value = p != null ? p.GetProperty(ProductNote.) : null; row.Cells["col"].Value = p != null ? p.GetProperty(ProductNote.) : null; row.Cells["colCategory"].Value = p != null && p.Category != null ? p.Category.Name : string.Empty; row.Cells["colUnit"].Value = item.Product.Unit; row.Cells["colPrice"].Value = item.Price; row.Cells["colCount"].Value = item.Count; row.Cells["colTotal"].Value = item.CalAmount(); row.Cells["colMemo"].Value = item.GetMemo(); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.<API key>(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Product.GetProperty(ProductNote.); row.Cells["col"].Value = item.Sqare(); row.Cells["col"].Value = item.GetModifyRecords() != null ? item.GetModifyRecords().Count.ToString() : null; var tz = item.Product.GetProperty(ProductNote.); int tzn; if (!string.IsNullOrEmpty(tz) && int.TryParse(tz, out tzn)) { row.DefaultCellStyle.ForeColor = Color.Red; } else { row.DefaultCellStyle.ForeColor = Color.Black; } } private void ShowPaymentState(Order sheet) { if (AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowPrice)) { decimal receivable; decimal hasPaid; new OrderBLL(AppSettings.Current.ConnStr).GetFinancialStateOf(sheet.ID, out receivable, out hasPaid); this.lnkShippedAmount.Text = receivable.ToString("C2"); this.lnkPayment.Text = hasPaid.ToString("C2"); this.lnkNotPaid.Text = (sheet.Amount - hasPaid).ToString("C2"); } } #endregion #region <summary> </summary> public Company Customer { get; set; } #endregion #region protected override bool CheckInput() { if (string.IsNullOrEmpty(txtSheetNo.Text) && UpdatingItem != null) { MessageBox.Show(""); txtSheetNo.Focus(); return false; } if (Customer == null) { MessageBox.Show(""); txtCustomer.Focus(); return false; } if (string.IsNullOrEmpty(txt.Text)) { MessageBox.Show(""); txt.Focus(); return false; } if (dtDemandDate.IsNull) { MessageBox.Show(""); dtDemandDate.Focus(); return false; } if (!rdWithTax.Checked && !rdWithoutTax.Checked) { MessageBox.Show(""); return false; } if (ItemsGrid.Rows.Count == 0 && ItemsGrid_.Rows.Count == 0) { MessageBox.Show(""); return false; } foreach (DataGridViewRow row in ItemsGrid.Rows) { OrderItem item = row.Tag as OrderItem; if (item != null && item.Count == 0) { MessageBox.Show(string.Format(" {0} ", row.Index + 1)); row.Selected = true; return false; } } return true; } protected override void InitControls() { this.txtCustomer.Text = Customer != null ? Customer.Name : string.Empty; this.dtDemandDate.IsNull = true; this.txt.Init(); if (IsForView) { toolStrip1.Enabled = false; ItemsGrid.ReadOnly = true; ItemsGrid.ContextMenu = null; ItemsGrid.ContextMenuStrip = null; } Order sheet = UpdatingItem as Order; if (!IsAdding) { if (sheet != null) UpdatingItem = new OrderBLL(AppSettings.Current.ConnStr).GetByID(sheet.ID).QueryObject; } if (IsAdding && UserSettings.Current. > 0) { dtDemandDate.Value = DateTime.Today.AddDays(UserSettings.Current.); } this.btn_AddItem.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Edit); this.mnu_RemoveItem.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Edit); this.mnu__.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Edit); this.mnu__.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Edit); this.ItemsGrid.Columns["colPrice"].Visible = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowPrice); this.ItemsGrid.Columns["colTotal"].Visible = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowPrice); this.ItemsGrid.Columns["col"].Visible = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowPrice); this.ItemsGrid.Columns["col"].Visible = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowPrice); mnu_.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowPrice); sheet = UpdatingItem as Order; if (sheet != null && sheet.State == SheetState. && !sheet.Items.Exists(it => it.Product.ClassID != ProductClass. && it.Count > 0)) { var pids = new SysparameterInfoBLL(AppSettings.Current.ConnStr).GetByID("").QueryObject; if (pids != null && !string.IsNullOrEmpty(pids.Value)) { DateTime dt = DateTime.Now; <API key> con = new <API key>(); con.IDS = pids.Value.Split(',').ToList(); var ps = new ProductBLL(AppSettings.Current.ConnStr).GetItems(con).QueryObjects; foreach (var product in ps) { sheet.AddItems(product, 0, dt, false); dt = dt.AddSeconds(1); } } } base.InitControls(); } protected override void ItemShowing() { Order sheet = UpdatingItem as Order; if (sheet != null) { this.txtSheetNo.Text = sheet.ID; this.txtSheetNo.Enabled = false; Customer = (new CompanyBLL(AppSettings.Current.ConnStr)).GetByID(sheet.CustomerID).QueryObject; this.txtCustomer.Text = Customer != null ? Customer.Name : sheet.CustomerID; txtProject.Text = sheet.ProjectID; this.txtLinker.Text = sheet.Linker; this.txtLinkerPhone.Text = sheet.LinkerCall; this.dtSheetDate.Value = sheet.SheetDate; this.txt.Text = sheet.SalesPerson; if (sheet.DemandDate.HasValue) this.dtDemandDate.SetDate(sheet.DemandDate.Value); else this.dtDemandDate.IsNull = true; this.rdWithTax.Checked = sheet.WithTax; this.rdWithoutTax.Checked = !sheet.WithTax; this.txtPaymentMode.Text = sheet.; this.txtNote.Text = sheet.; this.txtAddress.Text = sheet.Address; chk.Checked = sheet.GetProperty(SheetNote.) == "1"; chk.Checked = sheet.GetProperty(SheetNote.) == "1"; this.txtMemo.Text = sheet.Memo; if (!IsAdding) ShowPaymentState(sheet); <API key>(sheet); ShowDeliveryItemsOnGrid_(sheet); ShowOperations(sheet, dataGridView1); <API key>(sheet, this.gridAttachment); } } protected override object GetItemFromInput() { Order sheet = UpdatingItem as Order; if (sheet == null) { sheet = new Order(); sheet.Items = new List<OrderItem>(); sheet.LastActiveDate = DateTime.Now; } else { sheet = UpdatingItem as Order; } sheet.ID = this.txtSheetNo.Text; sheet.ClassID = SheetType.; sheet.SheetDate = this.dtSheetDate.Value; sheet.CustomerID = Customer.ID; sheet.ProjectID = txtProject.Text; sheet.Linker = txtLinker.Text.Trim(); sheet.LinkerCall = txtLinkerPhone.Text.Trim(); sheet.Address = txtAddress.Text.Trim(); sheet.SalesPerson = this.txt.Text; sheet.DemandDate = this.dtDemandDate.Value; sheet.WithTax = rdWithTax.Checked; sheet. = txtPaymentMode.Text.Trim(); sheet. = txtNote.Text; sheet.SetProperty(SheetNote., chk.Checked ? "1" : null); sheet.SetProperty(SheetNote., chk.Checked ? "1" : null); sheet.Memo = txtMemo.Text; sheet.Items.RemoveAll(it => it.Count == 0); sheet.Items.ForEach(item => item.SheetNo = sheet.ID); sheet.CalAmount(); return sheet; } protected override void ShowButtonState() { ShowButtonState(this.toolStrip1); btnSave.Enabled = btnSave.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Edit); btnApprove.Enabled = btnApprove.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Approve); btnUndoApprove.Enabled = btnUndoApprove.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.UndoApprove); btnNullify.Enabled = btnNullify.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Nullify); if (UserSettings.Current.) mnu_.Enabled =(UpdatingItem as Order ).State ==SheetState. && AppSettings.Current.OperatorPara.Permit(Permission., PermissionActions.Edit); else mnu_.Enabled = btnNullify.Enabled && AppSettings.Current.OperatorPara.Permit(Permission., PermissionActions.Edit); btn.Enabled = btnNullify.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Print); ItemsGrid.ReadOnly = !btnSave.Enabled; mnu_AttachmentAdd.Enabled = mnu_AttachmentAdd.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.EditAttachment); <API key>.Enabled = <API key>.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.EditAttachment); mnu_AttachmentOpen.Enabled = mnu_AttachmentOpen.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowAttachment); <API key>.Enabled = <API key>.Enabled && AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowAttachment); this.btn_AddItem.Enabled = btnSave.Enabled; this.mnu_.Enabled = btnSave.Enabled; this.mnu_RemoveItem.Enabled = btnSave.Enabled; this.mnu__.Enabled = btnSave.Enabled; this.mnu__.Enabled = btnSave.Enabled; if (UpdatingItem != null) { var o = UpdatingItem as Order; if (o.State == SheetState. && btnSave.Enabled == false && AppSettings.Current.OperatorPara.Permit(Permission., PermissionActions.Edit)) { btnSave.Enabled = true; this.mnu__.Enabled = btnSave.Enabled; this.mnu__.Enabled = btnSave.Enabled; panel2.Enabled = false; ItemsGrid.Enabled = false; } } } protected override CommandResult AddItem(object item) { return (new OrderBLL(AppSettings.Current.ConnStr)).ProcessSheet(item as Order, SheetOperation.); } protected override CommandResult UpdateItem(object item) { return (new OrderBLL(AppSettings.Current.ConnStr)).ProcessSheet(item as Order, SheetOperation.); } #endregion #region private void <API key>(object sender, EventArgs e) { Order item = UpdatingItem as Order; if (item != null) PerformAddAttach(item, gridAttachment); } private void <API key>(object sender, EventArgs e) { PerformDelAttach(gridAttachment); } private void <API key>(object sender, EventArgs e) { PerformAttachSaveAs(gridAttachment); } private void <API key>(object sender, EventArgs e) { PerformAttachOpen(gridAttachment); } private void <API key>(object sender, <API key> e) { PerformAttachOpen(gridAttachment); } #endregion #region private void btnSave_Click(object sender, EventArgs e) { OrderBLL processor = new OrderBLL(AppSettings.Current.ConnStr); string memo = null; if (UserSettings.Current. && !IsAdding) { FrmMemo frm = new FrmMemo(); if (frm.ShowDialog() != DialogResult.OK) return; memo = frm.Memo; } PerformOperation<Order>(processor, IsAdding ? SheetOperation. : SheetOperation., memo); } private void btnApprove_Click(object sender, EventArgs e) { OrderBLL processor = new OrderBLL(AppSettings.Current.ConnStr); PerformOperation<Order>(processor, SheetOperation.); } private void <API key>(object sender, EventArgs e) { OrderBLL processor = new OrderBLL(AppSettings.Current.ConnStr); PerformOperation<Order>(processor, SheetOperation.); } private void btnNullify_Click(object sender, EventArgs e) { OrderBLL processor = new OrderBLL(AppSettings.Current.ConnStr); PerformOperation<Order>(processor, SheetOperation.); } #endregion #region private string GetPrintModel() { string model = null; model = System.IO.Path.Combine(Application.StartupPath, "", "", "" + ".xlsx"); if (File.Exists(model)) return model; model = System.IO.Path.Combine(Application.StartupPath, "", "", "" + ".xls"); if (File.Exists(model)) return model; return null; } private bool SetPrinter(out int copies) { var dig = new PrintDialog(); dig.PrinterSettings.PrinterName = AppSettings.Current.; dig.ShowNetwork = false; dig.ShowHelp = false; dig.PrintToFile = false; dig.AllowCurrentPage = false; dig.AllowPrintToFile = false; dig.AllowSelection = false; dig.AllowSomePages = false; if (dig.ShowDialog() == DialogResult.OK) { AppSettings.Current. = dig.PrinterSettings.PrinterName; copies = dig.PrinterSettings.Copies; return true; } copies = 0; return false; } private void btn_Click(object sender, EventArgs e) { Order sheet = UpdatingItem as Order; if (sheet != null) { try { string modal = GetPrintModel(); if (System.IO.File.Exists(modal)) { Print.OrderExporter exporter = new Print.OrderExporter(modal, AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.ShowPrice)); var items = (from it in sheet.Items where it.Product.ClassID == ProductClass. orderby it.AddDate ascending select it).ToList(); var files = exporter.Export(sheet, LJH.GeneralLibrary.TempFolderManager.GetCurrentFolder(), items, false, 7, 8); foreach (var file in files) { if (System.IO.File.Exists(file)) System.Diagnostics.Process.Start(file); } } else { MessageBox.Show("", ""); } } catch (Exception ex) { LJH.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex); } } } #endregion #region private void <API key>(object sender, EventArgs e) { if (tabControl1.SelectedTab == tab_) { ShowDeliveryItemsOnGrid_(UpdatingItem as Order); } } private void ShowDeliveryItemsOnGrid_(Order sheet) { this.ItemsGrid_.Rows.Clear(); if (sheet.Items == null || sheet.Items.Count == 0) return; var items = (from it in sheet.Items where it.Product.ClassID != ProductClass. orderby it.AddDate ascending select it).ToList(); if (items != null && items.Count > 0) { foreach (OrderItem item in items) { int row = this.ItemsGrid_.Rows.Add(); ShowSheetItemOnRow_(this.ItemsGrid_.Rows[row], item); } int r = ItemsGrid_.Rows.Add(); this.ItemsGrid_.Rows[r].Cells["colPrice_"].Value = ""; this.ItemsGrid_.Rows[r].Cells["colCount_"].Value = items.Sum(it => it.Count).Trim(); this.ItemsGrid_.Rows[r].Cells["colTotal_"].Value = items.Sum(it => it.CalAmount()).Trim(); } this.tab_.Text = string.Format("({0})", items != null ? items.Count : 0); <API key> con = new <API key>(); con.SheetIDs = new List<string>() { sheet.ID }; List<OrderItemRecord> states = (new OrderBLL(AppSettings.Current.ConnStr)).GetRecords(con).QueryObjects; if (states != null && states.Count > 0) { int shipped = 0; foreach (DataGridViewRow row in ItemsGrid_.Rows) { OrderItem oi = row.Tag as OrderItem; if (oi != null) { OrderItemRecord st = states.SingleOrDefault(item => item.ID == oi.ID); row.Cells["colShipped_"].Value = st != null ? st.Shipped.Trim().ToString() : null; shipped += st != null ? (int)st.Shipped : 0; } } if (ItemsGrid_.Rows.Count > 1) { ItemsGrid_.Rows[ItemsGrid_.Rows.Count - 1].Cells["colShipped_"].Value = shipped; } } } private void ShowSheetItemOnRow_(DataGridViewRow row, OrderItem item) { Product p = item.Product; row.Tag = item; row.Cells["colHeader_"].Value = this.ItemsGrid_.Rows.Count; row.Cells["col_"].Value = p != null ? p.Name : string.Empty; row.Cells["col_"].Value = p != null ? p.Specification : null; row.Cells["col_"].Value = p != null ? p.Model : null; row.Cells["col_"].Value = item.Product.InventoryUnit; row.Cells["colPrice_"].Value = item.Price.Trim(); row.Cells["colCount_"].Value = item.Count.Trim(); row.Cells["colTotal_"].Value = item.CalAmount().Trim(); row.Cells["colMemo_"].Value = item.Memo; } private void ItemsGrid__CellContentClick(object sender, <API key> e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) return; OrderItem oi = ItemsGrid_.Rows[e.RowIndex].Tag as OrderItem; if (oi == null) return; if (ItemsGrid_.Columns[e.ColumnIndex].Name == "colShipped_") { <API key> con = new <API key>(); con.OrderItem = oi.ID; con.States = new List<SheetState>() { SheetState. }; <API key> frm = new <API key>(); frm.SearchCondition = con; frm.ShowDialog(); } } private void ItemsGrid__CellEndEdit(object sender, <API key> e) { DataGridViewColumn col = ItemsGrid_.Columns[e.ColumnIndex]; DataGridViewRow row = ItemsGrid_.Rows[e.RowIndex]; if (row.Tag != null) { OrderItem item = row.Tag as OrderItem; if (col.Name == "colPrice_") { decimal price; if (decimal.TryParse(row.Cells[e.ColumnIndex].Value.ToString(), out price)) { if (price < 0) price = 0; item.Price = price; row.Cells[e.ColumnIndex].Value = price; } } else if (col.Name == "colCount_") { int count; if (int.TryParse(row.Cells[e.ColumnIndex].Value.ToString(), out count)) { if (count < 0) count = 0; item.Count = count; row.Cells[e.ColumnIndex].Value = count; } } else if (col.Name == "colMemo_") { if (row.Cells[e.ColumnIndex].Value != null) { item.Memo = row.Cells[e.ColumnIndex].Value.ToString(); } else { item.Memo = null; } } row.Cells["colTotal_"].Value = item.CalAmount(); var sheet = (UpdatingItem as Order); ItemsGrid_.Rows[ItemsGrid_.Rows.Count - 1].Cells["colCount_"].Value = sheet.Items.Where(it => it.Product.ClassID != ProductClass.).Sum(it => it.Count).Trim(); ItemsGrid_.Rows[ItemsGrid_.Rows.Count - 1].Cells["colTotal_"].Value = sheet.Items.Where(it => it.Product.ClassID != ProductClass.).Sum(it => it.CalAmount()); } } private void mnu___Click(object sender, EventArgs e) { FrmProductSelection frm = new FrmProductSelection(); frm.StartPosition = FormStartPosition.CenterParent; frm.ProductClass = ProductClass.; if (frm.ShowDialog() == DialogResult.OK) { Order sheet = UpdatingItem as Order; var items = frm.SelectedItems; if (items != null && items.Count > 0) { DateTime dt = DateTime.Now; foreach (var item in items) { if (sheet.Items.Exists(it => it.ProductID == item.Key.ID)) continue; dt = dt.AddSeconds(1); var oi = new OrderItem() { ID = Guid.NewGuid(), AddDate = dt, SheetNo = sheet.ID, ProductID = item.Key.ID, Product = item.Key, Count = item.Value }; sheet.Items.Add(oi); } ShowDeliveryItemsOnGrid_(sheet); } } } private void mnu___Click(object sender, EventArgs e) { if (ItemsGrid_.SelectedCells.Count > 0) { Order sheet = UpdatingItem as Order; foreach (DataGridViewRow row in ItemsGrid_.SelectedRows) { if (row.Tag != null) { OrderItem si = row.Tag as OrderItem; var or = (new OrderBLL(AppSettings.Current.ConnStr)).GetRecordById(si.ID).QueryObject; if (or != null && (or.Shipped > 0 || or.Inventory > 0)) { MessageBox.Show("!"); continue; } else { sheet.Items.Remove(si); } } } ShowDeliveryItemsOnGrid_(sheet); } } #endregion #region private void <API key>(object sender, <API key> e) { DataGridViewColumn col = ItemsGrid.Columns[e.ColumnIndex]; DataGridViewRow row = ItemsGrid.Rows[e.RowIndex]; if (row.Tag != null) { OrderItem item = row.Tag as OrderItem; if (col.Name == "colPrice") { decimal price; if (decimal.TryParse(row.Cells[e.ColumnIndex].Value.ToString(), out price)) { if (price < 0) price = 0; item.Price = price; row.Cells[e.ColumnIndex].Value = price; } } else if (col.Name == "colCount") { int count; if (int.TryParse(row.Cells[e.ColumnIndex].Value.ToString(), out count)) { if (count < 0) count = 0; item.Count = count; row.Cells[e.ColumnIndex].Value = count; } } else if (col.Name == "colMemo") { if (row.Cells[e.ColumnIndex].Value != null) { item.Memo = row.Cells[e.ColumnIndex].Value.ToString(); } else { item.Memo = null; } } row.Cells["colTotal"].Value = item.CalAmount(); var sheet = (UpdatingItem as Order); ItemsGrid.Rows[ItemsGrid.Rows.Count - 1].Cells["colCount"].Value = sheet.Items.Where(it => it.Product.ClassID == ProductClass.).Sum(it => it.Count); ItemsGrid.Rows[ItemsGrid.Rows.Count - 1].Cells["colTotal"].Value = sheet.Items.Where(it => it.Product.ClassID == ProductClass.).Sum(it => it.CalAmount()); } } private void btn_Add_Click(object sender, EventArgs e) { Order sheet = UpdatingItem as Order; var frm = new Frm(); frm. = sheet.(); frm.ItemAdded += delegate(object o, ItemAddedEventArgs args) { OrderItem oi = args.AddedItem as OrderItem; if (!sheet.Items.Exists(it => it.ID == oi.ID)) sheet.Items.Add(oi); <API key>(sheet); }; frm.ShowDialog(); } private void <API key>(object sender, <API key> e) { if (!AppSettings.Current.OperatorPara.Permit(Permission.Order, PermissionActions.Edit)) return; if (e.RowIndex >= 0 && ItemsGrid.Rows[e.RowIndex].Tag != null) { var oi = ItemsGrid.Rows[e.RowIndex].Tag as OrderItem; var ois = (new OrderBLL(AppSettings.Current.ConnStr)).GetRecordById(oi.ID).QueryObject; var frm = new Frm(); frm.ProductCannotChange = ois != null && (ois.Purchased > 0 || ois.Inventory > 0 || ois.Shipped > 0); frm.OrderItem = oi; frm.ItemUpdated += delegate(object o, <API key> args) { Order sheet = UpdatingItem as Order; sheet.Items.RemoveAll(it => it.ID == oi.ID); sheet.Items.Add(args.UpdatedItem as OrderItem); <API key>(sheet); foreach (DataGridViewRow row in ItemsGrid.Rows) { row.Selected = row.Index == e.RowIndex; } }; frm.ShowDialog(); } } private void mnu_Remove_Click(object sender, EventArgs e) { if (ItemsGrid.SelectedCells.Count > 0) { Order sheet = UpdatingItem as Order; foreach (DataGridViewRow row in ItemsGrid.SelectedRows) { if (row.Tag != null) { OrderItem si = row.Tag as OrderItem; var or = (new OrderBLL(AppSettings.Current.ConnStr)).GetRecordById(si.ID).QueryObject; if (or != null && (or.Shipped > 0 || or.Inventory > 0)) { MessageBox.Show("!"); continue; } else { sheet.Items.Remove(si); } } } <API key>(sheet); } } private void <API key>(object sender, <API key> e) { FrmCustomerMaster frm = new FrmCustomerMaster(); frm.ForSelect = true; if (frm.ShowDialog() == DialogResult.OK) { Customer = frm.SelectedItem as Company; txtCustomer.Text = Customer != null ? Customer.Name : string.Empty; txtAddress.Text = Customer != null ? Customer.Address : string.Empty; if (Customer.DefaultLinker != null) { var contact = new ContactBLL(AppSettings.Current.ConnStr).GetByID(Customer.DefaultLinker.Value).QueryObject; txtLinker.Text = contact != null ? contact.Name : null; txtLinkerPhone.Text = contact != null ? contact.Mobile : null; } } } private void <API key>(object sender, EventArgs e) { Customer = null; txtCustomer.Text = string.Empty; } private void <API key>(object sender, <API key> e) { if (Customer == null) return; FrmProjectMaster frm = new FrmProjectMaster(); frm.ForSelect = true; frm.Customer = Customer; if (frm.ShowDialog() == DialogResult.OK) { var project = frm.SelectedItem as Company; txtProject.Text = project.Name; txtAddress.Text = project.Address; if (project.DefaultLinker != null) { var contact = new ContactBLL(AppSettings.Current.ConnStr).GetByID(project.DefaultLinker.Value).QueryObject; if (contact != null) { txtLinker.Text = contact.Name; txtLinkerPhone.Text = contact.Mobile; } } } } private void <API key>(object sender, EventArgs e) { txtProject.Text = null; txtProject.Tag = null; } private void <API key>(object sender, <API key> e) { Forms.General.FrmStaffMaster frm = new Forms.General.FrmStaffMaster(); frm.ForSelect = true; if (frm.ShowDialog() == DialogResult.OK) { Staff item = frm.SelectedItem as Staff; txt.Text = item != null ? item.Name : string.Empty; } } private void <API key>(object sender, EventArgs e) { txt.Text = string.Empty; } private void <API key>(object sender, <API key> e) { if (Customer != null && !string.IsNullOrEmpty(txtProject.Text)) { var cs = new CompanyBLL(AppSettings.Current.ConnStr).GetItems(new <API key>() { ClassID = CompanyClass., Parent = Customer.ID }).QueryObjects; var p = cs != null ? cs.FirstOrDefault(it => it.Name == txtProject.Text) : null; if (p != null) { FrmContactMaster frm = new FrmContactMaster(); <API key> con = new <API key>(); con.CompanyID = p.ID; frm.SearchCondition = con; frm.ForSelect = true; if (frm.ShowDialog() == DialogResult.OK) { Contact c = frm.SelectedItem as Contact; txtLinker.Text = c.Name; txtLinkerPhone.Text = c.Mobile; } } } else { MessageBox.Show(""); } } private void <API key>(object sender, <API key> e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) return; OrderItem oi = ItemsGrid.Rows[e.RowIndex].Tag as OrderItem; if (oi == null) return; if (ItemsGrid.Columns[e.ColumnIndex].Name == "colInventory") { <API key> con = new <API key>(); con.OrderItem = oi.ID; con.HasRemain = true; con.States = new List<<API key>>() { <API key>.Inventory, <API key>.WaitShipping, <API key>.Reserved }; <API key> frm = new <API key>(); frm.SearchCondition = con; frm.ShowDialog(); } else if (ItemsGrid.Columns[e.ColumnIndex].Name == "colShipped") { <API key> con = new <API key>(); con.OrderItem = oi.ID; con.States = new List<SheetState>() { SheetState. }; <API key> frm = new <API key>(); frm.SearchCondition = con; frm.ShowDialog(); } else if (ItemsGrid.Columns[e.ColumnIndex].Name == "col") { <API key> frm = new <API key>(); frm.Records = oi.GetModifyRecords(); frm.ShowDialog(); } } private void mnu__Click(object sender, EventArgs e) { Order sheet = UpdatingItem as Order; if (sheet != null) { var purchase = PurchaseOrder.Create(sheet); var ois = new OrderBLL(AppSettings.Current.ConnStr).GetRecords(new <API key>() { SheetID = sheet.ID }).QueryObjects; foreach (var oi in ois) { if (oi.Product.ClassID == ProductClass. && oi.NotHandled > 0) purchase.AddItems(oi, oi.NotHandled); } var frm = new Purchase.FrmDetail(); frm.IsAdding = true; frm.UpdatingItem = purchase; frm.ShowDialog(); } } private void mnu__Click(object sender, EventArgs e) { var sheet = UpdatingItem as Order; Frm frm = new Frm(); frm.StartPosition = FormStartPosition.CenterParent; frm.Sheet = sheet; frm.ShowDialog(); <API key>(sheet); } private void mnu__Click(object sender, EventArgs e) { List<OrderItem> ois = new List<OrderItem>(); foreach (DataGridViewRow row in ItemsGrid.SelectedRows) { if (row.Tag is OrderItem) ois.Add(row.Tag as OrderItem); } if (ois.Count == 0) return; var frm = new Frm(); frm.OrderItems = ois; if (frm.ShowDialog() == DialogResult.OK) { <API key>(UpdatingItem as Order); } } private void ToolStripMenuItem_Click(object sender, EventArgs e) { if (ItemsGrid.SelectedCells.Count > 0) { Order sheet = UpdatingItem as Order; List<OrderItemRecord> records = new List<OrderItemRecord>(); foreach (DataGridViewRow row in ItemsGrid.SelectedRows) { if (row.Tag != null) { OrderItem si = row.Tag as OrderItem; var or = (new OrderBLL(AppSettings.Current.ConnStr)).GetRecordById(si.ID).QueryObject; if (or != null) records.Add(or); } } if (records.Count > 0) { var frm = new Frm(); frm.Records = records; frm.ShowDialog(); } } } #endregion } }
# -*- coding: utf-8 -*- # PartMgr GUI - Protected spin box # This program is free software; you can redistribute it and/or modify # (at your option) any later version. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from partmgr.gui.protected_widget import * from partmgr.gui.util import * class ProtectedSpinBox(<API key>): valueChanged = Signal(int) def __init__(self, parent=None): <API key>.__init__(self, parent) self.spin = QSpinBox(self) self.spin.setAccelerated(True) self.setKeyboardTracking(True) self.setEditWidget(self.spin) self.__sync() self.setProtected() self.spin.valueChanged.connect(self.__valueChanged) def setKeyboardTracking(self, on=True): self.spin.setKeyboardTracking(on) def setMinimum(self, value): self.spin.setMinimum(value) def setMaximum(self, value): self.spin.setMaximum(value) def setSingleStep(self, value): self.spin.setSingleStep(value) def setSuffix(self, suffix): self.spin.setSuffix(suffix) self.__sync() def setValue(self, value): self.spin.setValue(value) def __sync(self): self.setReadOnlyText("%d%s" % (self.spin.value(), self.spin.suffix())) def __valueChanged(self, newValue): self.__sync() self.valueChanged.emit(newValue)
<?php abstract class <API key> extends <API key> { public static function sortArrayByKey($a, $b, $sKey='order') { return isset($a[ $sKey ], $b[ $sKey ]) ? $a[ $sKey ] - $b[ $sKey ] : 1; } public static function <API key>(&$mSubject, array $aKeys) { $_sKey = array_shift($aKeys); if (! empty($aKeys)) { if (isset($mSubject[ $_sKey ]) && is_array($mSubject[ $_sKey ])) { self::<API key>($mSubject[ $_sKey ], $aKeys); } return; } if (is_array($mSubject)) { unset($mSubject[ $_sKey ]); } } public static function <API key>(&$mSubject, array $aKeys, $mValue) { $_sKey = array_shift($aKeys); if (! empty($aKeys)) { if (! isset($mSubject[ $_sKey ]) || ! is_array($mSubject[ $_sKey ])) { $mSubject[ $_sKey ] = array(); } self::<API key>($mSubject[ $_sKey ], $aKeys, $mValue); return; } $mSubject[ $_sKey ] = $mValue; } public static function numerizeElements(array $aSubject) { $_aNumeric = self::<API key>($aSubject); $_aAssociative = self::<API key>($aSubject, $_aNumeric); foreach ($_aNumeric as &$_aElem) { $_aElem = self::uniteArrays($_aElem, $_aAssociative); } if (! empty($_aAssociative)) { array_unshift($_aNumeric, $_aAssociative); } return $_aNumeric; } public static function castArrayContents(array $aModel, array $aSubject) { $_aCast = array(); foreach ($aModel as $_isKey => $_v) { $_aCast[ $_isKey ] = self::getElement($aSubject, $_isKey, null); } return $_aCast; } public static function <API key>(array $aModel, array $aSubject) { $_aInvert = array(); foreach ($aModel as $_isKey => $_v) { if (array_key_exists($_isKey, $aSubject)) { continue; } $_aInvert[ $_isKey ] = $_v; } return $_aInvert; } public static function uniteArrays() { $_aArray = array(); foreach (array_reverse(func_get_args()) as $_aArg) { $_aArray = self::<API key>(self::getAsArray($_aArg), $_aArray); } return $_aArray; } public static function <API key>($aPrecedence, $aDefault) { if (is_null($aPrecedence)) { $aPrecedence = array(); } if (! is_array($aDefault) || ! is_array($aPrecedence)) { return $aPrecedence; } if (is_callable($aPrecedence)) { return $aPrecedence; } foreach ($aDefault as $sKey => $v) { if (! array_key_exists($sKey, $aPrecedence) || is_null($aPrecedence[ $sKey ])) { $aPrecedence[ $sKey ] = $v; } else { if (is_array($aPrecedence[ $sKey ]) && is_array($v)) { $aPrecedence[ $sKey ] = self::<API key>($aPrecedence[ $sKey ], $v); } } } return $aPrecedence; } public static function dropElementsByType(array $aArray, $aTypes=array( 'array' )) { foreach ($aArray as $isKey => $vValue) { if (in_array(gettype($vValue), $aTypes, true)) { unset($aArray[ $isKey ]); } } return $aArray; } public static function dropElementByValue(array $aArray, $vValue) { foreach (self::getAsArray($vValue, true) as $_vValue) { $_sKey = array_search($_vValue, $aArray, true); if ($_sKey === false) { continue; } unset($aArray[ $_sKey ]); } return $aArray; } public static function dropElementsByKey(array $aArray, $asKeys) { foreach (self::getAsArray($asKeys, true) as $_isKey) { unset($aArray[ $_isKey ]); } return $aArray; } }
namespace VB.ReCaptcha.Core.MVC { using Microsoft.AspNetCore.Razor.TagHelpers; [HtmlTargetElement("ReCaptcha")] public class ReCaptchaTagHelper : TagHelper { public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; var script = <API key>.BuildScript(output.Content.GetContent()); var widget = <API key>.BuildWidget(); output.Content.SetHtmlContent(widget + script); } } }
require 'spec_helper' require 'switchboard/server/lib/connection' Dir["#{Peas.root}/switchboard/clients*.rb"].each { |f| require f } describe 'Switchboard Pea Commands', :celluloid do describe 'Server Commands' do describe 'Logs' do it 'should receive and write log lines to DB' do app = Fabricate :app pea = Fabricate :pea, app: app with_socket_pair do |client, peer| connection = Connection.new(peer) client.puts Setting.retrieve 'peas.switchboard_key' client.puts "app_logs.#{pea._id}" client.puts 'Been busy and stuff ' client.puts 'More busy and other stuff ' connection.dispatch expect(client.gets.strip).to eq 'AUTHORISED' sleep 0.2 logs = app.logs_collection.find.to_a expect(logs[0]['line']).to include Date.today.to_s expect(logs[1]['line']).to include Date.today.to_s expect(logs[0]['line']).to include 'app[web.1]: Been busy and stuff' expect(logs[1]['line']).to include 'app[web.1]: More busy and other stuff' end end it 'should stream existing logs from the DB to the client' do app = Fabricate :app app.log 'Cool story bro', 'testing' app.log 'Do you even log?', 'testing' with_socket_pair do |client, peer| connection = Connection.new(peer) client.puts Setting.retrieve 'peas.switchboard_key' client.puts "stream_logs.#{app.name}" connection.dispatch expect(client.gets.strip).to eq 'AUTHORISED' first = client.gets expect(first).to include Date.today.to_s expect(first).to include 'app[testing]: Cool story bro' second = client.gets expect(second).to include Date.today.to_s expect(second).to include 'app[testing]: Do you even log?' end end it 'should stream new logs as they are added' do app = Fabricate :app app.log 'Existing', 'testing' with_socket_pair do |client, peer| connection = Connection.new(peer) client.puts Setting.retrieve 'peas.switchboard_key' client.puts "stream_logs.#{app.name} follow" connection.dispatch expect(client.gets.strip).to eq 'AUTHORISED' client.gets app.log 'New logs!', 'testing' fresh = client.gets expect(fresh).to include Date.today.to_s expect(fresh).to include 'app[testing]: New logs!' end end end describe 'Pubsub' do # A little word about these sleeps, they're bad m'kay # I suspect what's happening is that because the subscribe and publish processes are # running as separate celluloid threads they need to be forced to execute in the order # that is implied in this spec. The order isn't always honoured otherwise. Worth considering # the implications of this for production code. # Also, not sure why these don't use with_socket_pair{} before :each do @server = switchboard_server sleep 0.05 @client = client_connection end it 'should publish and broadcast to 2 subscribers' do listener1 = client_connection listener2 = client_connection listener1.puts 'subscribe.test' listener2.puts 'subscribe.test' sleep 0.05 @client.puts 'publish.test' @client.puts 'foo' sleep 0.05 expect(listener1.gets.strip).to eq 'foo' expect(listener2.gets.strip).to eq 'foo' end it "should not keep history when history isn't specified" do @client.puts 'publish.test' @client.puts 'forgetme' sleep 0.05 listener = client_connection listener.puts 'subscribe.test' sleep 0.05 @client.puts 'foo' expect(listener.gets.strip).to eq 'foo' end it 'should keep history when history is specified' do @client.puts 'publish.test history' @client.puts 'rememberme' @client.puts 'foo' listener = client_connection listener.puts 'subscribe.test history' expect(listener.gets.strip).to eq 'rememberme' expect(listener.gets.strip).to eq 'foo' end end describe 'TTY', :with_worker do let(:app) { Fabricate :app } after(:each) { app.peas.destroy_all } it 'should create a remote pea', :docker do <API key>(Pea).to receive(:destroy) with_socket_pair do |client, peer| connection = Connection.new(peer) client.puts Setting.retrieve 'peas.switchboard_key' client.puts "tty.#{app.name}" connection.dispatch expect(client.gets.strip).to eq 'AUTHORISED' client.puts "ls" # Wait up to 5 secs for the container to boot Timeout.timeout(5) do sleep 0.1 until app.peas.count == 1 sleep 0.1 while app.peas.first.pod.nil? end command = app.peas.first.command expect(command).to match(/cd \/app.*profile.*ls$/) expect(app.peas.first.docker.json['Config']['Cmd']).to eq ['/bin/bash', '-c', command] end end it 'should destroy the pea after a socket closes', :docker do with_socket_pair do |client, peer| # Try not to destroy the container straight away! <API key>(Docker::Container).to receive(:attach).and_yield { sleep 0.1 } <API key>(Docker::Container).to receive(:delete) connection = Connection.new(peer) client.puts Setting.retrieve 'peas.switchboard_key' client.puts "tty.#{app.name}" connection.dispatch expect(client.gets.strip).to eq 'AUTHORISED' client.puts "ls" # Wait up to 5 secs for the container to boot Timeout.timeout(5) do sleep 0.1 until Pea.count == 1 end # Wait up to 5 secs for the container to be removed Timeout.timeout(5) do sleep 0.1 until Pea.count == 0 end end end context 'Rendevous connection' do include_context :<API key> it 'created pea should connect to a client socket via rendevous' do <API key>(Pea).to receive(:destroy) container = instance_double(Docker::Container) <API key>(Pea).to receive(:docker).and_return(container) allow(container).to receive(:start) allow(container).to receive(:kill) allow(container).to receive(:delete) # This block simulates a container outputting through STDOUT allow(container).to receive(:attach) do |*args, &block| input = args.first[:stdin].gets.strip block.call "WOW #{input} TURNED INTO OUTPUT" end server_actor = Celluloid::Actor[:switchboard_server] with_socket_pair do |client, peer| connection = Connection.new(peer) client.puts Setting.retrieve 'peas.switchboard_key' client.puts "tty.#{app.name}" connection.dispatch expect(client.gets.strip).to eq 'AUTHORISED' client.puts "ls" client.puts "INPUT" # Wait up to 5 secs for the worker to create the container mock Timeout.timeout(5) do sleep 0.1 until Pea.count == 1 && server_actor.rendevous.keys.count == 1 end rendevous_socket = server_actor.rendevous[server_actor.rendevous.keys.first] expect(rendevous_socket.gets).to eq 'WOW INPUT TURNED INTO OUTPUT' end end end end describe 'Admin TTY' do it 'should shell out to the command line' do with_socket_pair do |client, peer| connection = Connection.new(peer) client.puts Setting.retrieve 'peas.switchboard_key' client.puts "admin_tty" connection.dispatch expect(client.gets.strip).to eq 'AUTHORISED' client.puts "echo REKT" client.gets expect(client.gets.strip).to eq 'REKT' end end end end describe 'Client Commands' do describe LogsArchiver do it 'should add a pea to the watch list and remove when finished' do app = Fabricate :app pea1 = Fabricate :pea, app: app, docker_id: 'pea1' pea2 = Fabricate :pea, app: app, docker_id: 'pea2' allow(Docker::Container).to receive(:all).and_return([ double(id: pea1.docker_id), double(id: pea2.docker_id) ]) done = [] expect(PeaLogsWatcher).to receive(:new).with(pea1).once do |&block| block.call done << 'pea1' end expect(PeaLogsWatcher).to receive(:new).with(pea2).once do |&block| block.call done << 'pea2' end actor = LogsArchiver.new expect(actor.watched).to eq [] sleep 0.05 until done.count == 2 end end describe PeaLogsWatcher do # Note that when recording you will need an image called 'node-js-sample' # And you will also need to manually kill the docker container, or manually abort the # blocking container.attach() request. It may be possible to automatically abort by setting # a lower limit for READ_TIMEOUT before :each do raw = double TCPSocket allow(TCPSocket).to receive(:new).and_return(raw) @socket = double(OpenSSL::SSL::SSLSocket) allow(OpenSSL::SSL::SSLSocket).to receive(:new).and_return(@socket) allow(@socket).to receive(:sync_close=) allow(@socket).to receive(:connect) allow(@socket).to receive(:close) allow(@socket).to receive(:puts).with('') allow(@socket).to receive(:gets).and_return('AUTHORISED') allow(@socket).to receive(:puts).with(any_args) @app = Fabricate :app, name: 'node-js-sample' @pea = Fabricate :pea, app: @app, port: nil, docker_id: nil @container = @pea.spawn_container end it 'should stream the logs for a pea', :docker do expect(@socket).to receive(:puts).with('> node-js-sample@0.1.0 start /app') if VCR.current_cassette.<API key>.nil? Thread.new do sleep 1 @container.kill @container.delete end end PeaLogsWatcher.new @pea end it 'should wait for a pea to boot before connecting', :docker do allow(@pea).to receive(:running?).and_return(false, true) <API key>(PeaLogsWatcher).to receive(:info).with(/Starting to watch/) <API key>(PeaLogsWatcher).to receive(:info).with(/Waiting for/) allow(@socket).to receive(:puts).with(any_args) expect(@socket).to receive(:puts).with('> node-js-sample@0.1.0 start /app') if VCR.current_cassette.<API key>.nil? Thread.new do sleep 1 @container.kill @container.delete end end PeaLogsWatcher.new @pea end end end end
#ifndef __SND_SEQ_TIMER_H #define __SND_SEQ_TIMER_H #include <sound/timer.h> #include <sound/seq_kernel.h> typedef struct { snd_seq_tick_time_t cur_tick; /* current tick */ unsigned long resolution; /* time per tick in nsec */ unsigned long fraction; /* current time per tick in nsec */ } seq_timer_tick_t; typedef struct { /* ... tempo / offset / running state */ unsigned int running:1, /* running state of queue */ initialized:1; /* timer is initialized */ unsigned int tempo; /* current tempo, us/tick */ int ppq; /* time resolution, ticks/quarter */ snd_seq_real_time_t cur_time; /* current time */ seq_timer_tick_t tick; /* current tick */ int tick_updated; int type; /* timer type */ snd_timer_id_t alsa_id; /* ALSA's timer ID */ <API key> *timeri; /* timer instance */ unsigned int ticks; unsigned long <API key>; /* timer resolution */ unsigned int skew; unsigned int skew_base; struct timeval last_update; /* time of last clock update, used for interpolation */ spinlock_t lock; } seq_timer_t; /* create new timer (constructor) */ extern seq_timer_t *snd_seq_timer_new(void); /* delete timer (destructor) */ extern void <API key>(seq_timer_t **tmr); void <API key>(seq_timer_tick_t *tick, int tempo, int ppq, int nticks); static inline void <API key>(seq_timer_tick_t *tick, unsigned long resolution) { if (tick->resolution > 0) { tick->fraction += resolution; tick->cur_tick += (unsigned int)(tick->fraction / tick->resolution); tick->fraction %= tick->resolution; } } /* compare timestamp between events */ /* return 1 if a >= b; otherwise return 0 */ static inline int <API key>(snd_seq_tick_time_t *a, snd_seq_tick_time_t *b) { /* compare ticks */ return (*a >= *b); } static inline int <API key>(snd_seq_real_time_t *a, snd_seq_real_time_t *b) { /* compare real time */ if (a->tv_sec > b->tv_sec) return 1; if ((a->tv_sec == b->tv_sec) && (a->tv_nsec >= b->tv_nsec)) return 1; return 0; } static inline void <API key>(snd_seq_real_time_t *tm) { while (tm->tv_nsec >= 1000000000) { /* roll-over */ tm->tv_nsec -= 1000000000; tm->tv_sec++; } } /* increment timestamp */ static inline void <API key>(snd_seq_real_time_t *tm, snd_seq_real_time_t *inc) { tm->tv_sec += inc->tv_sec; tm->tv_nsec += inc->tv_nsec; <API key>(tm); } static inline void <API key>(snd_seq_real_time_t *tm, unsigned long nsec) { tm->tv_nsec += nsec; <API key>(tm); } /* called by timer isr */ int snd_seq_timer_open(queue_t *q); int snd_seq_timer_close(queue_t *q); int <API key>(queue_t *q); int <API key>(queue_t *q); void <API key>(seq_timer_t *tmr); void snd_seq_timer_reset(seq_timer_t *tmr); int snd_seq_timer_stop(seq_timer_t *tmr); int snd_seq_timer_start(seq_timer_t *tmr); int <API key>(seq_timer_t *tmr); int <API key>(seq_timer_t *tmr, int tempo); int <API key>(seq_timer_t *tmr, int ppq); int <API key>(seq_timer_t *tmr, snd_seq_tick_time_t position); int <API key>(seq_timer_t *tmr, snd_seq_real_time_t position); int <API key>(seq_timer_t *tmr, unsigned int skew, unsigned int base); snd_seq_real_time_t <API key>(seq_timer_t *tmr); snd_seq_tick_time_t <API key>(seq_timer_t *tmr); #endif
<?php ?> <!-- post --> <article id="post-<?php the_ID(); ?>" <?php post_class( 'clearfix' ); ?> > <!-- entry-meta --> <div class="grid-25 tablet-grid-25 hide-on-mobile"> <div class="entry-meta"> <?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?> <div class="date-format"> <span class="day"><?php the_time('d'); ?></span> <span class="month"><?php the_time('M'); ?> <?php the_time('Y'); ?></span> </div> <span class="ut-sticky"><i class="fa fa-thumb-tack"></i><?php _e('Sticky Post', 'unitedthemes') ?></span> <span class="author-links"><i class="fa fa-user"></i><?php _e('By', 'unitedthemes') ?> <?php <API key>(); ?></span> <?php /* translators: used between list items, there is a space after the comma */ $categories_list = <API key>( __( ', ', 'unitedthemes' ) ); if ( $categories_list && <API key>() ) : ?> <span class="cat-links"><i class="fa fa-folder-open-o"></i><?php printf( __( 'Posted in %1$s', 'unitedthemes' ), $categories_list ); ?></span> <?php endif; // End if categories ?> <?php endif; // End if 'post' == get_post_type() ?> <?php if ( ! <API key>() && ( comments_open() || '0' != get_comments_number() ) ) : ?> <span class="comments-link"><i class="fa fa-comments-o"></i><?php _e('With', 'unitedthemes') ?> <?php comments_popup_link(__('No Comments', 'unitedthemes'), __('1 Comment', 'unitedthemes'), __('% Comments', 'unitedthemes')); ?></span> <?php endif; ?> <span class="permalink"><i class="fa fa-link"></i><a title="<?php printf(__('Permanent Link to %s', 'unitedthemes'), get_the_title()); ?>" href="<?php the_permalink(); ?>"><?php _e('Permalink', 'unitedthemes') ?></a></span> <?php edit_post_link( __( 'Edit', 'unitedthemes' ), '<span class="edit-link"><i class="fa fa-pencil-square-o"></i>', '</span>' ); ?> </div> </div><!-- close entry-meta --> <div class="grid-75 tablet-grid-75 mobile-grid-100"> <!-- entry-content --> <div class="entry-content clearfix"> <?php the_content( '<span class="more-link">' . __( 'Read more', 'unitedthemes' ) . '<i class="fa <API key>"></i></span>' ); ?> <?php ut_link_pages( array( 'before' => '<div class="page-links">', 'after' => '</div>' ) ); ?> <?php if ( is_single() ) : ?> <?php /* translators: used between list items, there is a space after the comma */ $tags_list = get_the_tag_list( '', __( ', ', 'unitedthemes' ) ); if ( $tags_list ) : ?> <span class="tags-links"> <i class="fa fa-tags"></i><?php printf( __( 'Tagged&#58; %1$s', 'unitedthemes' ), $tags_list ); ?> </span> <?php endif; // End if $tags_list ?> <?php endif; // is_single() ?> </div><!-- close entry-content --> </div> </article><!-- close post -->
#!/usr/bin/env python # qtfmt.py v1.10 # v1.10 : Updated to use Python 2.0 Unicode type. # Read a document in the quotation DTD, converting it to a list of Quotation # objects. The list can then be output in several formats. __doc__ = """Usage: qtfmt.py [options] file1.xml file2.xml ... If no filenames are provided, standard input will be read. Available options: -f or --fortune Produce output for the fortune(1) program -h or --html Produce HTML output -t or --text Produce plain text output -m N or --max N Suppress quotations longer than N lines; defaults to 0, which suppresses no quotations at all. """ import string, re, cgi, types import codecs from xml.sax import saxlib, saxexts def simplify(t, indent="", width=79): """Strip out redundant spaces, and insert newlines to wrap the text at the given width.""" t = string.strip(t) t = re.sub('\s+', " ", t) if t=="": return t t = indent + t t2 = "" while len(t) > width: index = string.rfind(t, ' ', 0, width) if index == -1: t2 = t2 + t[:width] ; t = t[width:] else: t2 = t2 + t[:index] ; t = t[index+1:] t2 = t2 + '\n' return t2 + t class Quotation: """Encapsulates a single quotation. Attributes: stack -- used during construction and then deleted text -- A list of Text() instances, or subclasses of Text(), containing the text of the quotation. source -- A list of Text() instances, or subclasses of Text(), containing the source of the quotation. (Optional) author -- A list of Text() instances, or subclasses of Text(), containing the author of the quotation. (Optional) Methods: as_fortune() -- return the quotation formatted for fortune as_html() -- return an HTML version of the quotation as_text() -- return a plain text version of the quotation """ def __init__(self): self.stack = [ Text() ] self.text = [] def as_text(self): "Convert instance into a pure text form" output = "" def flatten(textobj): "Flatten a list of subclasses of Text into a list of paragraphs" if type(textobj) != types.ListType: textlist=[textobj] else: textlist = textobj paragraph = "" ; paralist = [] for t in textlist: if (isinstance(t, PreformattedText) or isinstance(t, CodeFormattedText) ): paralist.append(paragraph) paragraph = "" paralist.append(t) elif isinstance(t, Break): paragraph = paragraph + t.as_text() paralist.append(paragraph) paragraph = "" else: paragraph = paragraph + t.as_text() paralist.append(paragraph) return paralist # Flatten the list of instances into a list of paragraphs paralist = flatten(self.text) if len(paralist) > 1: indent = 2*" " else: indent = "" for para in paralist: if isinstance(para, PreformattedText) or isinstance(para, CodeFormattedText): output = output + para.as_text() else: output = output + simplify(para, indent) + '\n' attr = "" for i in ['author', 'source']: if hasattr(self, i): paralist = flatten(getattr(self, i)) text = string.join(paralist) if attr: attr = attr + ', ' text = string.lower(text[:1]) + text[1:] attr = attr + text attr=simplify(attr, width = 79 - 4 - 3) if attr: output = output + ' -- '+re.sub('\n', '\n ', attr) return output + '\n' def as_fortune(self): return self.as_text() + '%' def as_html(self): output = "<P>" def flatten(textobj): if type(textobj) != types.ListType: textlist = [textobj] else: textlist = textobj paragraph = "" ; paralist = [] for t in textlist: paragraph = paragraph + t.as_html() if isinstance(t, Break): paralist.append(paragraph) paragraph = "" paralist.append(paragraph) return paralist paralist = flatten(self.text) for para in paralist: output = output + string.strip(para) + '\n' attr = "" for i in ['author', 'source']: if hasattr(self, i): paralist = flatten(getattr(self, i)) text = string.join(paralist) attr=attr + ('<P CLASS=%s>' % i) + string.strip(text) return output + attr # Text and its subclasses are used to hold chunks of text; instances # know how to display themselves as plain text or as HTML. class Text: "Plain text" def __init__(self, text=""): self.text = text # We need to allow adding a string to Text instances. def __add__(self, val): newtext = self.text + str(val) # __class__ must be used so subclasses create instances of themselves. return self.__class__(newtext) def __str__(self): return self.text def __repr__(self): s = string.strip(self.text) if len(s) > 15: s = s[0:15] + '...' return '<%s: "%s">' % (self.__class__.__name__, s) def as_text(self): return self.text def as_html(self): return cgi.escape(self.text) class PreformattedText(Text): "Text inside <pre>...</pre>" def as_text(self): return str(self.text) def as_html(self): return '<pre>' + cgi.escape(str(self.text)) + '</pre>' class CodeFormattedText(Text): "Text inside <code>...</code>" def as_text(self): return str(self.text) def as_html(self): return '<code>' + cgi.escape(str(self.text)) + '</code>' class CitedText(Text): "Text inside <cite>...</cite>" def as_text(self): return '_' + simplify(str(self.text)) + '_' def as_html(self): return '<cite>' + string.strip(cgi.escape(str(self.text))) + '</cite>' class ForeignText(Text): "Foreign words, from Latin or French or whatever." def as_text(self): return '_' + simplify(str(self.text)) + '_' def as_html(self): return '<i>' + string.strip(cgi.escape(str(self.text))) + '</i>' class EmphasizedText(Text): "Text inside <em>...</em>" def as_text(self): return '*' + simplify(str(self.text)) + '*' def as_html(self): return '<em>' + string.strip(cgi.escape(str(self.text))) + '</em>' class Break(Text): def as_text(self): return "" def as_html(self): return "<P>" # The QuotationDocHandler class is a SAX handler class that will # convert a marked-up document using the quotations DTD into a list of # quotation objects. class QuotationDocHandler(saxlib.HandlerBase): def __init__(self, process_func): self.process_func = process_func self.newqt = None # Errors should be signaled, so we'll output a message and raise # the exception to stop processing def fatalError(self, exception): sys.stderr.write('ERROR: '+ str(exception)+'\n') sys.exit(1) error = fatalError warning = fatalError def characters(self, ch, start, length): if self.newqt != None: s = ch[start:start+length] # Undo the UTF-8 encoding, converting to ISO Latin1, which # is the default character set used for HTML. latin1_encode = codecs.lookup('iso-8859-1') [0] unicode_str = s s, consumed = latin1_encode( unicode_str ) assert consumed == len( unicode_str ) self.newqt.stack[-1] = self.newqt.stack[-1] + s def startDocument(self): self.quote_list = [] def startElement(self, name, attrs): methname = 'start_'+str(name) if hasattr(self, methname): method = getattr(self, methname) method(attrs) else: sys.stderr.write('unknown start tag: <' + name + ' ') for name, value in attrs.items(): sys.stderr.write(name + '=' + '"' + value + '" ') sys.stderr.write('>\n') def endElement(self, name): methname = 'end_'+str(name) if hasattr(self, methname): method = getattr(self, methname) method() else: sys.stderr.write('unknown end tag: </' + name + '>\n') # There's nothing to be done for the <quotations> tag def start_quotations(self, attrs): pass def end_quotations(self): pass def start_quotation(self, attrs): if self.newqt == None: self.newqt = Quotation() def end_quotation(self): st = self.newqt.stack for i in range(len(st)): if type(st[i]) == types.StringType: st[i] = Text(st[i]) self.newqt.text=self.newqt.text + st del self.newqt.stack if self.process_func: self.process_func(self.newqt) else: print "Completed quotation\n ", self.newqt.__dict__ self.newqt=Quotation() # Attributes of a quotation: <author>...</author> and <source>...</source> def start_author(self, data): # Add the current contents of the stack to the text of the quotation self.newqt.text = self.newqt.text + self.newqt.stack # Reset the stack self.newqt.stack = [ Text() ] def end_author(self): # Set the author attribute to contents of the stack; you can't # have more than one <author> tag per quotation. self.newqt.author = self.newqt.stack # Reset the stack for more text. self.newqt.stack = [ Text() ] # The code for the <source> tag is exactly parallel to that for <author> def start_source(self, data): self.newqt.text = self.newqt.text + self.newqt.stack self.newqt.stack = [ Text() ] def end_source(self): self.newqt.source = self.newqt.stack self.newqt.stack = [ Text() ] # Text markups: <br/> for breaks, <pre>...</pre> for preformatted # text, <em>...</em> for emphasis, <cite>...</cite> for citations. def start_br(self, data): # Add a Break instance, and a new Text instance. self.newqt.stack.append(Break()) self.newqt.stack.append( Text() ) def end_br(self): pass def start_pre(self, data): self.newqt.stack.append( Text() ) def end_pre(self): self.newqt.stack[-1] = PreformattedText(self.newqt.stack[-1]) self.newqt.stack.append( Text() ) def start_code(self, data): self.newqt.stack.append( Text() ) def end_code(self): self.newqt.stack[-1] = CodeFormattedText(self.newqt.stack[-1]) self.newqt.stack.append( Text() ) def start_em(self, data): self.newqt.stack.append( Text() ) def end_em(self): self.newqt.stack[-1] = EmphasizedText(self.newqt.stack[-1]) self.newqt.stack.append( Text() ) def start_cite(self, data): self.newqt.stack.append( Text() ) def end_cite(self): self.newqt.stack[-1] = CitedText(self.newqt.stack[-1]) self.newqt.stack.append( Text() ) def start_foreign(self, data): self.newqt.stack.append( Text() ) def end_foreign(self): self.newqt.stack[-1] = ForeignText(self.newqt.stack[-1]) self.newqt.stack.append( Text() ) if __name__ == '__main__': import sys, getopt # Process the command-line arguments opts, args = getopt.getopt(sys.argv[1:], 'fthm:r', ['fortune', 'text', 'html', 'max=', 'help', 'randomize'] ) # Set defaults maxlength = 0 ; method = 'as_fortune' randomize = 0 # Process arguments for opt, arg in opts: if opt in ['-f', '--fortune']: method='as_fortune' elif opt in ['-t', '--text']: method = 'as_text' elif opt in ['-h', '--html']: method = 'as_html' elif opt in ['-m', '--max']: maxlength = string.atoi(arg) elif opt in ['-r', '--randomize']: randomize = 1 elif opt == '--help': print __doc__ ; sys.exit(0) # This function will simply output each quotation by calling the # desired method, as long as it's not suppressed by a setting of # --max. qtlist = [] def process_func(qt, qtlist=qtlist, maxlength=maxlength, method=method): func = getattr(qt, method) output = func() length = string.count(output, '\n') if maxlength!=0 and length > maxlength: return qtlist.append(output) # Loop over the input files; use sys.stdin if no files are specified if len(args) == 0: args = [sys.stdin] for file in args: if type(file) == types.StringType: input = open(file, 'r') else: input = file # Enforce the use of the Expat parser, because the code needs to be # sure that the output will be UTF-8 encoded. p=saxexts.XMLParserFactory.make_parser(["xml.sax.drivers.drv_pyexpat"]) dh = QuotationDocHandler(process_func) p.setDocumentHandler(dh) p.setErrorHandler(dh) p.parseFile(input) if type(file) == types.StringType: input.close() p.close() # Randomize the order of the quotations if randomize: import whrandom q2 = [] for i in range(len(qtlist)): qt = whrandom.randint(0,len(qtlist)-1 ) q2.append( qtlist[qt] ) qtlist[qt:qt+1] = [] assert len(qtlist) == 0 qtlist = q2 for quote in qtlist: print quote # We're done!
-- [Q] [A] Report to Goldshire -- Also moved the emote to creature_text -- Doesn't work because it's auto-accept.. -- Marshal McBride SAI SET @ENTRY := 197; SET @QUEST := 54; UPDATE `creature_template` SET `AIName`='SmartAI' WHERE `entry`=@ENTRY; UPDATE `quest_template` SET `StartScript`=0,`CompleteScript`=0 WHERE `id`=@QUEST; DELETE FROM `quest_start_scripts` WHERE `id`=@QUEST; DELETE FROM `smart_scripts` WHERE `entryorguid`=@ENTRY AND `source_type`=0; INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES (@ENTRY,0,0,0,19,0,100,0,@QUEST,0,0,0,1,0,0,0,0,0,0,7,0,0,0,0,0,0,0,"Marshal McBride - On Quest Accept - Say Line 0"); -- Text DELETE FROM `db_script_string` WHERE `entry`=2000000059; DELETE FROM `creature_text` WHERE `entry`=@ENTRY; INSERT INTO `creature_text` (`entry`,`groupid`,`id`,`text`,`type`,`language`,`probability`,`emote`,`duration`,`sound`,`comment`) VALUES (@ENTRY,0,0,"You are dismissed, $N.",12,0,100,113,0,0,"Marshal McBride");
#include "precompiled_header.hpp" #include "wss/session_sheet_map.hpp" #include "wss/worksheet.hpp" #include "wss/session.hpp" const uuid_type& session_sheet_map::<API key>( session& s, const <API key>& original_sheet, const bool <API key> /*= false */ ) { <API key> session_sheet = worksheet::<API key>( s, original_sheet ); <API key>( original_sheet, session_sheet ); if ( <API key> ) { s.selected().worksheet( session_sheet ); } original_sheet->fill_session_sheet( s, session_sheet ); return session_sheet->uuid(); } session_sheet_map::uuid_list session_sheet_map::<API key>() const { uuid_list return_list; <API key> it( m_id_translation.begin() ), end_it( m_id_translation.end() ); for ( ; it != end_it; ++it ) { return_list.push_back( it->second ); } return return_list; } session_sheet_map::uuid_list session_sheet_map::<API key>() const { uuid_list return_list; <API key> it( m_id_translation.begin() ), end_it( m_id_translation.end() ); for ( ; it != end_it; ++it ) { return_list.push_back( it->first ); } return return_list; } const <API key>& session_sheet_map::session_sheet( const uuid_type& session_sheet_id ) const { const_iterator it( m_storage.find( session_sheet_id ) ); if ( it != m_storage.end() ) { return it->second; } static <API key> dummy; return dummy; } const <API key>& session_sheet_map::session_sheet( const utf8_ci_string& name ) const { const_name_iterator it( m_name_lookup.find( name ) ); if ( it != m_name_lookup.end() ) { return session_sheet( it->second ); } static <API key> dummy; return dummy; } const <API key>& session_sheet_map::<API key>( const uuid_type& original_sheet_id ) const { const_iterator it( m_storage.find( <API key>.find( original_sheet_id )->second ) ); if ( it != m_storage.end() ) { return it->second; } static <API key> dummy; return dummy; } void session_sheet_map::<API key>( const <API key>& original_sheet, const <API key>& session_sheet ) { m_storage[session_sheet->uuid()] = session_sheet; m_id_translation[session_sheet->uuid()] = original_sheet->uuid(); m_name_lookup[original_sheet->name()] = session_sheet->uuid(); <API key>[original_sheet->uuid()] = session_sheet->uuid(); } void session_sheet_map::<API key>( const uuid_type& session_sheet_id ) { <API key> id_it( m_id_translation.find( session_sheet_id ) ); if ( id_it != m_id_translation.end() ) { iterator store_it( m_storage.find( session_sheet_id ) ); assert( "session sheet storage is in an unstable state!!" && store_it != m_storage.end() ); //make sure everything is removed properly! store_it->second->unload(); //then erase the sheet //m_id_translation.erase( session_sheet_id ); <API key>.erase( m_id_translation.find( id_it->first )->second ); m_name_lookup.erase( store_it->second->name() ); m_id_translation.erase( id_it ); m_storage.erase( store_it ); } } void session_sheet_map::notify_sheet_unload( const uuid_type& sheet_id ) { std::vector< uuid_type > uuids_to_remove; <API key> it( m_id_translation.begin() ), end_it( m_id_translation.end() ); for ( ; it != end_it; ++it ) { if ( sheet_id == it->second ) { uuids_to_remove.push_back( it->first ); } } std::vector< uuid_type >::const_iterator it_del( uuids_to_remove.begin() ), end_it_del( uuids_to_remove.end() ); for ( ; it_del != end_it_del; ++it_del ) { <API key>( *it_del ); } } const bool session_sheet_map::check( const uuid_type& session_sheet_id ) const { return m_storage.find( session_sheet_id ) != m_storage.end(); } const bool session_sheet_map::check( const utf8_ci_string& name ) const { return m_name_lookup.find( name ) != m_name_lookup.end(); } const bool session_sheet_map::check_original_uuid( const uuid_type& original_sheet_id ) const { return <API key>.find( original_sheet_id ) != <API key>.end(); } const session_sheet_map::<API key>& session_sheet_map::<API key>() const { return m_id_translation; } session_sheet_map::~session_sheet_map() { std::vector< uuid_type > uuids_to_remove; <API key> it( m_id_translation.begin() ), end_it( m_id_translation.end() ); for ( ; it != end_it; ++it ) { uuids_to_remove.push_back( it->first ); } std::vector< uuid_type >::const_iterator it_del( uuids_to_remove.begin() ), end_it_del( uuids_to_remove.end() ); for ( ; it_del != end_it_del; ++it_del ) { <API key>( *it_del ); } }
{getHeader} {if isset($sidebarType) && $sidebarType == 'home'} {if !is_active_sidebar('sidebar-home')} {var $fullwidth = true} {/if} {elseif isset($sidebarType) && $sidebarType == 'item'} {if !is_active_sidebar('sidebar-item')} {var $fullwidth = true} {/if} {else} {if !is_active_sidebar('sidebar-1')} {var $fullwidth = true} {/if} {/if} <div id="main" class="defaultContentWidth{ifset $fullwidth} onecolumn{/ifset}"> <div id="wrapper-row"> <div id="primary" class=""> <div id="content" role="main"> {ifset $themeOptions->advertising->showBox2} <div id="advertising-box-2" class="advertising-box"> {!$themeOptions->advertising->box2Content} </div> {/ifset} {include #content} </div><!-- /#content --> </div><!-- /#primary --> {ifset $fullwidth} {else} {if isset($sidebarType) && $sidebarType == 'home'} {isActiveSidebar sidebar-home} <div id="secondary" class="widget-area" role="complementary"> {dynamicSidebar sidebar-home} </div> {/isActiveSidebar} {elseif isset($sidebarType) && $sidebarType == 'item'} {isActiveSidebar sidebar-item} <div id="secondary" class="widget-area" role="complementary"> {dynamicSidebar sidebar-item} </div> {/isActiveSidebar} {else} {isActiveSidebar sidebar-1} <div id="secondary" class="widget-area" role="complementary"> {dynamicSidebar sidebar-1} </div> {/isActiveSidebar} {/if} {/ifset} </div> </div> <!-- /#main --> {getFooter}
#ifndef _Fa4Help_H #define _Fa4Help_H extern void Usage( WS, uint32_t Err ); extern int ProcessArgs( LPWORKSTR pWS, int argc, char **argp, uint32_t level ); typedef enum { // date styles od_dateup = 1, od_datedown = 2, od_sizeup = 3, od_sizedown = 4 }OrderStyle; #endif /* _Fa4Help_H */ // eof - Fa4Help.h
Player = FindMetaTable("Player") resource.AddFile( "materials/saikred/melontank/orange_crosshair.png" ) resource.AddFile( "materials/saikred/melontank/UI.png" ) resource.AddFile( "materials/saikred/melontank/melon_half.png" ) resource.AddFile( "materials/saikred/melontank/melon_half_moon.png" ) resource.AddFile( "materials/saikred/melontank/logo.png" ) resource.AddFile( "sound/saikred/melontank/r-novoxbfh.mp3" ) include( "sv_toclient.lua" ) include( "sh_init.lua" ) include( "sv_playerfuncs.lua" ) include( "sv_spawning.lua" ) include( "sv_endround.lua" ) AddCSLuaFile( "sh_init.lua" ) AddCSLuaFile( "cl_toserver.lua" ) AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "cl_cameracontrols.lua" ) AddCSLuaFile( "cl_hud.lua" ) AddCSLuaFile( "cl_scoreboard.lua" ) hook.Add( "Think" , "Bonus" , function() if not #ents.FindByClass( "bonus" ) or #ents.FindByClass( "bonus" ) < 1 then if math.random( 1 , 1000 ) > 1 then return false end local BonPos = table.Random( ents.FindByClass( "mt_bonus" ) ):GetPos() local BonEnt = ents.Create( "bonus" ) BonEnt:SetPos( BonPos + Vector( 0 , 0 , 35 ) ) BonEnt:Spawn() end end ) hook.Add( "Think" , "ShiledOver" , function() for _,Ply in pairs( player.GetAll() ) do if Ply.Shield and Ply.Shield > 100 then Ply.Shield = Ply.Shield - 0.05 UpdateTank( Ply )end end end )
<?php session_start(); $memberFolder=$_SESSION['userId']; $albumid=$_SESSION["Aid"]; ?> <!doctype html public "-//w3c//dtd html 3.2//en"> <html> <head> <title>Multiple image upload</title> <meta name="GENERATOR" content="Arachnophilia 4.0"> <meta name="FORMATTER" content="Arachnophilia 4.0"> </head> <body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000"> <?php include("dbconn.php"); for($i=1;$i<=10;$i++) { $value=$_FILES[image.$i][name]; if(!empty($value)) { $filename = $value; //path to upload image $add = "../Images/$memberFolder/$filename"; // echo $_FILES[images][type][$key]; if(checkAlreadyExists($memberFolder,$filename)==1) { echo"Image Name ".$filename." already exists! "; echo"<br>Renaming the File in Progress..."; //or rename it here //getting extension of image file switch($_FILES[image.$i][type]) { case 'image/gif'; $ext="gif"; break; case 'image/jpeg'; $ext="jpg"; break; case 'image/pjpeg'; $ext="jpg"; break; case 'image/png'; $ext="png"; break; case 'application/x-shockwave-flash'; $ext="swf"; break; case 'image/psd'; $ext="psd"; break; case 'image/bmp'; $ext="bmp"; break; } $name=RandomFile(); $filename=$name.".".$ext; $add = "Images/$memberFolder/$filename"; // exit(); } copy($_FILES[image.$i][tmp_name], $add); chmod("$add",0777); //change file mode if(file_exists("$add")) { $info= getimagesize("$add"); //e.g list($width, $height, $type, $attr) = getimagesize("img/flag.jpg"); print("upload successful for $filename - $info[3] <br>\n"); $result=$db->query("SELECT * FROM images"); $count = $result->num_rows; $result=$db->query("SELECT * FROM images where ImageId=$count"); while ($row = $result->fetch_assoc()) { $Imgid=$row["ImageId"]; } $Imgid=$Imgid+1; $date=getCurrentDate(); $db->query("INSERT INTO images VALUES ($Imgid, '','$date','$memberFolder/$filename','')"); $db->query("INSERT INTO albumcontainsimages VALUES ($albumid,$Imgid )"); $_SESSION["ImageTag"]=array(); //replace later with sesion userid $userid=$_SESSION['userId']; $_SESSION["Userid"]=$userid; global $Img; $Img=array(); $result = $db->query('SELECT distinct i.ImageId FROM images as i WHERE i.ImageId In(select a.ImageId From albumcontainsimages as a Where a.AlbumId IN( Select o.AlbumId From ownalbum as o Where o.OwnerId='."$userid".')) and (i.ImageName="" or i.Description="") '); $count = $result->num_rows; if(!empty($count)) { echo" You have $count new Images to be tagged!"; while ($row = $result->fetch_assoc()) { $Img[]=$row["ImageId"]; }//end of while loop $_SESSION["ImageTag"]=$Img; echo"<br><a href=../tagImage/ImageTag.php?ImgId=".$Img[0].">Click here to tag Images </a> &nbsp;"; } else { echo" You have 0 Images to be tagged!"; } } else { print("error: upload failed<br>\n"); } } } $result->close(); $db->close(); ?> </body> </html>
/* This module provides statistics about two merged capture files, to find packet loss, * time delay, ip header checksum errors and order check to tshark. * It's also detecting the matching regions of the different files. * * The packets are compared by the ip id. MAC or TTL is used to distinct the different files. * It is only used by tshark and not wireshark */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "epan/packet_info.h" #include <epan/in_cksum.h> #include <epan/packet.h> #include <epan/tap.h> #include <epan/timestamp.h> #include <epan/stat_cmd_args.h> #include <epan/dissectors/packet-ip.h> #include "epan/timestats.h" /* For checksum */ #define BYTES 8 #define WRONG_CHKSUM 0 #define MERGED_FILES 2 #define TTL_SEARCH 5 void <API key>(void); /* information which will be printed */ typedef struct _for_print { guint count; guint16 cksum; nstime_t predecessor_time; struct _frame_info *partner; } for_print; /* each tracked packet */ typedef struct _frame_info { for_print *fp; guint32 num; guint16 id; guint8 ip_ttl; address dl_dst; nstime_t abs_ts, zebra_time, delta; } frame_info; /* used to keep track of the statistics for an entire program interface */ typedef struct _comparestat_t { char *filter; GHashTable *packet_set, *ip_id_set, *nr_set; address eth_dst, eth_src; nstime_t zebra_time, current_time; timestat_t stats; GArray *ip_ttl_list; gboolean last_hit; guint32 start_ongoing_hits, stop_ongoing_hits, <API key>, <API key>, <API key>, <API key>; guint32 first_file_amount, second_file_amount; } comparestat_t; /* to call directly _init */ static gdouble compare_variance=0.0; static guint8 compare_start, compare_stop; static gboolean TTL_method=TRUE, ON_method=TRUE; /* This callback is never used by tshark but it is here for completeness. */ static void comparestat_reset(void *dummy _U_) { } /* This callback is invoked whenever the tap system has seen a packet * we might be interested in. * function returns : * 0: no updates, no need to call (*draw) later * !0: state has changed, call (*draw) sometime later */ static int comparestat_packet(void *arg, packet_info *pinfo, epan_dissect_t *edt _U_, const void *arg2) { comparestat_t *cs=(comparestat_t *)arg; const ws_ip *ci=(const ws_ip *)arg2; frame_info *fInfo; vec_t cksum_vec[3]; guint16 computed_cksum=0; /* so this get filled, usually with the first frame */ if(cs->eth_dst.len==0) { cs->eth_dst=pinfo->dl_dst; cs->eth_src=pinfo->dl_src; } /* Set up the fields of the pseudo-header and create checksum */ cksum_vec[0].ptr=&ci->ip_v_hl; cksum_vec[0].len=BYTES; /* skip TTL */ cksum_vec[1].ptr=&ci->ip_p; cksum_vec[1].len=1; /* skip header checksum and ip's (because of NAT)*/ cksum_vec[2].ptr=(const guint8 *)ci->ip_dst.data; cksum_vec[2].ptr=cksum_vec[2].ptr+ci->ip_dst.len; /* dynamic computation */ cksum_vec[2].len=ci->ip_len-20; computed_cksum=in_cksum(&cksum_vec[0], 3); /* collect all packet infos */ fInfo=(frame_info*)se_alloc(sizeof(frame_info)); fInfo->fp=(for_print*)se_alloc(sizeof(for_print)); fInfo->fp->partner=NULL; fInfo->fp->count=1; fInfo->fp->cksum=computed_cksum; fInfo->num=pinfo->fd->num; fInfo->id=ci->ip_id; fInfo->ip_ttl=ci->ip_ttl; fInfo->dl_dst=pinfo->dl_dst; fInfo->abs_ts=pinfo->fd->abs_ts; /* clean memory */ nstime_set_zero(&fInfo->zebra_time); nstime_set_zero(&fInfo->fp->predecessor_time); g_hash_table_insert(cs->packet_set, GINT_TO_POINTER(pinfo->fd->num), fInfo); return 1; } /* Find equal packets, same IP-Id, count them and make time statistics */ static void <API key>(gpointer key _U_, gpointer value, gpointer arg) { comparestat_t *cs=(comparestat_t*)arg; frame_info *fInfo=(frame_info*)value, *fInfoTemp; nstime_t delta; guint i; /* we only need one value out of pinfo we use a temp one */ packet_info *pinfo=(packet_info*)ep_alloc(sizeof(packet_info)); pinfo->fd=(frame_data*)ep_alloc(sizeof(frame_data)); pinfo->fd->num = fInfo->num; fInfoTemp=(frame_info *)g_hash_table_lookup(cs->ip_id_set, GINT_TO_POINTER((gint)fInfo->id)); if(fInfoTemp==NULL){ /* Detect ongoing package loss */ if((cs->last_hit==FALSE)&&(cs->start_ongoing_hits>compare_start)&&(cs->stop_ongoing_hits<compare_stop)){ cs->stop_ongoing_hits++; cs-><API key>=fInfo->num; } else if(cs->stop_ongoing_hits<compare_stop){ cs->stop_ongoing_hits=0; cs-><API key>=G_MAXINT32; } cs->last_hit=FALSE; fInfo->fp->count=1; g_hash_table_insert(cs->ip_id_set, GINT_TO_POINTER((gint)fInfo->id), fInfo); } else { /* Detect ongoing package hits, special behavior if start is set to 0 */ if((cs->last_hit||(compare_start==0))&&(cs->start_ongoing_hits<compare_start||(compare_start==0))){ if((compare_start==0)&&(cs->start_ongoing_hits!=0)){ /* start from the first packet so already set */ } else { cs->start_ongoing_hits++; /* Take the lower number */ cs-><API key>=fInfoTemp->num; cs-><API key>=fInfo->num; } } else if(cs->start_ongoing_hits<compare_start){ cs->start_ongoing_hits=0; cs-><API key>=G_MAXINT32; } cs->last_hit=TRUE; fInfo->fp->count=fInfoTemp->fp->count + 1; if(fInfoTemp->fp->cksum!=fInfo->fp->cksum){ fInfo->fp->cksum=WRONG_CHKSUM; fInfoTemp->fp->cksum=WRONG_CHKSUM; } /* Add partner */ fInfo->fp->partner=fInfoTemp; /* Create time statistic */ if(fInfo->fp->count==MERGED_FILES){ nstime_delta(&delta, &fInfo->abs_ts, &fInfoTemp->abs_ts); /* Set delta in both packets */ nstime_set_zero(&fInfoTemp->delta); nstime_add(&fInfoTemp->delta, &delta); nstime_set_zero(&fInfo->delta); nstime_add(&fInfo->delta, &delta); time_stat_update(&cs->stats, &delta, pinfo); } g_hash_table_insert(cs->ip_id_set, GINT_TO_POINTER((gint)fInfo->id), fInfo); } /* collect TTL's */ if(TTL_method && (fInfo->num<TTL_SEARCH)){ for(i=0; i < cs->ip_ttl_list->len; i++){ if(g_array_index(cs->ip_ttl_list, guint8, i) == fInfo->ip_ttl){ return; } } g_array_append_val(cs->ip_ttl_list, fInfo->ip_ttl); } } /*Create new numbering */ static void <API key>(gpointer key _U_, gpointer value, gpointer arg) { comparestat_t *cs=(comparestat_t*)arg; frame_info *fInfo=(frame_info*)value, *fInfoTemp; /* overwrite Info column for new ordering */ fInfoTemp=(frame_info *)g_hash_table_lookup(cs->nr_set, GINT_TO_POINTER((gint)fInfo->id)); if(fInfoTemp==NULL){ if(TTL_method==FALSE){ if((ADDRESSES_EQUAL(&cs->eth_dst, &fInfo->dl_dst)) || (ADDRESSES_EQUAL(&cs->eth_src, &fInfo->dl_dst))){ g_hash_table_insert(cs->nr_set, GINT_TO_POINTER((gint)fInfo->id), fInfo); fInfo->zebra_time=cs->zebra_time; cs->zebra_time.nsecs=cs->zebra_time.nsecs + MERGED_FILES; } else { cs->zebra_time.nsecs++; g_hash_table_insert(cs->nr_set, GINT_TO_POINTER((gint)fInfo->id), fInfo); fInfo->zebra_time=cs->zebra_time; cs->zebra_time.nsecs++; } } else { if((g_array_index(cs->ip_ttl_list, guint8, 0)==fInfo->ip_ttl) || (g_array_index(cs->ip_ttl_list, guint8, 1)==fInfo->ip_ttl)){ g_hash_table_insert(cs->nr_set, GINT_TO_POINTER((gint)fInfo->id), fInfo); fInfo->zebra_time=cs->zebra_time; cs->zebra_time.nsecs=cs->zebra_time.nsecs + MERGED_FILES; } else { cs->zebra_time.nsecs++; g_hash_table_insert(cs->nr_set, GINT_TO_POINTER((gint)fInfo->id), fInfo); fInfo->zebra_time=cs->zebra_time; cs->zebra_time.nsecs++; } } } else { if(TTL_method==FALSE){ if(((ADDRESSES_EQUAL(&cs->eth_dst, &fInfo->dl_dst)) || (ADDRESSES_EQUAL(&cs->eth_src, &fInfo->dl_dst)))&&(!fmod(fInfoTemp->zebra_time.nsecs,MERGED_FILES))){ fInfo->zebra_time.nsecs=fInfoTemp->zebra_time.nsecs; } else { fInfo->zebra_time.nsecs=fInfoTemp->zebra_time.nsecs+1; } } else { if(((g_array_index(cs->ip_ttl_list, guint8, 0)==fInfo->ip_ttl) || (g_array_index(cs->ip_ttl_list, guint8, 1)==fInfo->ip_ttl))&&(!fmod(fInfoTemp->zebra_time.nsecs,MERGED_FILES))){ fInfo->zebra_time.nsecs=fInfoTemp->zebra_time.nsecs; } else { fInfo->zebra_time.nsecs=fInfoTemp->zebra_time.nsecs+1; } } } /* count packets of file */ if(fmod(fInfo->zebra_time.nsecs, MERGED_FILES)){ cs->first_file_amount++; } else { cs->second_file_amount++; } /* ordering */ if(!nstime_is_unset(&cs->current_time)){ fInfo->fp->predecessor_time.nsecs=cs->current_time.nsecs; } cs->current_time.nsecs=fInfo->zebra_time.nsecs; } /* calculate scopes if not set yet */ static void <API key>(gpointer key _U_, gpointer value, gpointer arg) { comparestat_t *cs=(comparestat_t*)arg; frame_info *fInfo=(frame_info*)value, *fInfoTemp=NULL; guint32 tot_packet_amount=cs->first_file_amount+cs->second_file_amount, swap; if((fInfo->num==tot_packet_amount)&&(cs-><API key>!=G_MAXINT32)){ /* calculate missing stop number */ swap=cs-><API key>; cs-><API key>=<API key>->second_file_amount; cs-><API key>=swap; } if((fInfo->num==tot_packet_amount)&&(cs-><API key>==G_MAXINT32)&&(cs-><API key>!=G_MAXINT32)){ fInfoTemp=(frame_info *)g_hash_table_lookup(cs->packet_set, GINT_TO_POINTER(cs-><API key>)); if(fInfoTemp==NULL){ printf("ERROR: start number not set correctly\n"); return; } if(fmod(fInfoTemp->zebra_time.nsecs, 2)){ /*first file*/ cs-><API key>=cs-><API key>+abs(cs->second_file_amount-(cs-><API key>->first_file_amount)); if(cs-><API key>>(<API key>->second_file_amount)){ cs-><API key>=<API key>->second_file_amount; } /*this only happens if we have too many MAC's or TTL*/ if(cs-><API key>>cs-><API key>){ cs-><API key>=cs-><API key>; } fInfoTemp=(frame_info *)g_hash_table_lookup(cs->packet_set, GINT_TO_POINTER(cs-><API key>)); while((fInfoTemp!=NULL)?fmod(!fInfoTemp->zebra_time.nsecs, 2):TRUE){ cs-><API key> fInfoTemp=(frame_info *)g_hash_table_lookup(cs->packet_set, GINT_TO_POINTER(cs-><API key>)); } } else { /*this only happens if we have too many MAC's or TTL*/ cs-><API key>=cs->first_file_amount+cs-><API key>; if(cs-><API key>><API key>->first_file_amount){ cs-><API key>=<API key>->first_file_amount; } fInfoTemp=(frame_info *)g_hash_table_lookup(cs->packet_set, GINT_TO_POINTER(cs-><API key>)); while((fInfoTemp!=NULL)?fmod(fInfoTemp->zebra_time.nsecs, 2):TRUE){ cs-><API key> fInfoTemp=(frame_info *)g_hash_table_lookup(cs->packet_set, GINT_TO_POINTER(cs-><API key>)); } } /* set second stop location */ cs-><API key>=cs-><API key>+abs(cs-><API key>-><API key>); if(cs-><API key>>tot_packet_amount){ cs-><API key>=tot_packet_amount; } } /* no start found */ if(fInfo->num==tot_packet_amount&&compare_start!=0&&compare_stop!=0){ if(cs-><API key>==G_MAXINT32){ printf("Start point couldn't be set, choose a lower compare start"); } } } static void <API key>(gpointer key _U_, gpointer value, gpointer user_data) { frame_info *fInfo=(frame_info*)value; comparestat_t *cs=(comparestat_t*)user_data; gdouble delta, average; gboolean show_it=FALSE; delta=fabs(get_average(&fInfo->delta,1)); average=fabs(get_average(&cs->stats.tot, cs->stats.num)); /* special case if both are set to zero ignore start and stop numbering */ if(compare_start!=0&&compare_stop!=0){ /* check out if packet is in searched scope */ if((cs-><API key><fInfo->num)&&(cs-><API key>>fInfo->num)){ show_it=TRUE; } else { /* so we won't miss the other file */ if((fInfo->num>cs-><API key>)&&(fInfo->num<cs-><API key>)){ show_it=TRUE; } } } else { show_it=TRUE; } if(show_it){ if(fInfo->fp->count < MERGED_FILES){ printf("Packet id :%i, count:%i Problem:", fInfo->id, fInfo->fp->count); printf("Packet lost\n"); } if(fInfo->fp->count > MERGED_FILES){ printf("Packet id :%i, count:%i Problem:", fInfo->id, fInfo->fp->count); printf("More than two packets\n"); if(fInfo->fp->cksum == WRONG_CHKSUM){ printf("Checksum error over IP header\n"); } } if(fInfo->fp->count == MERGED_FILES){ if(fInfo->fp->cksum == WRONG_CHKSUM){ printf("Packet id :%i, count:%i Problem:", fInfo->id, fInfo->fp->count); printf("Checksum error over IP header\n"); if(((delta < (average-cs->stats.variance)) || (delta > (average+cs->stats.variance))) && (delta > 0.0) && (cs->stats.variance!=0)){ printf("Not arrived in time\n"); } if((nstime_cmp(&fInfo->fp->predecessor_time, &fInfo->zebra_time)>0||nstime_cmp(&fInfo->fp->partner->fp->predecessor_time, &fInfo->fp->partner->zebra_time)>0) && (fInfo->zebra_time.nsecs!=MERGED_FILES) && ON_method){ printf("Not correct order\n"); } } else if(((delta < (average-cs->stats.variance)) || (delta > (average+cs->stats.variance))) && (delta > 0.0) && (cs->stats.variance!=0)) { printf("Packet id :%i, count:%i Problem:", fInfo->id, fInfo->fp->count); printf("Package not arrived in time\n"); if((nstime_cmp(&fInfo->fp->predecessor_time, &fInfo->zebra_time)>0||nstime_cmp(&fInfo->fp->partner->fp->predecessor_time, &fInfo->fp->partner->zebra_time)>0) && fInfo->zebra_time.nsecs != MERGED_FILES && ON_method){ printf("Not correct order\n"); } } else if((nstime_cmp(&fInfo->fp->predecessor_time, &fInfo->zebra_time)>0||nstime_cmp(&fInfo->fp->partner->fp->predecessor_time, &fInfo->fp->partner->zebra_time)>0) && fInfo->zebra_time.nsecs != MERGED_FILES && ON_method){ printf("Packet id :%i, count:%i Problem:", fInfo->id, fInfo->fp->count); printf("Not correct order\n"); } } } } /* This callback is used when tshark wants us to draw/update our * data to the output device. Since this is tshark only output is * stdout. * TShark will only call this callback once, which is when tshark has * finished reading all packets and exists. * If used with wireshark this may be called any time, perhaps once every 3 * seconds or so. * This function may even be called in parallell with (*reset) or (*draw) * so make sure there are no races. The data in the rpcstat_t can thus change * beneath us. Beware. */ static void comparestat_draw(void *prs) { comparestat_t *cs=(comparestat_t *)prs; GString *filter_str = g_string_new(""); const gchar *statis_string; guint32 first_file_amount, second_file_amount; /* initial steps, clear all data before start*/ cs->zebra_time.secs=0; cs->zebra_time.nsecs=1; nstime_set_unset(&cs->current_time); cs->ip_ttl_list=g_array_new(FALSE, FALSE, sizeof(guint8)); cs->last_hit=FALSE; cs->start_ongoing_hits=0; cs->stop_ongoing_hits=0; cs-><API key>=G_MAXINT32; cs-><API key>=G_MAXINT32; cs-><API key>=G_MAXINT32; cs-><API key>=G_MAXINT32; cs->first_file_amount=0; cs->second_file_amount=0; time_stat_init(&cs->stats); cs->ip_id_set=g_hash_table_new(NULL, NULL); <API key>(cs->packet_set, <API key>, cs); /* set up TTL choice if only one number found */ if(TTL_method&&cs->ip_ttl_list->len==1){ g_array_append_val(cs->ip_ttl_list, g_array_index(cs->ip_ttl_list, guint8, 1)); } <API key>(cs->packet_set, <API key>,cs); <API key>(cs->packet_set, <API key>, cs); /* remembering file amounts */ first_file_amount=cs->first_file_amount; second_file_amount=cs->second_file_amount; /* reset after numbering */ <API key>(cs->nr_set); /* Variance */ cs->stats.variance=compare_variance; /* add statistic string */ statis_string=g_strdup_printf("Compare Statistics: \nFilter: %s\nNumber of packets total:%i 1st file:%i, 2nd file:%i\nScopes:\t start:%i stop:%i\nand:\t start:%i stop:%i\nEqual packets: %i \nAllowed variation: %f \nAverage time difference: %f\n", cs->filter ? cs->filter : "", (first_file_amount+second_file_amount), first_file_amount, second_file_amount, cs-><API key>, cs-><API key>, cs-><API key>, cs-><API key>, cs->stats.num, cs->stats.variance, fabs(get_average(&cs->stats.tot, cs->stats.num))); printf("\n"); printf("===================================================================\n"); printf("%s", statis_string); <API key>(cs->ip_id_set, <API key>, cs); printf("===================================================================\n"); g_string_free(filter_str, TRUE); <API key>(cs->ip_id_set); g_array_free(cs->ip_ttl_list, TRUE); } /* When called, this function will create a new instance of comparestat. * This function is called from tshark when it parses the -z compare, arguments * and it creates a new instance to store statistics in and registers this * new instance for the compare tap. */ static void comparestat_init(const char *opt_arg, void* userdata _U_) { comparestat_t *cs; const char *filter=NULL; GString *error_string; gint start, stop,ttl, order, pos=0; gdouble variance; if(sscanf(opt_arg,"compare,%d,%d,%d,%d,%lf%n",&start, &stop, &ttl, &order, &variance, &pos)==5){ if(pos){ if(*(opt_arg+pos)==',') filter=opt_arg+pos+1; else filter=opt_arg+pos; } else { filter=NULL; } } else { fprintf(stderr, "tshark: invalid \"-z compare,<start>,<stop>,<ttl[0|1]>,<order[0|1]>,<variance>[,<filter>]\" argument\n"); exit(1); } compare_variance=variance; compare_start=start; compare_stop=stop; TTL_method=ttl; ON_method=order; cs=g_new(comparestat_t,1); nstime_set_unset(&cs->current_time); cs->ip_ttl_list=g_array_new(FALSE, FALSE, sizeof(guint8)); cs->last_hit=FALSE; cs->start_ongoing_hits=0; cs->stop_ongoing_hits=0; cs-><API key>=G_MAXINT32; cs-><API key>=G_MAXINT32; cs-><API key>=G_MAXINT32; cs-><API key>=G_MAXINT32; cs->first_file_amount=0; cs->second_file_amount=0; cs->zebra_time.secs=0; cs->zebra_time.nsecs=1; cs->nr_set=g_hash_table_new(NULL, NULL); /* microsecond precision */ <API key>(TS_PREC_AUTO_NSEC); if(filter){ cs->filter=g_strdup(filter); } else { cs->filter=NULL; } /* create a Hash to count the packets with the same ip.id */ cs->packet_set=g_hash_table_new(NULL, NULL); error_string=<API key>("ip", cs, filter, 0, comparestat_reset, comparestat_packet, comparestat_draw); if(error_string){ /* error, we failed to attach to the tap. clean up */ g_free(cs->filter); <API key>(cs->packet_set); g_free(cs); fprintf(stderr, "tshark: Couldn't register compare tap: %s\n", error_string->str); g_string_free(error_string, TRUE); exit(1); } } void <API key>(void) { <API key>("compare,", comparestat_init,NULL); }
using Bifrost.Slack.UI.WinPhone.Common; using Cirrious.MvvmCross.WindowsCommon.Views; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Graphics.Display; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Bifrost.Slack.UI.WinPhone.Views { <summary> An empty page that can be used on its own or navigated to within a Frame. </summary> public sealed partial class AllUsersView : MvxWindowsPage { private NavigationHelper navigationHelper; public AllUsersView() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); NavigationCacheMode = NavigationCacheMode.Enabled; } <summary> Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>. </summary> public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } #region NavigationHelper registration <summary> The methods provided in this section are simply used to allow NavigationHelper to respond to the page's navigation methods. <para> Page specific logic should be placed in event handlers for the <see cref="NavigationHelper.LoadState"/> and <see cref="NavigationHelper.SaveState"/>. The navigation parameter is available in the LoadState method in addition to page state preserved during an earlier session. </para> </summary> <param name="e">Provides data for navigation methods and event handlers that cannot cancel the navigation request.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); this.navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); this.navigationHelper.OnNavigatedFrom(e); } #endregion } }
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* vim: set sw=4 sts=4 ts=4 expandtab: */ #ifndef RSVG_H #define RSVG_H #include <glib-object.h> #include <gio/gio.h> #include <gdk-pixbuf/gdk-pixbuf.h> G_BEGIN_DECLS #define RSVG_TYPE_HANDLE (<API key> ()) #define RSVG_HANDLE(obj) (<API key> ((obj), RSVG_TYPE_HANDLE, RsvgHandle)) #define RSVG_HANDLE_CLASS(klass) (<API key> ((klass), RSVG_TYPE_HANDLE, RsvgHandleClass)) #define RSVG_IS_HANDLE(obj) (<API key> ((obj), RSVG_TYPE_HANDLE)) #define <API key>(klass) (<API key> ((klass), RSVG_TYPE_HANDLE)) #define <API key>(obj) (<API key> ((obj), RSVG_TYPE_HANDLE, RsvgHandleClass)) GType <API key> (void); /** * An enumeration representing possible error domains */ typedef enum { RSVG_ERROR_FAILED } RsvgError; #define RSVG_ERROR (rsvg_error_quark ()) GQuark rsvg_error_quark (void) G_GNUC_CONST; /** * The RsvgHandle is an object representing the parsed form of a SVG */ typedef struct _RsvgHandle RsvgHandle; typedef struct RsvgHandlePrivate RsvgHandlePrivate; typedef struct _RsvgHandleClass RsvgHandleClass; typedef struct _RsvgDimensionData RsvgDimensionData; typedef struct _RsvgPositionData RsvgPositionData; struct _RsvgHandleClass { GObjectClass parent; gpointer _abi_padding[15]; }; struct _RsvgHandle { GObject parent; RsvgHandlePrivate *priv; gpointer _abi_padding[15]; }; /* RsvgDimensionData */ struct _RsvgDimensionData { /** * SVG's width, in pixels */ int width; /** * SVG's height, in pixels */ int height; gdouble em; gdouble ex; }; /** * Position of an SVG fragment. **/ struct _RsvgPositionData { int x; int y; }; void rsvg_init (void); void rsvg_term (void); void <API key> (double dpi); void <API key> (double dpi_x, double dpi_y); void rsvg_handle_set_dpi (RsvgHandle * handle, double dpi); void <API key> (RsvgHandle * handle, double dpi_x, double dpi_y); RsvgHandle *rsvg_handle_new (void); gboolean rsvg_handle_write (RsvgHandle * handle, const guchar * buf, gsize count, GError ** error); gboolean rsvg_handle_close (RsvgHandle * handle, GError ** error); GdkPixbuf *<API key> (RsvgHandle * handle); GdkPixbuf *<API key> (RsvgHandle * handle, const char *id); const char *<API key> (RsvgHandle * handle); void <API key> (RsvgHandle * handle, const char *base_uri); void <API key> (RsvgHandle * handle, RsvgDimensionData * dimension_data); gboolean <API key> (RsvgHandle * handle, RsvgDimensionData * dimension_data, const char *id); gboolean <API key> (RsvgHandle * handle, RsvgPositionData * position_data, const char *id); gboolean rsvg_handle_has_sub (RsvgHandle * handle, const char *id); /* GIO APIs */ typedef enum { <API key> = 0 } RsvgHandleFlags; void <API key> (RsvgHandle *handle, GFile *base_file); gboolean <API key> (RsvgHandle *handle, GInputStream *stream, GCancellable *cancellable, GError **error); RsvgHandle *<API key> (GFile *file, RsvgHandleFlags flags, GCancellable *cancellable, GError **error); RsvgHandle *<API key> (GInputStream *input_stream, GFile *base_file, RsvgHandleFlags flags, GCancellable *cancellable, GError **error); /* Accessibility API */ const char *<API key> (RsvgHandle * handle); const char *<API key> (RsvgHandle * handle); const char *<API key> (RsvgHandle * handle); RsvgHandle *<API key> (const guint8 * data, gsize data_len, GError ** error); RsvgHandle *<API key> (const gchar * file_name, GError ** error); #ifndef <API key> void rsvg_handle_free (RsvgHandle * handle); /** * RsvgSizeFunc (): * @width: Pointer to where to set/store the width * @height: Pointer to where to set/store the height * @user_data: User data pointer * * Function to let a user of the library specify the SVG's dimensions * @width: the ouput width the SVG should be * @height: the output height the SVG should be * @user_data: user data * * Deprecated: Set up a cairo matrix and use <API key>() instead. */ typedef void (*RsvgSizeFunc) (gint * width, gint * height, gpointer user_data); void <API key> (RsvgHandle * handle, RsvgSizeFunc size_func, gpointer user_data, GDestroyNotify user_data_destroy); /* GdkPixbuf convenience API */ GdkPixbuf *<API key> (const gchar * file_name, GError ** error); GdkPixbuf *<API key> (const gchar * file_name, double x_zoom, double y_zoom, GError ** error); GdkPixbuf *<API key> (const gchar * file_name, gint width, gint height, GError ** error); GdkPixbuf *<API key> (const gchar * file_name, gint max_width, gint max_height, GError ** error); GdkPixbuf *<API key> (const gchar * file_name, double x_zoom, double y_zoom, gint max_width, gint max_height, GError ** error); #endif /* <API key> */ G_END_DECLS #endif /* RSVG_H */
// This program is free software: you can redistribute it and/or modify // the Free Software Foundation, version 2.0. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // A copy of the GPL 2.0 should have been included with the program. // Official SVN repository and contact information can be found at #ifndef _VERTEXMANAGER_H #define _VERTEXMANAGER_H #include "CPMemory.h" #include "VertexLoader.h" #include "VertexManagerBase.h" namespace DX9 { class VertexManager : public ::VertexManager { public: NativeVertexFormat* <API key>(); void GetElements(NativeVertexFormat* format, D3DVERTEXELEMENT9** elems, int* num); void CreateDeviceObjects(); void <API key>(); private: u32 CurrentVBufferIndex; u32 CurrentVBufferSize; u32 CurrentIBufferIndex; u32 CurrentIBufferSize; u32 NumVBuffers; u32 CurrentVBuffer; u32 CurrentIBuffer; <API key> *VBuffers; <API key> *IBuffers; void PrepareVBuffers(int stride); void DrawVB(int stride); void DrawVA(int stride); // temp void vFlush(); }; } #endif
#pragma once #include <d3d12.h> #include <cassert> #include <wrl/client.h> #include "Emu/Memory/vm.h" #include "Emu/RSX/GCM.h" using namespace Microsoft::WRL; #define CHECK_HRESULT(expr) if (HRESULT hr = (expr)) if (FAILED(hr)) throw EXCEPTION("HRESULT = 0x%x", hr) /** * Send data to dst pointer without polluting cache. * Usefull to write to mapped memory from upload heap. */ inline void streamToBuffer(void* dst, void* src, size_t sizeInBytes) { for (int i = 0; i < sizeInBytes / 16; i++) { const __m128i &srcPtr = _mm_loadu_si128((__m128i*) ((char*)src + i * 16)); _mm_stream_si128((__m128i*)((char*)dst + i * 16), srcPtr); } } /** * copy src to dst pointer without polluting cache. * Usefull to write to mapped memory from upload heap. */ inline void streamBuffer(void* dst, void* src, size_t sizeInBytes) { // Assume 64 bytes cache line int offset = 0; bool isAligned = !((size_t)src & 15); for (offset = 0; offset < sizeInBytes - 64; offset += 64) { char *line = (char*)src + offset; char *dstline = (char*)dst + offset; // prefetch next line _mm_prefetch(line + 16, _MM_HINT_NTA); __m128i srcPtr = isAligned ? _mm_load_si128((__m128i *)line) : _mm_loadu_si128((__m128i *)line); _mm_stream_si128((__m128i*)dstline, srcPtr); srcPtr = isAligned ? _mm_load_si128((__m128i *)(line + 16)) : _mm_loadu_si128((__m128i *)(line + 16)); _mm_stream_si128((__m128i*)(dstline + 16), srcPtr); srcPtr = isAligned ? _mm_load_si128((__m128i *)(line + 32)) : _mm_loadu_si128((__m128i *)(line + 32)); _mm_stream_si128((__m128i*)(dstline + 32), srcPtr); srcPtr = isAligned ? _mm_load_si128((__m128i *)(line + 48)) : _mm_loadu_si128((__m128i *)(line + 48)); _mm_stream_si128((__m128i*)(dstline + 48), srcPtr); } memcpy((char*)dst + offset, (char*)src + offset, sizeInBytes - offset); }
#include <linux/kernel.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/unistd.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/mii.h> #include <linux/ethtool.h> #include <linux/phy.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/uaccess.h> /* The Level one LXT970 is used by many boards */ #define MII_LXT970_IER 17 /* Interrupt Enable Register */ #define MII_LXT970_IER_IEN 0x0002 #define MII_LXT970_ISR 18 /* Interrupt Status Register */ #define MII_LXT970_CONFIG 19 /* Configuration Register */ /* The Level one LXT971 is used on some of my custom boards */ /* register definitions for the 971 */ #define MII_LXT971_IER 18 /* Interrupt Enable Register */ #define MII_LXT971_IER_IEN 0x00f2 #define MII_LXT971_ISR 19 /* Interrupt Status Register */ /* register definitions for the 973 */ #define MII_LXT973_PCR 16 /* Port Configuration Register */ #define PCR_FIBER_SELECT 1 MODULE_DESCRIPTION("Intel LXT PHY driver"); MODULE_AUTHOR("Andy Fleming"); MODULE_LICENSE("GPL"); static int <API key>(struct phy_device *phydev) { int err; err = phy_read(phydev, MII_BMSR); if (err < 0) return err; err = phy_read(phydev, MII_LXT970_ISR); if (err < 0) return err; return 0; } static int lxt970_config_intr(struct phy_device *phydev) { int err; if(phydev->interrupts == <API key>) err = phy_write(phydev, MII_LXT970_IER, MII_LXT970_IER_IEN); else err = phy_write(phydev, MII_LXT970_IER, 0); return err; } static int lxt970_config_init(struct phy_device *phydev) { int err; err = phy_write(phydev, MII_LXT970_CONFIG, 0); return err; } static int <API key>(struct phy_device *phydev) { int err = phy_read(phydev, MII_LXT971_ISR); if (err < 0) return err; return 0; } static int lxt971_config_intr(struct phy_device *phydev) { int err; if(phydev->interrupts == <API key>) err = phy_write(phydev, MII_LXT971_IER, MII_LXT971_IER_IEN); else err = phy_write(phydev, MII_LXT971_IER, 0); return err; } static int lxt973_probe(struct phy_device *phydev) { int val = phy_read(phydev, MII_LXT973_PCR); if (val & PCR_FIBER_SELECT) { /* * If fiber is selected, then the only correct setting * is 100Mbps, full duplex, and auto negotiation off. */ val = phy_read(phydev, MII_BMCR); val |= (BMCR_SPEED100 | BMCR_FULLDPLX); val &= ~BMCR_ANENABLE; phy_write(phydev, MII_BMCR, val); /* Remember that the port is in fiber mode. */ phydev->priv = lxt973_probe; } else { phydev->priv = NULL; } return 0; } static int lxt973_config_aneg(struct phy_device *phydev) { /* Do nothing if port is in fiber mode. */ return phydev->priv ? 0 : genphy_config_aneg(phydev); } static struct phy_driver lxt970_driver = { .phy_id = 0x78100000, .name = "LXT970", .phy_id_mask = 0xfffffff0, .features = PHY_BASIC_FEATURES, .flags = PHY_HAS_INTERRUPT, .config_init = lxt970_config_init, .config_aneg = genphy_config_aneg, .read_status = genphy_read_status, .ack_interrupt = <API key>, .config_intr = lxt970_config_intr, .driver = { .owner = THIS_MODULE,}, }; static struct phy_driver lxt971_driver = { .phy_id = 0x001378e0, .name = "LXT971", .phy_id_mask = 0xfffffff0, .features = PHY_BASIC_FEATURES, .flags = PHY_HAS_INTERRUPT, .config_aneg = genphy_config_aneg, .read_status = genphy_read_status, .ack_interrupt = <API key>, .config_intr = lxt971_config_intr, .driver = { .owner = THIS_MODULE,}, }; static struct phy_driver lxt973_driver = { .phy_id = 0x00137a10, .name = "LXT973", .phy_id_mask = 0xfffffff0, .features = PHY_BASIC_FEATURES, .flags = 0, .probe = lxt973_probe, .config_aneg = lxt973_config_aneg, .read_status = genphy_read_status, .driver = { .owner = THIS_MODULE,}, }; static int __init lxt_init(void) { int ret; ret = phy_driver_register(&lxt970_driver); if (ret) goto err1; ret = phy_driver_register(&lxt971_driver); if (ret) goto err2; ret = phy_driver_register(&lxt973_driver); if (ret) goto err3; return 0; err3: <API key>(&lxt971_driver); err2: <API key>(&lxt970_driver); err1: return ret; } static void __exit lxt_exit(void) { <API key>(&lxt970_driver); <API key>(&lxt971_driver); <API key>(&lxt973_driver); } module_init(lxt_init); module_exit(lxt_exit); <<<< HEAD static struct mdio_device_id __maybe_unused lxt_tbl[] = { ==== static struct mdio_device_id lxt_tbl[] = { >>>> <SHA1-like> { 0x78100000, 0xfffffff0 }, { 0x001378e0, 0xfffffff0 }, { 0x00137a10, 0xfffffff0 }, { } }; MODULE_DEVICE_TABLE(mdio, lxt_tbl);
# postags.py # List of function POS tags and content POS tags # $Id: postags.py 1657 2006-06-04 03:03:05Z turian $ # Function POS tags function = { "AUX": 1, "AUXG": 1, "CC": 1, "DT": 1, "EX": 1, "IN": 1, "MD": 1, "PDT": 1, "POS": 1, "PRP": 1, "PRP$": 1, "RP": 1, "TO": 1, "WDT": 1, "WP": 1, "WP$": 1, "WRB": 1, " "$": 1, ".": 1, ",": 1, ":": 1, "''": 1, "``": 1, "-LRB-": 1, "-RRB-": 1, "-NONE-": 1, } # Content POS tags content = { "CD": 1, "FW": 1, "JJ": 1, "JJR": 1, "JJS": 1, "LS": 1, "NN": 1, "NNS": 1, "NNP": 1, "NNPS": 1, "RB": 1, "RBR": 1, "RBS": 1, "SYM": 1, "UH": 1, "VB": 1, "VBD": 1, "VBG": 1, "VBN": 1, "VBP": 1, "VBZ": 1, }
layout: api title: v0.6.7 categories: api navigation: version: v0.6.7 navigation: - title: mapbox.map items: - map.smooth - map.center - map.zoom - map.centerzoom - map.getExtent - map.setExtent - map.setZoomRange - map.setPanLimits - map.setSize - map.zoomBy - map.zoomByAbout - map.panBy - map.draw - map.requestRedraw - map.refresh - Separator: Properties - map.coordinate - map.dimensions - map.parent - Separator: Conversions - map.pointLocation - map.pointCoordinate - map.locationPoint - map.locationCoordinate - map.coordinatePoint - map.coordinateLocation - Separator: Layer management - map.addLayer - map.addTileLayer - map.removeLayer - map.removeLayerAt - map.disableLayer - map.disableLayerAt - map.enableLayer - map.enableLayerAt - map.getLayer - map.getLayers - map.getLayerAt - Separator: Easing - map.ease - Separator: User interface - map.ui - map.ui.fullscreen - map.ui.hash - map.ui.zoombox - map.ui.zoomer - map.ui.attribution - map.ui.legend - map.ui.pointselector - map.ui.boxselector - map.ui.refresh - Separator: Interaction - map.interaction - map.interaction.auto - map.interaction.refresh - Separator: Events - map.addCallback - map.removeCallback - Event "zoomed" - Event "panned" - Event "resized" - Event "extentset" - Event "drawn" - title: mapbox.load items: - title: mapbox.auto items: - title: mapbox.layer items: - layer.id - layer.named - layer.url - layer.tilejson - layer.composite - layer.parent - title: mapbox.markers.layer items: - markers.named - markers.factory - markers.features - markers.add_feature - markers.sort - markers.filter - markers.key - markers.url - markers.id - markers.csv - markers.extent - markers.addCallback - markers.removeCallback - markers.markers - title: mapbox.markers.interaction items: - interaction.remove - interaction.add - interaction.hideOnMove - interaction.showOnHover - interaction.exclusive - interaction.formatter - title: mapbox.ease items: - ease.map - ease.from - ease.to - ease.zoom - ease.optimal - ease.location - ease.t - ease.future - ease.easing - ease.path - ease.run - ease.running - ease.stop <div></div><h1>Map</h1> <div id="content-undefined"class="depth-1"><p>Maps are the central element of the Javascript API - the map object manages tile layers, contains UI elements, and provides many types of interactivity. </p> </div><h2 id="mapbox.map">mapbox.map<span class="bracket">(</span><span class="args">element [, layers] [, dimensions] [, eventHandlers]</span><span class="bracket">)</span></h2> <div id="content-mapbox.map"class="depth-2"><p>Create a map on the current page. </p> <p><em>Arguments:</em> </p> <ul> <li><code>element</code> must be the <code>id</code> of an element on the page, or an element itself. Typically maps are created within <code>&lt;div&gt;</code> elements. This element should have a <em>size</em>: whether specified with external CSS or an inline style like <code>style=&quot;width:600px;height:400px&quot;</code></li> <li><code>layers</code> can be a layer created with <a href="#mapbox.layer"><code>mapbox.layer()</code></a>, an array of such layers, or omitted</li> <li><code>dimensions</code> can be an object with <code>x</code> and <code>y</code> attributes representing the width and height in pixels</li> <li><code>eventHandlers</code> can be an array of event handlers, including any of the following:<ul> <li><code>easey_handlers.DragHandler()</code></li> <li><code>easey_handlers.DoubleClickHandler()</code></li> <li><code>easey_handlers.MouseWheelHandler()</code></li> <li><code>easey_handlers.TouchHandler()</code></li> <li><code>MM.DragHandler()</code></li> <li><code>MM.DoubleClickHandler()</code></li> <li><code>MM.MouseWheelHandler()</code></li> <li><code>MM.TouchHandler()</code></li> </ul> </li> </ul> <p><em>Returns</em> a map object, which has the following methods: </p> <p><em>Example:</em> </p> <pre><code>// for this to work, you&#39;ll need an element like // &lt;div id=&quot;map&quot;&gt;&lt;/div&gt; on your page var map = mapbox.map(&#39;map&#39;);</code></pre> </div><h3 id="map.smooth">map.smooth<span class="bracket">(</span><span class="args">value</span><span class="bracket">)</span></h3> <div id="content-map.smooth"class="depth-3"><p>Enable or disable inertial panning on maps. By default, maps smoothly pan and zoom with inertia. </p> <p><em>Arguments:</em> </p> <ul> <li><code>value</code> must be <code>true</code> or <code>false</code> to set whether the map uses inertia.</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example:</em> </p> <pre><code>map.smooth(false); // disable inertial panning</code></pre> </div><h3 id="map.center">map.center<span class="bracket">(</span><span class="args">centerpoint [, animate]</span><span class="bracket">)</span></h3> <div id="content-map.center"class="depth-3"><p>Center the map on a geographical location, or get its current center. </p> <p><em>Arguments:</em> </p> <ul> <li><code>centerpoint</code> can be an object with <code>lat</code> and <code>lon</code> values, like <code>{ lat: 10, lon: -88 }</code>, or ommitted to get the map&#39;s current location</li> <li><code>animate</code> can be <code>true</code> to animate the map&#39;s movement, or omitted to move immediately</li> </ul> <p><em>Returns</em> the map object if arguments are given, the map&#39;s center location (in the same form as specified in <code>centerpoint</code>) otherwise. </p> <p><em>Example:</em> </p> <pre><code>// center the map on Manhattan map.center({ lat: 40.74, lon: -73.98 });</code></pre> </div><h3 id="map.zoom">map.zoom<span class="bracket">(</span><span class="args">zoom [, animate]</span><span class="bracket">)</span></h3> <div id="content-map.zoom"class="depth-3"><p>Set the map&#39;s zoom level, or get its current zoom level. </p> <p><em>Arguments:</em> </p> <ul> <li><code>zoom</code> can be zoom level in the range supported by the map&#39;s layers (an integer from 0-20, typically), or omitted to get the current zoom level..</li> <li><code>animate</code> can be <code>true</code> to animate the map&#39;s movement, or omitted to move immediately.</li> </ul> <p><em>Returns</em> the map object if arguments are given, the map&#39;s current zoom level otherwise. </p> <p><strong>Example:</strong> </p> <pre><code>// zoom to z10 and animate the transition map.zoom(10, true);</code></pre> </div><h3 id="map.centerzoom">map.centerzoom<span class="bracket">(</span><span class="args">center, zoom [, animate]</span><span class="bracket">)</span></h3> <div id="content-map.centerzoom"class="depth-3"><p>Set the map&#39;s zoom level and centerpoint simultaneously. Especially with the third argument, <code>animate</code>, set to <code>true</code>, this allows for a better animation effect. </p> <p><em>Arguments:</em> </p> <ul> <li><code>centerpoint</code> can be an object with <code>lat</code> and <code>lon</code> values, like <code>{ lat: 10, lon: -88 }</code></li> <li><code>zoom</code> must be zoom level in the range supported by the map&#39;s layers (an integer from 0-20, typically)</li> <li><code>animate</code> can be <code>true</code> to animate the map&#39;s movement, or omitted to move immediately.</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example:</em> </p> <pre><code>// Center the map on Washington, DC, at zoom level 5 map.centerzoom({ lat: 38.9, lon: -77.03 }, 5);</code></pre> </div><h3 id="map.getExtent">map.getExtent<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.getExtent"class="depth-3"><p>Get the extent of the currently visible area. </p> <p><em>Returns</em> an instance of <code>MM.Extent</code>. </p> </div><h3 id="map.setExtent">map.setExtent</h3> <div id="content-map.setExtent"class="depth-3"><p>Modify the center and zoom of the map so that the provided extent is visible. This can be useful because extents - the corners of the map - can implicitly cause the map to &#39;show the whole world&#39; regardless of screen size. </p> <p><em>Arguments:</em> </p> <ul> <li><code>extent</code> can be an instance of <code>MM.Extent</code>, or an array of two locations.</li> <li><code>precise</code> can be <code>true</code> or <code>false</code>. If true, resulting zoom levels may be fractional. (By default, the map&#39;s zoom level is rounded down to keep tile images from blurring.)</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example:</em> </p> <pre><code>// using an extent object: map.setExtent(new MM.Extent(80, -170, -70, 170)); // this call can also be expressed as: map.setExtent([{ lat: 80, lon: -170 }, { lat: -70, lon: 170 }]);</code></pre> </div><h3 id="map.setZoomRange">map.setZoomRange<span class="bracket">(</span><span class="args">minZoom, maxZoom</span><span class="bracket">)</span></h3> <div id="content-map.setZoomRange"class="depth-3"><p>Set the map&#39;s minimum and maximum zoom levels. </p> <p><em>Arguments:</em> </p> <ul> <li><code>minZoom</code> is the minimum zoom level</li> <li><code>maxZoom</code> is the maximum zoom level</li> </ul> <p><em>Returns</em> the map object. </p> <p><strong>Example:</strong> </p> <pre><code>map.setZoomRange(3, 17);</code></pre> </div><h3 id="map.setPanLimits">map.setPanLimits<span class="bracket">(</span><span class="args">locations</span><span class="bracket">)</span></h3> <div id="content-map.setPanLimits"class="depth-3"><p>Set the map&#39;s panning limits. </p> <p><em>Arguments:</em> </p> <ul> <li><code>locations</code> must be either an instance of MM.Extent or an array of two locations in <code>{ lat: 0, lon: 0 }</code> form. The order of locations doesn&#39;t matter - they&#39;re sorted internally.</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example</em>: </p> <pre><code>map.setPanLimits([{ lat: -20, lon: 0 }, { lat: 0, lon: 20 }]); // or with an Extent object map.setPanLimits(new MM.Extent(0, -20, -20, 0));</code></pre> </div><h3 id="map.setSize">map.setSize<span class="bracket">(</span><span class="args">dimensions</span><span class="bracket">)</span></h3> <div id="content-map.setSize"class="depth-3"><p>Set the map&#39;s dimensions. This sets <code>map.autoSize</code> to false to prevent further automatic resizing. </p> <p><em>Arguments:</em> </p> <ul> <li><code>dimensions</code> is an object with <code>x</code> and <code>y</code> properties representing the map&#39;s new dimensions in pixels.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.zoomBy">map.zoomBy<span class="bracket">(</span><span class="args">zoomOffset</span><span class="bracket">)</span></h3> <div id="content-map.zoomBy"class="depth-3"><p>Change zoom level by the provided offset. </p> <p><em>Arguments:</em> </p> <ul> <li><code>zoomOffset</code> is the amount to zoom by. Positive offsets zoom in. Negative offsets zoom out.</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example:</em> </p> <pre><code>// zoom in by one zoom level map.zoomBy(1); // zoom out by two zoom levels map.zoomBy(-2);</code></pre> </div><h3 id="map.zoomByAbout">map.zoomByAbout<span class="bracket">(</span><span class="args">zoomOffset, point</span><span class="bracket">)</span></h3> <div id="content-map.zoomByAbout"class="depth-3"><p>Change the zoom level by the provided offset, while maintaining the same location at the provided point. This is used by <code>MM.DoubleClickHandler</code>. </p> <ul> <li><code>zoomOffset</code> is the amount to zoom by. Positive offsets zoom in. Negative offsets zoom out.</li> <li><code>point</code> is the point on the map that maintains its current location.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.panBy">map.panBy<span class="bracket">(</span><span class="args">x, y</span><span class="bracket">)</span></h3> <div id="content-map.panBy"class="depth-3"><p>Pan by the specified distances. </p> <p><em>Arguments:</em> </p> <ul> <li><code>x</code> the distance to pan horizontally. Positive values pan right, negative values pan left.</li> <li><code>y</code> the distance to pan vertically. Positive values pan down, negative values pan up.</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example:</em> </p> <pre><code>// pan right and down by one pixel map.panBy(1, 1);</code></pre> </div><h3 id="map.draw">map.draw<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.draw"class="depth-3"><p>Redraw the map and its layers. First, the map enforces its coordLimits on its center and zoom. If autoSize is true, the map&#39;s dimensions are recalculated from its parent. Lastly, each of the map&#39;s layers is drawn. </p> </div><h3 id="map.requestRedraw">map.requestRedraw<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.requestRedraw"class="depth-3"><p>Request a &quot;lazy&quot; call to draw in 1 second. This is useful if you&#39;re responding to lots of user input and know that you&#39;ll need to redraw the map eventually, but not immediately. </p> </div><h3 id="map.refresh">map.refresh<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.refresh"class="depth-3"><p>Refreshes map.ui and map.interaction to reflect any layer changes. </p> </div><div class="separator" id="Properties">Properties</div><div id="content-Properties"class="depth-0"></div><h3 id="map.coordinate">map.coordinate</h3> <div id="content-map.coordinate"class="depth-3"><p>The map&#39;s current center coordinate. </p> </div><h3 id="map.dimensions">map.dimensions</h3> <div id="content-map.dimensions"class="depth-3"><p>An object with <code>x</code> and <code>y</code> attributes expressing the dimensions of the map in pixels. </p> </div><h3 id="map.parent">map.parent</h3> <div id="content-map.parent"class="depth-3"><p>The DOM element containing the map. </p> </div><div class="separator" id="Conversions">Conversions</div><div id="content-Conversions"class="depth-0"></div><h3 id="map.pointLocation">map.pointLocation<span class="bracket">(</span><span class="args">point</span><span class="bracket">)</span></h3> <div id="content-map.pointLocation"class="depth-3"><p>Convert a screen point to a location (longitude and latitude). </p> <p><em>Arguments:</em> </p> <ul> <li><code>point</code> is an instance of <code>MM.Point</code> or an object with <code>x</code> and <code>y</code> properties.</li> </ul> <p><em>Returns</em> an object with <code>lat</code> and <code>lon</code> properties indicating the latitude and longitude of the point on the globe. </p> <p><em>Example:</em> </p> <pre><code>// get the geographical location of the top-left corner of the map var top_left = map.pointLocation({ x: 0, y: 0});</code></pre> </div><h3 id="map.pointCoordinate">map.pointCoordinate<span class="bracket">(</span><span class="args">point</span><span class="bracket">)</span></h3> <div id="content-map.pointCoordinate"class="depth-3"><p>Convert a screen point to a tile coordinate. </p> <p><em>Arguments:</em> </p> <ul> <li><code>point</code> is an instance of <code>MM.Point</code> or an object with <code>x</code> and <code>y</code> properties.</li> </ul> <p><em>Returns</em> an instance of <code>MM.Coordinate</code> - an object with <code>column</code>, <code>row</code>, and <code>zoom</code> properties indicating the coordinate of the point. The <code>zoom</code> of the point will be same as the current zoom level of the map. </p> <p><em>Example:</em> </p> <pre><code>// get the coordinate location of the top-left corner of the map var top_left = map.coordinateLocation({ x: 0, y: 0});</code></pre> </div><h3 id="map.locationPoint">map.locationPoint<span class="bracket">(</span><span class="args">location</span><span class="bracket">)</span></h3> <div id="content-map.locationPoint"class="depth-3"><p>Convert a location to a screen point. </p> <p><em>Arguments:</em> </p> <ul> <li><code>location</code> is an instance of <code>MM.Location</code> or an object with <code>lat</code> and <code>lon</code> properties.</li> </ul> <p><em>Returns</em> an instance of <code>MM.Point</code>. </p> </div><h3 id="map.locationCoordinate">map.locationCoordinate<span class="bracket">(</span><span class="args">location</span><span class="bracket">)</span></h3> <div id="content-map.locationCoordinate"class="depth-3"><p>Convert a location to a tile coordinate. </p> <p><em>Arguments:</em> </p> <ul> <li><code>location</code> is an instance of <code>MM.Location</code> or an object with <code>lat</code> and <code>lon</code> properties.</li> </ul> <p><em>Returns</em> an instance of <code>MM.Coordinate</code>. </p> </div><h3 id="map.coordinatePoint">map.coordinatePoint<span class="bracket">(</span><span class="args">coordinate</span><span class="bracket">)</span></h3> <div id="content-map.coordinatePoint"class="depth-3"><p>Convert a tile coordinate to a screen point. </p> <p><em>Arguments:</em> </p> <ul> <li><code>coordinate</code> is an instance of <code>MM.Coordinate</code>.</li> </ul> <p><em>Returns</em> an instance of <code>MM.Point</code>. </p> </div><h3 id="map.coordinateLocation">map.coordinateLocation<span class="bracket">(</span><span class="args">coordinate</span><span class="bracket">)</span></h3> <div id="content-map.coordinateLocation"class="depth-3"><p>Convert a tile coordinate to a location (longitude and latitude). </p> <p><em>Arguments:</em> </p> <ul> <li><code>coordinate</code> is an instance of <code>MM.Coordinate</code>.</li> </ul> <p><em>Returns</em> and instance of <code>MM.Location</code>. </p> </div><div class="separator" id="Layer_management">Layer management</div><div id="<API key>"class="depth-0"></div><h3 id="map.addLayer">map.addLayer<span class="bracket">(</span><span class="args">layer</span><span class="bracket">)</span></h3> <div id="content-map.addLayer"class="depth-3"><p>Add a layer to the map, above other layers. </p> <p><em>Arguments:</em> </p> <ul> <li><code>layer</code> is a layer object, such as an instance of <code>mapbox.layer()</code> or <code>mapbox.markers.layer()</code>.</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example:</em> </p> <pre><code>// add a layer to the map map.addLayer(mapbox.layer().id(&#39;examples.map-dg7cqh4z&#39;));</code></pre> </div><h3 id="map.addTileLayer">map.addTileLayer<span class="bracket">(</span><span class="args">layer</span><span class="bracket">)</span></h3> <div id="content-map.addTileLayer"class="depth-3"><p>Add a tile layer to the map, below any marker layers to prevent them from being covered up. </p> <ul> <li><code>layer</code> is a layer object, such as an instance of <code>mapbox.layer()</code>.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.removeLayer">map.removeLayer<span class="bracket">(</span><span class="args">layer</span><span class="bracket">)</span></h3> <div id="content-map.removeLayer"class="depth-3"><p>Remove the provided layer from the map. </p> <p><em>Arguments:</em> </p> <ul> <li><code>layer</code> is a layer, or the name of a layer, currently added to the map.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.removeLayerAt">map.removeLayerAt<span class="bracket">(</span><span class="args">index</span><span class="bracket">)</span></h3> <div id="content-map.removeLayerAt"class="depth-3"><p>Remove the layer at the provided index. </p> <ul> <li><code>index</code> is a non-negative integer.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.disableLayer">map.disableLayer<span class="bracket">(</span><span class="args">layer</span><span class="bracket">)</span></h3> <div id="content-map.disableLayer"class="depth-3"><p>Disable a layer. Disabled layers maintain their position, but do not get drawn. </p> <p><em>Arguments:</em> </p> <ul> <li><code>layer</code> is the name of a layer currently added to the map.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.disableLayerAt">map.disableLayerAt<span class="bracket">(</span><span class="args">index</span><span class="bracket">)</span></h3> <div id="content-map.disableLayerAt"class="depth-3"><p>Disable a layer at the provided index. Disabled layers maintain their position, but do not get drawn. </p> <p><em>Arguments:</em> </p> <ul> <li><code>index</code> is a non-negative integer representing the position of the layer.</li> </ul> <p><em>Returns</em> the map object. </p> <p><em>Example:</em> </p> <pre><code>// disable the topmost layer in the map map.disableLayerAt(0);</code></pre> </div><h3 id="map.enableLayer">map.enableLayer<span class="bracket">(</span><span class="args">layer</span><span class="bracket">)</span></h3> <div id="content-map.enableLayer"class="depth-3"><p>Enable a previously disabled layer. </p> <p><em>Arguments:</em> </p> <ul> <li><code>layer</code> is the name of a layer currently added to the map.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.enableLayerAt">map.enableLayerAt<span class="bracket">(</span><span class="args">index</span><span class="bracket">)</span></h3> <div id="content-map.enableLayerAt"class="depth-3"><p>Enable the layer at the provided index. </p> <p><em>Arguments:</em> </p> <ul> <li><code>index</code> is a non-negative integer representing the position of the layer to be enabled.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.getLayer">map.getLayer<span class="bracket">(</span><span class="args">name</span><span class="bracket">)</span></h3> <div id="content-map.getLayer"class="depth-3"><p>Get a layer by name. </p> <p><em>Arguments:</em> </p> <ul> <li><code>name</code> is the name of a layer.</li> </ul> <p><em>Returns</em> the layer object. </p> </div><h3 id="map.getLayers">map.getLayers<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.getLayers"class="depth-3"><p><em>Returns</em> a list the map&#39;s layers. </p> </div><h3 id="map.getLayerAt">map.getLayerAt<span class="bracket">(</span><span class="args">index</span><span class="bracket">)</span></h3> <div id="content-map.getLayerAt"class="depth-3"><p>Get the layer at the provided index. </p> <p><em>Arguments</em> </p> <ul> <li><code>index</code> can be a non-negative integer.</li> </ul> <p><em>Returns</em> a layer. </p> </div><div class="separator" id="Easing">Easing</div><div id="content-Easing"class="depth-0"></div><h3 id="map.ease">map.ease</h3> <div id="content-map.ease"class="depth-3"><p>This is an instance of <a href="#mapbox.ease">mapbox.ease</a> attached to the map for convenience. For full documentation take a look at <a href="#mapbox.ease">mapbox.ease</a>. </p> <p><em>Example:</em> </p> <pre><code>map.ease.location({ lat: 10, lon: -88 }).zoom(5).optimal();</code></pre> </div><div class="separator" id="User_interface">User interface</div><div id="<API key>"class="depth-0"></div><h3 id="map.ui">map.ui</h3> <div id="content-map.ui"class="depth-3"><p>The API provides a set of UI elements that can be freely mixed &amp; matched, as well as styled beyond the default (provided in the <code>mapbox.css</code> stylesheet). Maps created with <a href="#mapbox.map"><code>mapbox.map</code></a> have an array of pre-initialized UI elements at <code>.ui</code>. All UI elements support the simple operations <code>.add()</code> and <code>.remove()</code> to add &amp; remove them from the map. </p> </div><h4 id=".add">.add<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h4> <div id="content-.add"class="depth-4"><p>Add the UI element to the map. Add the HTML elements that the UI element manages (if any) to the map element, and bind any events. </p> <p><em>Example:</em> </p> <pre><code>// enable the zoomer control. adds + and - buttons to the map map.ui.zoomer.add();</code></pre> </div><h4 id=".remove">.remove<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h4> <div id="content-.remove"class="depth-4"><p>Remove the UI element from the map. Removes the HTML elements from the map, if any, and removes listeners, if any. </p> <pre><code>// remove the fullscreen control from the map visually and functionally map.ui.fullscreen.remove();</code></pre> </div><h4 id=".element">.element<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h4> <div id="content-.element"class="depth-4"><p>For applicable elements (zoomer, attribution, legend, fullscreen), returns the DOM element this control exposes. </p> </div><h3 id="map.ui.fullscreen">map.ui.fullscreen</h3> <div id="content-map.ui.fullscreen"class="depth-3"><p>Add a link that can maximize and minimize the map on the browser page </p> <p><em>DOM Structure:</em> </p> <pre><code>&lt;a class=&quot;map-fullscreen&quot; href=&quot;#fullscreen&quot;&gt;fullscreen&lt;/a&gt;</code></pre> </div><h3 id="map.ui.hash">map.ui.hash</h3> <div id="content-map.ui.hash"class="depth-3"><p>Add the map&#39;s changing position to the URL, making map locations linkable </p> </div><h3 id="map.ui.zoombox">map.ui.zoombox</h3> <div id="content-map.ui.zoombox"class="depth-3"><p>Add the ability to zoom into the map by shift-clicking and dragging a box, to which the map zooms </p> </div><h3 id="map.ui.zoomer">map.ui.zoomer</h3> <div id="content-map.ui.zoomer"class="depth-3"><p>Add zoom in and zoom out buttons to map </p> <p><em>DOM Structure:</em> </p> <pre><code>&lt;!-- when a zoom control is inactive, .zoomdisable is added to it --&gt; &lt;a href=&quot;#&quot; class=&quot;zoomer zoomin&quot;&gt;+&lt;/a&gt; &lt;a href=&quot;#&quot; class=&quot;zoomer zoomout&quot;&gt;-&lt;/a&gt;</code></pre> </div><h3 id="map.ui.attribution">map.ui.attribution</h3> <div id="content-map.ui.attribution"class="depth-3"><p>Add an element with attribution information to the map </p> <p><em>DOM Structure:</em> </p> <pre><code>&lt;div class=&quot;map-attribution map-mm&quot;&gt;&lt;/div&gt;</code></pre> </div><h3 id="map.ui.legend">map.ui.legend</h3> <div id="content-map.ui.legend"class="depth-3"><p>Add an element with legend information to map </p> <p><em>DOM Structure:</em> </p> <pre><code>&lt;div class=&quot;map-legends&quot;&gt; &lt;div class=&quot;map-legend&quot;&gt; &lt;!-- Legend content --&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div><h3 id="map.ui.pointselector">map.ui.pointselector</h3> <div id="content-map.ui.pointselector"class="depth-3"><p>Allow simple location selection on the map: clicking without dragging will select a point, and notify listeners with the new list of points. </p> </div><h4 id="pointselector.addCallback">pointselector.addCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h4> <div id="<API key>.addCallback"class="depth-4"><p>Adds a callback that is called on changes to the pointselector contents. </p> <p><em>Arguments:</em> </p> <ul> <li><code>event</code> is a string of the event you want to bind the callback to</li> <li><code>callback</code> is a function that is called on the event specified by <code>event</code></li> </ul> <p>Event should be a String which is one of the following: </p> <ul> <li><code>change</code>: whenever points are added or removed</li> </ul> <p>Callback is a Function that is called with arguments depending on what <code>event</code> is bound: </p> <ul> <li><code>drawn</code>: the layer object</li> <li><code>locations</code>: a list of locations currently selected</li> </ul> <p><em>Returns</em> the pointselector </p> </div><h4 id="pointselector.removeCallback">pointselector.removeCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h4> <div id="<API key>.removeCallback"class="depth-4"><p>Remove a callback bound by <code>.addCallback(event, callback)</code>. </p> <p><em>Arguments:</em> </p> <ul> <li><p><code>event</code> is a string of the event you want to bind the callback to This must be the same string that was given in <code>addCallback</code></p> </li> <li><p><code>callback</code> is a function that is called on the event specified by <code>event</code>. This must be the same function as was given in <code>addCallback</code>. </p> </li> </ul> <p><em>Returns</em> the pointselector </p> </div><h3 id="map.ui.boxselector">map.ui.boxselector</h3> <div id="content-map.ui.boxselector"class="depth-3"><p>Allow extents to be selected on the map. </p> </div><h4 id="boxselector.addCallback">boxselector.addCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h4> <div id="content-boxselector.addCallback"class="depth-4"><p>Adds a callback that is called on changes to the boxselector contents. </p> <p><em>Arguments:</em> </p> <ul> <li><code>event</code> is a string of the event you want to bind the callback to</li> <li><code>callback</code> is a function that is called on the event specified by <code>event</code></li> </ul> <p>Event should be a String which is one of the following: </p> <ul> <li><code>change</code>: whenever an extent is selected</li> </ul> <p>Callback is a Function that is called with arguments depending on what <code>event</code> is bound: </p> <ul> <li><code>drawn</code>: the layer object</li> <li><code>extent</code>: the currently selected extent</li> </ul> <p><em>Returns</em> the boxselector </p> </div><h4 id="boxselector.removeCallback">boxselector.removeCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h4> <div id="content-boxselector.removeCallback"class="depth-4"><p>Remove a callback bound by <code>.addCallback(event, callback)</code>. </p> <p><em>Arguments:</em> </p> <ul> <li><p><code>event</code> is a string of the event you want to bind the callback to This must be the same string that was given in <code>addCallback</code></p> </li> <li><p><code>callback</code> is a function that is called on the event specified by <code>event</code>. This must be the same function as was given in <code>addCallback</code>.</p> </li> </ul> <p><em>Returns</em> the boxselector </p> </div><h3 id="map.ui.refresh">map.ui.refresh<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.ui.refresh"class="depth-3"><p>Refresh legend and attribution to reflect layer changes, merging and displaying legends and attribution for all enabled layers. </p> <p><em>Returns</em> the ui object. </p> </div><div class="separator" id="Interaction">Interaction</div><div id="content-Interaction"class="depth-0"></div><h3 id="map.interaction">map.interaction</h3> <div id="content-map.interaction"class="depth-3"><p>Interaction is what we call interactive parts of maps that are created with the <a href="http://mapbox.com/tilemill/docs/crashcourse/tooltips/">powerful tooltips &amp; regions system in TileMill</a>. Under the hood, it& specification. </p> </div><h3 id="map.interaction.auto">map.interaction.auto<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.interaction.auto"class="depth-3"><p>Enable default settings - animated tooltips - for interaction with the map. This internally calls <a href="#interaction.refresh"><code>interaction.refresh()</code></a> to set the interactivity for the top layer. </p> <p><em>Returns</em> the interaction control </p> <p><em>Example:</em> </p> <pre><code>var interaction = mapbox.interaction() .map(map) .auto();</code></pre> <p><em>DOM Structure (tooltips)</em>: </p> <pre><code>&lt;div class=&quot;map-tooltip map-tooltip-0&quot;&gt; &lt;!-- Tooltip content --&gt; &lt;/div&gt;</code></pre> </div><h3 id="map.interaction.refresh">map.interaction.refresh<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-map.interaction.refresh"class="depth-3"><p>Refresh interactivity control to reflect any layer changes. If <code>auto</code> has not been called, this function will not change anything. </p> <p><em>Returns</em> the interaction control </p> </div><div class="separator" id="Events">Events</div><div id="content-Events"class="depth-0"></div><h3 id="map.addCallback">map.addCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h3> <div id="content-map.addCallback"class="depth-3"><p>Add a callback for a specific event type. Event types are listed further down. </p> <p><em>Arguments:</em> </p> <ul> <li><code>event</code> is a string such as &quot;zoomed&quot; or &quot;drawn&quot;.</li> <li><code>callback</code> is function that gets called when the event is triggered.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id="map.removeCallback">map.removeCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h3> <div id="content-map.removeCallback"class="depth-3"><p>Remove a previously added callback. </p> <p><em>Arguments:</em> </p> <ul> <li><code>event</code> is the event type to remove the callback for.</li> <li><code>callback</code> is the callback to be removed.</li> </ul> <p><em>Returns</em> the map object. </p> </div><h3 id='Event_"zoomed"'>Event: zoomed</h3> <div id="content-Event_"zoomed""class="depth-3"><p>Fires when the map&#39;s zoom level changes. Callbacks receive two arguments: </p> <ul> <li><code>map</code> is the map object.</li> <li><code>zoomOffset</code> is the difference between zoom levels. Get the current zoom with <code>map.zoom()</code>.</li> </ul> <p><strong>Example:</strong> </p> <pre><code>map.addCallback(&quot;zoomed&quot;, function(map, zoomOffset) { console.log(&quot;Map zoomed by&quot;, zoomOffset); });</code></pre> </div><h3 id='Event_"panned"'>Event: panned</h3> <div id="content-Event_"panned""class="depth-3"><p>Fires when the map has been panned. Callbacks receive two arguments: </p> <ul> <li><code>map</code> is the map object.</li> <li><code>panOffset</code> is a two-element array in the form of <code>[dx, dy]</code>.</li> </ul> <p><strong>Example:</strong> </p> <pre><code>map.addCallback(&quot;panned&quot;, function(map, panOffset) { console.log(&quot;map panned by x:&quot;, panOffset[0], &quot;y:&quot;, panOffset[1]); });</code></pre> </div><h3 id='Event_"resized"'>Event: resized</h3> <div id="content-Event_"resized""class="depth-3"><p>Fires when the map has been resized. Callbacks receive two arguments: </p> <ul> <li><code>map</code> is the map object.</li> <li><code>dimensions</code> is a new <code>MM.Point</code> with the map&#39;s new dimensions.</li> </ul> <p><em>Example:</em> </p> <pre><code>map.addCallback(&quot;resized&quot;, function(map, dimensions) { console.log(&quot;map dimensions:&quot;, dimensions.x, &quot;y:&quot;, dimensions.y); });</code></pre> </div><h3 id='Event_"extentset"'>Event: extentset</h3> <div id="content-Event_"extentset""class="depth-3"><p>Fires when the map&#39;s extent is set. Callbacks receive two arguments: </p> <ul> <li><code>map</code> is the map object.</li> <li><code>extent</code> is an instance of <code>MM.Extent</code>.</li> </ul> <p><em>Example:</em> </p> <pre><code>map.addCallback(&quot;extentset&quot;, function(map, extent) { console.log(&quot;Map&#39;s extent set to:&quot;, extent); });</code></pre> </div><h3 id='Event_"drawn"'>Event: drawn</h3> <div id="content-Event_"drawn""class="depth-3"><p>Fires when the map is redrawn. Callbacks receive one argument: </p> <ul> <li><code>map</code> is the map object.</li> </ul> <p><em>Example:</em> </p> <pre><code>map.addCallback(&quot;drawn&quot;, function(map) { console.log(&quot;map drawn!&quot;); });</code></pre> </div><h1>Loading Utilities</h1> <div id="content-Event_"drawn""class="depth-1"><p>To load information about a certain map you& <code>mapbox.auto</code>, which pull the <a href="http://mapbox.com/wax/tilejson.html">TileJSON</a> file from a server and auto-instantiate many of its features. </p> </div><h2 id="mapbox.load">mapbox.load<span class="bracket">(</span><span class="args">url, callback</span><span class="bracket">)</span></h2> <div id="content-mapbox.load"class="depth-2"><p>Load layer definitions and other map information from MapBox. </p> <p><em>Arguments:</em> </p> <ul> <li><code>url</code> can be either be a full URL to a TileJSON file, like <code>http://a.tiles.mapbox.com/v3/tmcw.map-hehqnmda.jsonp</code>, or a bare id, like <code>tmcw.map-hehqnmda</code>, which will get expanded to the former. This can also accept an array of urls in the same format.</li> <li><p><code>callback</code> must be a function that receives either a single object with details or an array of objects if an array of map ids was given as the first argument.</p> <p> {</p> <pre><code>zoom: ZOOM_LEVEL, center: CENTER, // like you could create with mapbox.layer() layer: TILE_LAYER, // if present, like you would create with mapbox.markers() markers: MARKERS_LAYER</code></pre> <p> }</p> </li> </ul> <p><em>Example:</em> </p> <pre><code>&lt;div id=&#39;map&#39; style=&#39;width:500px;height:400px;&#39;&gt;&lt;/div&gt; &lt;script&gt; mapbox.load(&#39;tmcw.map-hehqnmda&#39;, function(o) { var map = mapbox.map(&#39;map&#39;); map.addLayer(o.layer); }); &lt;/script&gt;</code></pre> </div><h2 id="mapbox.auto">mapbox.auto<span class="bracket">(</span><span class="args">element, url [, callback]</span><span class="bracket">)</span></h2> <div id="content-mapbox.auto"class="depth-2"><p>Load and create a map with sensible defaults. </p> <p><em>Arguments:</em> </p> <ul> <li><code>element</code> must be the <code>id</code> of an element on the page, or an element itself. Typically maps are created within <code>&lt;div&gt;</code> elements</li> <li><code>url</code> must be a TileJSON URL, the id of a MapBox map, multiple IDs and URLs in an array.</li> <li><code>callback</code> if specified, receives the map as its first argument, and the same object as <code>mapbox.load</code> as the second argument. It is called after all resources have been loaded and the map is complete.</li> </ul> <p><em>Returns</em> <code>undefined</code>: this is an asynchronous function without a useful return value. </p> <p><strong>Example:</strong> </p> <pre><code>&lt;div id=&#39;map&#39; style=&#39;width:500px;height:400px;&#39;&gt;&lt;/div&gt; &lt;script&gt; mapbox.auto(& &lt;/script&gt;</code></pre> </div><h1>Layer</h1> <div id="content-mapbox.auto"class="depth-1"><p><code>mapbox.layer</code> is a fast way to add layers to your map without having to deal with complex configuration. </p> </div><h2 id="mapbox.layer">mapbox.layer<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h2> <div id="content-mapbox.layer"class="depth-2"><p>You can add a tiled layer to your map with <code>mapbox.layer()</code>, a simple interface to layers from MapBox and elsewhere. </p> <p><em>Returns</em> a layer object, which has the following methods: </p> </div><h3 id="layer.id">layer.id<span class="bracket">(</span><span class="args">id, callback</span><span class="bracket">)</span></h3> <div id="content-layer.id"class="depth-3"><p>Get or set the layer ID, which corresponds to a MapBox map. </p> <p><em>Arguments:</em> </p> <ul> <li><code>id</code> can be the id of a <a href="http://mapbox.com/">MapBox</a> map, or omitted to get the current <code>id</code> value. This also calls <a href="#layer.named">layer.named()</a> setting the name to be the same as the id - call <code>named()</code> to reset it. For instance, if you were trying to add the map at <code>https://tiles.mapbox.com/tmcw/map/map-hehqnmda</code>, you could create this layer like so:</li> <li><code>callback</code>, if provided, is called after the layer has been asynchronously loaded from MapBox. It is called with on argument, the layer object.</li> </ul> <p><em>Returns</em> the layer object if arguments are given, the layer&#39;s <code>id</code> otherwise. </p> <p><em>Example:</em> </p> <pre><code>var layer = mapbox.layer().id(&#39;map-hehqnmda&#39;);</code></pre> </div><h3 id="layer.named">layer.named<span class="bracket">(</span><span class="args">[name]</span><span class="bracket">)</span></h3> <div id="content-layer.named"class="depth-3"><p>Get or set the name of the layer, as referred to by the map. </p> <p><em>Arguments:</em> </p> <ul> <li><code>name</code> can be a new name to call this layer</li> </ul> <p><em>Returns</em> the layer object if arguments are given, the layer&#39;s <code>name</code> otherwise. </p> </div><h3 id="layer.url">layer.url<span class="bracket">(</span><span class="args">[url, callback]</span><span class="bracket">)</span></h3> <div id="content-layer.url"class="depth-3"><p>Pull a layer from a server besides MapBox that supports <a href="https: </p> <p><em>Arguments:</em> </p> <ul> <li><code>url</code> can be a string value that is a fully-formed URL, or omitted to get the URL from which this layer was sourced.</li> <li><code>callback</code>, if provided, is called with one argument, the layer object, after the TileJSON information has been asynchronously loaded.</li> </ul> <p><em>Returns</em> the layer object if arguments are given, the pulled URL otherwise. </p> <p><strong>Example:</strong> </p> <pre><code>var layer = mapbox.layer().url(& </div><h3 id="layer.tilejson">layer.tilejson<span class="bracket">(</span><span class="args">[tilejson]</span><span class="bracket">)</span></h3> <div id="content-layer.tilejson"class="depth-3"><p>Set layer options directly from a <a href="https://github.com/mapbox/tilejson-spec">TileJSON</a> object. </p> <p><em>Arguments:</em> </p> <ul> <li><code>tilejson</code> must be a TileJSON object as a Javascript object.</li> </ul> <p><em>Returns</em> the layer object if arguments are given, the layer&#39;s TileJSON settings otherwise. </p> </div><h3 id="layer.composite">layer.composite<span class="bracket">(</span><span class="args">enabled</span><span class="bracket">)</span></h3> <div id="content-layer.composite"class="depth-3"><p>Enable or disable compositing layers together on MapBox. Compositing combines multiple tile images into one layer of blended images, increasing map performance and reducing the number of requests the browser needs to make. </p> <ul> <li><code>enabled</code> must be either true or false.</li> </ul> <p><em>Returns</em> the layer object. </p> </div><h3 id="layer.parent">layer.parent</h3> <div id="content-layer.parent"class="depth-3"><p>The layer&#39;s parent DOM element. </p> </div><div></div><h1>Markers layer</h1> <div id="content-layer.parent"class="depth-1"><p><code>mapbox.markers</code> is a markers library that makes it easier to add HTML elements on top of maps in geographical locations and interact with them. Internally, markers are stored as <a href="http: interfaces through CSV and simple Javascript are provided. </p> </div><h2 id="mapbox.markers.layer">mapbox.markers.layer<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h2> <div id="content-mapbox.markers.layer"class="depth-2"><p><code>mapbox.markers.layer()</code> creates a new layer into which markers can be placed and which can be added to a map with <a href="#map.addLayer"><code>map.addLayer()</code></a> </p> </div><h3 id="markers.named">markers.named<span class="bracket">(</span><span class="args">[name]</span><span class="bracket">)</span></h3> <div id="content-markers.named"class="depth-3"><p>Set the name of this markers layer. The default name for a <code>markers</code> layer is <code>&#39;markers&#39;</code> </p> <p><em>Arguments:</em> </p> <ul> <li><code>name</code> if given, must be a string.</li> </ul> <p><em>Returns</em> the layer object if a new name is provided, otherwise the layer&#39;s existing name if it is omitted. </p> </div><h3 id="markers.factory">markers.factory<span class="bracket">(</span><span class="args">[factoryfunction]</span><span class="bracket">)</span></h3> <div id="content-markers.factory"class="depth-3"><p>Define a new factory function, and if the layer already has points added to it, re-render them with the new factory. Factory functions are what turn GeoJSON feature objects into HTML elements on the map. Due to the way that markers allows multiple layers of interactivity, factories that want their elements to be interactive <strong>must</strong> either set <code>.style.pointerEvents = &#39;all&#39;</code> on them via Javascript, or have an equivalent CSS rule with <code>pointer-events: all</code> that affects the elements. </p> <p><em>Arguments:</em> </p> <ul> <li><code>factoryfunction</code> should be a function that takes a <a href="http://geojson.org/geojson-spec.html#feature-objects">GeoJSON feature object</a> and returns an HTML element, or omitted to get the current value.</li> </ul> <p><em>Returns</em> the layer object if a new factory function is provided, otherwise the layer&#39;s existing factory function </p> </div><h3 id="markers.features">markers.features<span class="bracket">(</span><span class="args">[features]</span><span class="bracket">)</span></h3> <div id="content-markers.features"class="depth-3"><p>Set the contents of a markers layer: run the provided features through the filter function and then through the factory function to create elements for the map. If the layer already has features, they are replaced with the new features. An empty array will clear the layer of all features. </p> <p><em>Arguments:</em> </p> <ul> <li><code>features</code> can be a array of <a href="http://geojson.org/geojson-spec.html#feature-objects">GeoJSON feature objects</a>, or omitted to get the current value.</li> </ul> <p><em>Returns</em> the layer object if a new array of features is provided, otherwise the layer&#39;s features </p> </div><h3 id="markers.add_feature">markers.add_feature<span class="bracket">(</span><span class="args">[feature]</span><span class="bracket">)</span></h3> <div id="content-markers.add_feature"class="depth-3"><p>Add a single GeoJSON feature object to the layer. </p> <p><em>Arguments:</em> </p> <ul> <li><code>features</code> must be a single GeoJSON feature object</li> </ul> <p><em>Returns</em> the layer object </p> <p><em>Example:</em> </p> <pre><code>var markerLayer = mapbox.markers.layer(); var newfeature = { geometry: { coordinates: [-77, 37.9] }, properties: { } }; // add this single new feature markerLayer.add_feature(newfeature); // This call is equivalent to markerLayer.features(markerLayer.features().concat([x]));</code></pre> </div><h3 id="markers.sort">markers.sort<span class="bracket">(</span><span class="args">[sortfunction]</span><span class="bracket">)</span></h3> <div id="content-markers.sort"class="depth-3"><p>Set the sorting function for markers in the DOM. Markers are typically sorted in the DOM in order for them to correctly visually overlap. By default, this is a function that sorts markers by latitude value - <code>geometry.coordinates[1]</code>. </p> <p><em>Arguments:</em> </p> <ul> <li><code>sortfunction</code> can be a function that takes two GeoJSON feature objects and returns a number indicating sorting direction - fulfilling the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort">Array.sort</a> interface, or omitted to get the current value.</li> </ul> <p><em>Returns</em> the layer object if a new function is specified, otherwise the current function used to sort. </p> <p><em>Example:</em> </p> <pre><code>// The default sorting function is: layer.sort(function(a, b) { return b.geometry.coordinates[1] - a.geometry.coordinates[1]; });</code></pre> </div><h3 id="markers.filter">markers.filter<span class="bracket">(</span><span class="args">[filterfunction]</span><span class="bracket">)</span></h3> <div id="content-markers.filter"class="depth-3"><p>Set the layer&#39;s filter function and refilter features. Markers can also be filtered before appearing on the map. This is a purely presentational filter - the underlying features, which are accessed by <a href="#markers.features"><code>markers.features()</code></a>, are unaffected. Setting a new filter can therefore cause points to be displayed which were previously hidden. </p> <p><em>Arguments:</em> </p> <ul> <li><code>filterfunction</code> can be a function that takes a GeoJSON feature object and returns <code>true</code> to allow it to be displayed or <code>false</code> to hide it, or omitted to get the current value</li> </ul> <p><em>Returns</em> the layer object if a new function is specified, otherwise the current function used to filter. </p> <p><em>Example:</em> </p> <pre><code>// The default filter function is: layer.filter(function() { return true; });</code></pre> </div><h3 id="markers.key">markers.key<span class="bracket">(</span><span class="args">[idfunction]</span><span class="bracket">)</span></h3> <div id="content-markers.key"class="depth-3"><p>Set the key getter for this layer. The key getter is a funcion that takes a GeoJSON feature and returns a <em>unique id</em> for that feature. If this is provided, the layer can optimize repeated calls to <a href="#markers.features"><code>markers.features()</code></a> for animation purposes, since updated markers will not be recreated, only modified. </p> <p><em>Arguments:</em> </p> <ul> <li><code>keyfunction</code> must be a function that takes a GeoJSON object and returns a unique ID for it that does not change for the same features on repeated calls</li> </ul> <p><em>Returns</em> the layer object if a new function is specified, otherwise the current function used to get keys. </p> <p><em>Example:</em> </p> <pre><code>// The default id function is: var _seq = 0; layer.key(function() { return ++_seq; }); // Thus this function always returns a new id for any feature. If you had // features that do have an id attribute, a function would look like layer.key(function(f) { return f.properties.id; });</code></pre> </div><h3 id="markers.url">markers.url<span class="bracket">(</span><span class="args">url [, callback]</span><span class="bracket">)</span></h3> <div id="content-markers.url"class="depth-3"><p>Load features from a remote GeoJSON file into the layer. </p> <p><em>Arguments:</em> </p> <ul> <li><code>url</code> should be a URL to a GeoJSON file on a server. If the server is remote, the GeoJSON file must be served with a <code>.geojsonp</code> extension and respond to the JSONP callback <code>grid</code>.</li> <li><code>callback</code>, if provided, is optional and should be a callback that is called after the request finishes, with the error (if encountered), features array (if any) and the layer instance as arguments. If an error is encountered, <code>markers.url()</code> will not call <code>markers.features()</code>, since this would likely clear the features array.</li> </ul> <p><strong>Returns</strong> the markers layer or the current URL given if no <code>url</code> argument is provided. </p> </div><h3 id="markers.id">markers.id<span class="bracket">(</span><span class="args">layerid [, callback]</span><span class="bracket">)</span></h3> <div id="content-markers.id"class="depth-3"><p>Load markers from a <a href="http://mapbox.com/">MapBox</a> layer. </p> <p><em>Arguments:</em> </p> <ul> <li><code>layerid</code> must be the ID of a layer, like <code>user.map-example</code></li> <li><code>callback</code> can be a callback that fires after the request finishes, and behaves the same as the callback in <code>markers.url</code></li> </ul> <p><strong>Returns</strong> the markers layer. </p> </div><h3 id="markers.csv">markers.csv<span class="bracket">(</span><span class="args">csvstring</span><span class="bracket">)</span></h3> <div id="content-markers.csv"class="depth-3"><p>Convert a string of <a href="http://en.wikipedia.org/wiki/<API key>">CSV</a> data into GeoJSON and set layer to show it as features. If it can find features in the CSV string, the <a href="#markers.features"><code>markers.features()</code></a> of the layer are set to them - otherwise it will throw an error about not finding headers. </p> <p><em>Arguments:</em> </p> <ul> <li><code>csvstring</code> must be a string of CSV data. This method returns the markers layer. The CSV string must include columns beginning with <code>lat</code> and <code>lon</code> in any case (Latitude, latitude, lat are acceptable).</li> </ul> <p><em>Returns</em> the markers layer </p> </div><h3 id="markers.extent">markers.extent<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-markers.extent"class="depth-3"><p>Get the extent of all of the features provided. </p> <p><em>Returns</em> an array of two <code>{ lat: 23, lon: 32 }</code> objects compatible with the <a href="#map.extent"><code>map.extent()</code></a> call. If there are no features, the extent is set to <code>Infinity</code> in all directions, and if there is one feature, the extent is set to its point exactly. </p> </div><h3 id="markers.addCallback">markers.addCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h3> <div id="content-markers.addCallback"class="depth-3"><p>Add a callback that is called on certain events by this layer. These are primarily used by <a href="#mapbox.markers.interaction"><code>mapbox.markers.interaction</code></a>, but otherwise useful to support more advanced bindings on markers layers that are bound at times when the markers layer object may not be added to a map - like binding to the map&#39;s <code>panned</code> event to clear tooltips. </p> <p><em>Arguments:</em> </p> <ul> <li><code>event</code> is a string of the event you want to bind the callback to</li> <li><code>callback</code> is a funcion that is called on the event specified by <code>event</code></li> </ul> <p>Event should be a String which is one of the following: </p> <ul> <li><code>drawn</code>: whenever markers are drawn - which includes any map movement</li> <li><code>markeradded</code>: when markers are added anew</li> </ul> <p>Callback is a Function that is called with arguments depending on what <code>event</code> is bound: </p> <ul> <li><code>drawn</code>: the layer object</li> <li><code>markeradded</code>: the new marker</li> </ul> <p><em>Returns</em> the markers layer </p> </div><h3 id="markers.removeCallback">markers.removeCallback<span class="bracket">(</span><span class="args">event, callback</span><span class="bracket">)</span></h3> <div id="content-markers.removeCallback"class="depth-3"><p>Remove a callback bound by <code>markers.addCallback(event, callback)</code>. </p> <p><em>Arguments:</em> </p> <ul> <li><p><code>event</code> is a string of the event you want to bind the callback to This must be the same string that was given in <code>addCallback</code></p> </li> <li><p><code>callback</code> is a funcion that is called on the event specified by <code>event</code>. This must be the same function as was given in <code>markers.addCallback</code>.</p> </li> </ul> <p><em>Returns</em> the markers layer </p> </div><h3 id="markers.markers">markers.markers<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-markers.markers"class="depth-3"><p>Get the layer&#39;s internal markers array. Unlike <code>markers.features()</code>, this is not a getter-setter - you can only <em>get</em> the internal markers. Markers are internally objects of <code>{ element: DOMNode, location: Location, data: feature }</code> structure, optionally with <code>showTooltip()</code> functions added by <code>mapbox.markers.interaction()</code>. </p> <p>This is direct access to the internal circuitry of markers, and should only be used in very specific circumstances, where the functionality provided by <code>markers.factory()</code>, <code>markers.filter()</code>, etc., is insufficient. </p> <p><em>Returns</em> the internal array of marker objects. </p> </div><h2>Styling markers</h2> <div id="content-markers.markers"class="depth-2"><p>By default, markers use pretty styles and a default factory function. <code>markers.factory()</code> allows for custom DOM elements as markers, which should be assigned specific CSS in order to ensure correct placement. </p> <p>All styles should position elements with <code>position:absolute;</code> and offset them so that the center of the element is in the positioning center - thus the geographic center. So, an element this is 40x40 should be offset by 20 pixels up and to the left. </p> <p>And in order to support mouse events - like tooltips or hover hints, you&#39;ll need to add a rule setting the <code>pointer-events</code> property of the markers: </p> <p><em>Example:</em> </p> <pre><code>.my-custom-marker { /* support pointer events */ pointer-events:all; position:absolute; width:40px; height:40px; /* offset to keep a correct center */ margin-left:-20px; margin-top:-20px; }</code></pre> </div><h2 id="mapbox.markers.interaction">mapbox.markers.interaction<span class="bracket">(</span><span class="args">markerslayer</span><span class="bracket">)</span></h2> <div id="content-mapbox.markers.interaction"class="depth-2"><p>Bind interaction, hovering and/or clicking markers and seeing their details, and customizable through its methods. This supports both mouse &amp; touch input. </p> <p>Adds tooltips to your markers, for when a user hovers over or taps the features. </p> <p>This function will create at most one interaction instance per markers layer. Thus you can use it to access interaction instances previously created and to change their settings. </p> <p><em>Arguments:</em> </p> <ul> <li><code>markerslayer</code> must be a markers layer.</li> </ul> <p><em>Returns</em> an <code>interaction</code> instance which provides methods for customizing how the layer behaves. </p> </div><h3 id="interaction.remove">interaction.remove<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-interaction.remove"class="depth-3"><p>Disable interactivity. </p> <p><em>Returns</em> the interaction instance. </p> </div><h3 id="interaction.add">interaction.add<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-interaction.add"class="depth-3"><p>Enable interactivity. By default, interactivity is enabled. </p> <p><em>Returns</em> the interaction instance. </p> </div><h3 id="interaction.hideOnMove">interaction.hideOnMove<span class="bracket">(</span><span class="args">[value]</span><span class="bracket">)</span></h3> <div id="content-interaction.hideOnMove"class="depth-3"><p>Determine whether tooltips are hidden when the map is moved. The single argument should be <code>true</code> or <code>false</code> or not given in order to retrieve the current value. </p> <p><em>Arguments:</em> </p> <ul> <li><code>value</code> must be true or false to activate or deactivate the mode</li> </ul> <p><em>Returns</em> the interaction instance. </p> </div><h3 id="interaction.showOnHover">interaction.showOnHover<span class="bracket">(</span><span class="args">[value]</span><span class="bracket">)</span></h3> <div id="content-interaction.showOnHover"class="depth-3"><p>Determine whether tooltips are shown when the user hovers over them. The single argument should be <code>true</code> or <code>false</code> or not given in order to retrieve the current value. </p> <p><em>Arguments:</em> </p> <ul> <li><code>value</code> must be true or false to activate or deactivate the mode</li> </ul> <p><em>Returns</em> the interaction instance. </p> </div><h3 id="interaction.exclusive">interaction.exclusive<span class="bracket">(</span><span class="args">[value]</span><span class="bracket">)</span></h3> <div id="content-interaction.exclusive"class="depth-3"><p>Determine whether a single popup should be open at a time, or unlimited. The single argument should be <code>true</code> or <code>false</code> or not given in order to retrieve the current value. </p> <p><em>Arguments:</em> </p> <ul> <li><code>value</code> must be true or false to activate or deactivate the mode</li> </ul> <p><em>Returns</em> the interaction instance. </p> </div><h3 id="interaction.formatter">interaction.formatter<span class="bracket">(</span><span class="args">[formatterfunction]</span><span class="bracket">)</span></h3> <div id="content-interaction.formatter"class="depth-3"><p>Set or get the formatter function, that decides how data goes from being in a feature&#39;s <code>properties</code> to the HTML inside of a tooltip. This is a getter setter that takes a Function as its argument. </p> <p><em>Arguments:</em> </p> <ul> <li><code>formatterfunction</code>: a new function that takes GeoJSON features as input and returns HTML suitable for tooltips, or omitted to get the current value.</li> </ul> <p><em>Returns</em> the interaction instance if a new formatter function is provided, otherwise the current formatter function </p> <p><em>Example:</em> </p> <pre><code>// The default formatter function interaction.formatter(function(feature) { var o = &#39;&#39;, props = feature.properties; if (props.title) { o += &#39;&lt;h1 class=&quot;marker-title&quot;&gt;&#39; + props.title + &#39;&lt;/h1&gt;&#39;; } if (props.description) { o += &#39;&lt;div class=&quot;marker-description&quot;&gt;&#39; + props.description + &#39;&lt;/div&gt;&#39;; } if (typeof html_sanitize !== undefined) { o = html_sanitize(o, function(url) { if (/^(https?:\/\/|data:image)/.test(url)) return url; }, function(x) { return x; }); } return o; });</code></pre> </div><h2>Styling tooltips</h2> <div id="content-interaction.formatter"class="depth-2"><p>Tooltips, provided in <code>mapbox.markers.interaction</code>, are added to the map as markers themselves, so that they are correctly geographically positioned. You can customize the details of tooltips by changing one of the classes in its DOM structure: </p> <pre><code>&lt;div class=&#39;marker-tooltip&#39;&gt; &lt;div&gt; &lt;div class=&#39;marker-popup&#39;&gt; &lt;div class=&#39;marker-title&#39;&gt;Your Marker&#39;s Title&lt;/div&gt; &lt;div class=&#39;marker-description&#39;&gt;Your Marker&#39;s Description&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div><div></div><h1>Easing</h1> <div id="content-interaction.formatter"class="depth-1"><p>Easing is moving from one point or zoom to another in a fluid motion, instead of just &#39;popping&#39; from place to place. It&#39;s useful for map-based storytelling, since users get a better idea of geographical distance. </p> </div><h2 id="mapbox.ease">mapbox.ease<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h2> <div id="content-mapbox.ease"class="depth-2"><p><strong>Returns</strong> an easey object, which has the following methods: </p> </div><h3 id="ease.map">ease.map<span class="bracket">(</span><span class="args">map</span><span class="bracket">)</span></h3> <div id="content-ease.map"class="depth-3"><p>Specify the map to be used. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>map</code> is an instance of <code>mapbox.map()</code> or <code>MM.Map</code></li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.from">ease.from<span class="bracket">(</span><span class="args">coord</span><span class="bracket">)</span></h3> <div id="content-ease.from"class="depth-3"><p>Set the starting coordinate for the easing. You don&#39;t usually need to call this, because easings default to the current coordinate. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>coord</code> is an instance of <code>MM.Coordinate</code> representing the starting coordinate for the easing.</li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.to">ease.to<span class="bracket">(</span><span class="args">coord</span><span class="bracket">)</span></h3> <div id="content-ease.to"class="depth-3"><p>Set the destination coordinate for the easing. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>coord</code> is an instance of <code>MM.Coordinate</code> representing the destination coordinate for the easing. </li> </ul> <p>Since easey deals exclusively in Coordinates, <a href="https://github.com/stamen/modestmaps-js/wiki/Point,-Location,-and-Coordinate">the reference for converting between points, locations, and coordinates in Modest Maps is essential reading</a>. </p> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.zoom">ease.zoom<span class="bracket">(</span><span class="args">level</span><span class="bracket">)</span></h3> <div id="content-ease.zoom"class="depth-3"><p>Set the zoom level of the <code>to</code> coordinate that easey is easing to. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>level</code> is a number representing the zoom level</li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.optimal">ease.optimal<span class="bracket">(</span><span class="args">[V] [,rho] [,callback]</span><span class="bracket">)</span></h3> <div id="content-ease.optimal"class="depth-3"><p>Eases to <code>from</code> in the smoothest way possible, automatically choosing run time based on distance. The easing zooms out and in to optimize for the shortest easing time and the slowest percieved speed. The optional arguments are as defined in <em><a href="http: </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>V</code> inversely affects the speed (default is 0.9) </li> <li><code>rho</code> affects the sensitivity of zooming in and out (default 1.42)</li> <li><code>callback</code> is a function that gets called after the animation completes.</li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.location">ease.location<span class="bracket">(</span><span class="args">location</span><span class="bracket">)</span></h3> <div id="content-ease.location"class="depth-3"><p>Sets the <code>to</code> coordinate to the provided location. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>location</code> is an object with <code>lat</code> and <code>lon</code> properties, or an instance of <code>MM.Location</code>.</li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.t">ease.t<span class="bracket">(</span><span class="args">value</span><span class="bracket">)</span></h3> <div id="content-ease.t"class="depth-3"><p>Set the map to a specific point in the easing. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>value</code> is a float between 0 and 1, where 0 is <code>from</code> and 1 is <code>to</code>.</li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.future">ease.future<span class="bracket">(</span><span class="args">parts</span><span class="bracket">)</span></h3> <div id="content-ease.future"class="depth-3"><p>Get the future of an easing transition, given a number of parts for it to be divided over. This is a convenience function for calling <code>easey.t()</code> a bunch of times. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>parts</code> is an positive integer representing the number of parts to divide the easing into.</li> </ul> <p><strong>Returns</strong> an array of <code>MM.Coordinate</code> objects representing each in-between location. </p> </div><h3 id="ease.easing">ease.easing<span class="bracket">(</span><span class="args">name</span><span class="bracket">)</span></h3> <div id="content-ease.easing"class="depth-3"><p>Set the easing curve - this defines how quickly the transition gets to its end and whether it speeds up or slows down near the beginning and end. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>name</code> is the string name of the easing to use. Current options are:<ul> <li>&#39;easeIn&#39;</li> <li>&#39;easeOut&#39;</li> <li>&#39;easeInOut&#39;</li> <li>&#39;linear&#39;</li> </ul> </li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.path">ease.path<span class="bracket">(</span><span class="args">pathname</span><span class="bracket">)</span></h3> <div id="content-ease.path"class="depth-3"><p>Set the type of path - the type of interpolation between points. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>pathname</code> is a string name of the path to use. Current options are:<ul> <li><code>screen</code>: a &#39;straight line&#39; path from place to place - in the Mercator projection, this is a rhumb line</li> <li><code>about</code>: the default path for a double-click zoom: this keeps a single coordinate in the same screen pixel over the zoom transition</li> </ul> </li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.run">ease.run<span class="bracket">(</span><span class="args">[time [, callback]</span><span class="bracket">)</span></h3> <div id="content-ease.run"class="depth-3"><p>Start an <em>animated ease</em>. Both parameters are optional. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>time</code> is an integer representing the duration of the easing in milliseconds (default is 1000).</li> <li><code>callback</code> is a Javascript function that is called when the map has reached its destination.</li> </ul> <p><strong>Returns</strong> the easey object. </p> </div><h3 id="ease.running">ease.running<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3> <div id="content-ease.running"class="depth-3"><p><strong>Returns</strong> <code>true</code> or <code>false</code> depending on whether easey is currently animating the map. </p> </div><h3 id="ease.stop">ease.stop<span class="bracket">(</span><span class="args">[callback]</span><span class="bracket">)</span></h3> <div id="content-ease.stop"class="depth-3"><p>Abort the currently running animation. </p> <p><strong>Arguments:</strong> </p> <ul> <li><code>callback</code> is a function to be called after the previous animation has been successfully stopped.</li> </ul> <p><strong>Returns</strong> the easey object. </p> </div>
#pragma once #include <algorithm> #include <memory> #include <kodi/Filesystem.h> namespace utilities { /** * Compares two containers for equality based on the equality of their * dereferenced contents (i.e. the containers should contain some kind of * pointers). */ template<class Container> bool deref_equals(const Container& left, const Container& right) { return !(left.size() != right.size() || !std::equal(left.begin(), left.end(), right.begin(), [](const typename Container::value_type& leftItem, const typename Container::value_type& rightItem) { return *leftItem == *rightItem; })); } /** * Reads the contents of the file pointed to by the handle and returns it. * The file handle must be opened before calling this method. * @param fileHandle the file handle * @return the contents (unique pointer) */ inline std::unique_ptr<std::string> ReadFileContents(kodi::vfs::CFile& fileHandle) { std::unique_ptr<std::string> content(new std::string()); char buffer[1024]; int bytesRead = 0; // Read until EOF or explicit error while ((bytesRead = fileHandle.Read(buffer, sizeof(buffer) - 1)) > 0) content->append(buffer, bytesRead); return content; } } // namespace utilities
#ifndef <API key> #define <API key> #include "core/inspector/<API key>.h" #include "public/platform/WebSize.h" namespace WebCore { class <API key>; class <API key> FINAL : public <API key> { public: static PassRefPtr<<API key>> create(const blink::WebSize&, double, const String&, const <API key>&, const double); static PassRefPtr<<API key>> create(PassRefPtr<JSONObject> obj); virtual ~<API key>(); virtual void accept(<API key>& visitor) OVERRIDE; virtual size_t size(); virtual PassRefPtr<JSONObject> serialize() OVERRIDE; virtual void deserialize(PassRefPtr<JSONObject> json) OVERRIDE; float pageScaleDelta(); private: <API key>(const blink::WebSize&, double, const String&, const <API key>&, const double); <API key>(PassRefPtr<JSONObject> obj); float m_pageScaleDelta; }; } /* namespace WebCore */ #endif /* <API key> */
package com.autentia.intra.bean.account; import com.autentia.intra.bean.BaseBean; import com.autentia.intra.bean.NavigationResults; import com.autentia.intra.businessobject.AccountEntryGroup; import com.autentia.intra.businessobject.AccountEntryType; import com.autentia.intra.dao.SortCriteria; import com.autentia.intra.dao.search.<API key>; import com.autentia.intra.manager.account.<API key>; import com.autentia.intra.manager.account.<API key>; import com.autentia.intra.manager.security.Permission; import com.autentia.intra.upload.Uploader; import com.autentia.intra.upload.UploaderFactory; import com.autentia.intra.util.FacesUtils; import com.autentia.intra.util.SpringUtils; import org.acegisecurity.acls.domain.BasePermission; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.faces.component.UIComponent; import javax.faces.component.html.HtmlDataTable; import javax.faces.model.SelectItem; import java.util.ArrayList; import java.util.Date; import java.util.List; public class <API key> extends BaseBean { /* accountEntryType - generated by stajanov (do not edit/delete) */ /** * Logger */ private static final Log log = LogFactory.getLog(<API key>.class); /** * Active search object */ private <API key> search = new <API key>(); /** * Manager */ private static <API key> manager = <API key>.getDefault(); /** * Upload service */ private static final Uploader uploader = UploaderFactory.getInstance("accountEntryType"); /** * Active AccountEntryType object */ private AccountEntryType accountEntryType; /** * Default sort column */ private String sortColumn = "name"; /** * Default sort order */ private boolean sortAscending = false; /** * Quick search letter for ABC pager control */ private Character letter; /** * List accountEntryTypes. Order depends on Faces parameter sort. * * @return the list of all accountEntryTypes sorted by requested criterion */ public List<AccountEntryType> getAll() { return manager.getAllEntities(search, new SortCriteria(sortColumn, sortAscending)); } // Getters to list possible values of related entities /** * Get the list of all groups * * @return the list of all groups */ public List<SelectItem> getGroups() { List<AccountEntryGroup> refs = <API key>.getDefault().getAllEntities(null, new SortCriteria("name")); ArrayList<SelectItem> ret = new ArrayList<SelectItem>(); for (AccountEntryGroup ref : refs) { ret.add(new SelectItem(ref, ref.getName())); } return ret; } // Getters to list possible values of enum fields // Methods to create/remove instances of one-to-many entities (slave entities) /** * Whether or not create button is available for user * * @return true if user can create objects of type AccountEntryType */ public boolean isCreateAvailable() { return SpringUtils.<API key>(Permission.Entity_Create(AccountEntryType.class)); } /** * Whether or not edit button is available for user * * @return true if user can edit current object */ public boolean isEditAvailable() { return SpringUtils.<API key>(accountEntryType, BasePermission.WRITE); } /** * Whether or not delete button is available for user * * @return true if user can delete current object */ public boolean isDeleteAvailable() { return (accountEntryType.getId() != null) && SpringUtils.<API key>(accountEntryType, BasePermission.DELETE); } /** * Go to create page * * @return forward to CREATE page */ public String create() { accountEntryType = new AccountEntryType(); return NavigationResults.CREATE; } /** * Go to detail page * * @return forward to DETAIL page */ public String detail() { Integer id = Integer.parseInt(FacesUtils.getRequestParameter("id")); accountEntryType = manager.getEntityById(id); return SpringUtils.<API key>(accountEntryType, BasePermission.WRITE) ? NavigationResults.EDIT : NavigationResults.DETAIL; } /** * Save bean and stay on it * * @return forward to list page */ public String save() { doBeforeSave(); if (accountEntryType.getId() == null) { manager.insertEntity(accountEntryType); } else { manager.updateEntity(accountEntryType); } // Calls an after save action String result = doAfterSave(NavigationResults.LIST); // Unselect object accountEntryType = null; return result; } /** * Delete bean and go back to beans list * * @return forward to LIST page */ public String delete() { manager.deleteEntity(accountEntryType); accountEntryType = null; return NavigationResults.LIST; } /** * Go back to beans list * * @return forward to LIST page */ public String list() { return NavigationResults.LIST; } /** * Reset search criteria * * @return forward to LIST page */ public String reset() { search.reset(); return list(); } /** * Go to search page * * @return forward to SEARCH page */ public String search() { return NavigationResults.SEARCH; } /** * Check if we have an active object. * * @return true is an object is selected */ public boolean <API key>() { return accountEntryType != null; } // Getters and setters to manipulate sorting public boolean isSortAscending() { return sortAscending; } public void setSortAscending(boolean sortAscending) { this.sortAscending = sortAscending; } public String getSortColumn() { return sortColumn; } public void setSortColumn(String sortColumn) { this.sortColumn = sortColumn; } // Getters and setters to handle search public <API key> getSearch() { return search; } public String getSearchName() { return search.getName(); } public void setSearchName(String val) { if (search.isNameSet()) { search.setName(val); } } public boolean isSearchNameValid() { return search.isNameSet(); } public void setSearchNameValid(boolean val) { if (val) { search.setName(search.getName()); } else { search.unsetName(); } } public String <API key>() { return search.getObservations(); } public void <API key>(String val) { if (search.isObservationsSet()) { search.setObservations(val); } } public boolean <API key>() { return search.isObservationsSet(); } public void <API key>(boolean val) { if (val) { search.setObservations(search.getObservations()); } else { search.unsetObservations(); } } public Integer <API key>() { return search.getCustomizableId(); } public void <API key>(Integer val) { if (search.isCustomizableIdSet()) { search.setCustomizableId(val); } } public boolean <API key>() { return search.isCustomizableIdSet(); } public void <API key>(boolean val) { if (val) { search.setCustomizableId(search.getCustomizableId()); } else { search.unsetCustomizableId(); } } public Integer getSearchOwnerId() { return search.getOwnerId(); } public void setSearchOwnerId(Integer val) { if (search.isOwnerIdSet()) { search.setOwnerId(val); } } public boolean <API key>() { return search.isOwnerIdSet(); } public void <API key>(boolean val) { if (val) { search.setOwnerId(search.getOwnerId()); } else { search.unsetOwnerId(); } } public Integer <API key>() { return search.getDepartmentId(); } public void <API key>(Integer val) { if (search.isDepartmentIdSet()) { search.setDepartmentId(val); } } public boolean <API key>() { return search.isDepartmentIdSet(); } public void <API key>(boolean val) { if (val) { search.setDepartmentId(search.getDepartmentId()); } else { search.unsetDepartmentId(); } } public Date <API key>() { return search.getStartInsertDate(); } public void <API key>(Date val) { if (val != null) { search.setStartInsertDate(val); } else { search.<API key>(); } } public boolean <API key>() { return search.<API key>(); } public void <API key>(boolean val) { if (val) { search.setStartInsertDate(search.getStartInsertDate()); } else { search.<API key>(); } } public Date <API key>() { return search.getEndInsertDate(); } public void <API key>(Date val) { if (val != null) { search.setEndInsertDate(val); } else { search.unsetEndInsertDate(); } } public boolean <API key>() { return search.isEndInsertDateSet(); } public void <API key>(boolean val) { if (val) { search.setEndInsertDate(search.getEndInsertDate()); } else { search.unsetEndInsertDate(); } } public Date <API key>() { return search.getStartUpdateDate(); } public void <API key>(Date val) { if (val != null) { search.setStartUpdateDate(val); } else { search.<API key>(); } } public boolean <API key>() { return search.<API key>(); } public void <API key>(boolean val) { if (val) { search.setStartUpdateDate(search.getStartUpdateDate()); } else { search.<API key>(); } } public Date <API key>() { return search.getEndUpdateDate(); } public void <API key>(Date val) { if (val != null) { search.setEndUpdateDate(val); } else { search.unsetEndUpdateDate(); } } public boolean <API key>() { return search.isEndUpdateDateSet(); } public void <API key>(boolean val) { if (val) { search.setEndUpdateDate(search.getEndUpdateDate()); } else { search.unsetEndUpdateDate(); } } public AccountEntryGroup getSearchGroup() { return search.getGroup(); } public void setSearchGroup(AccountEntryGroup val) { if (search.isGroupSet()) { search.setGroup(val); } } public boolean isSearchGroupValid() { return search.isGroupSet(); } public void setSearchGroupValid(boolean val) { if (val) { search.setGroup(search.getGroup()); } else { search.unsetGroup(); } } public AccountEntryType getSearchParent() { return search.getParent(); } public void setSearchParent(AccountEntryType val) { if (search.isParentSet()) { search.setParent(val); } } public boolean isSearchParentValid() { return search.isParentSet(); } public void <API key>(boolean val) { if (val) { search.setParent(search.getParent()); } else { search.unsetParent(); } } /** * Handle an ABC pager letter click: filter objects by specified starting letter */ public void letterClicked() { if (letter != null) { UIComponent comp = FacesUtils.getComponent("accountEntryTypes:list"); HtmlDataTable tabla = (HtmlDataTable) comp; tabla.setFirst(0); search.setName(letter + "%"); } else { search.unsetName(); } } public Character getLetter() { return letter; } public void setLetter(Character letter) { this.letter = letter; } // Getters and setters to handle uploads // Getters and setters to manipulate active AccountEntryType object public java.lang.Integer getId() { return accountEntryType.getId(); } public String getName() { return accountEntryType.getName(); } public void setName(String name) { accountEntryType.setName(name); } public String getObservations() { return accountEntryType.getObservations(); } public void setObservations(String observations) { accountEntryType.setObservations(observations); } public Integer getCustomizableId() { return accountEntryType.getCustomizableId(); } public void setCustomizableId(Integer customizableId) { accountEntryType.setCustomizableId(customizableId); } public Integer getOwnerId() { return accountEntryType.getOwnerId(); } public void setOwnerId(Integer ownerId) { accountEntryType.setOwnerId(ownerId); } public Integer getDepartmentId() { return accountEntryType.getDepartmentId(); } public void setDepartmentId(Integer departmentId) { accountEntryType.setDepartmentId(departmentId); } public Date getInsertDate() { return accountEntryType.getInsertDate(); } public void setInsertDate(Date insertDate) { accountEntryType.setInsertDate(insertDate); } public Date getUpdateDate() { return accountEntryType.getUpdateDate(); } public void setUpdateDate(Date updateDate) { accountEntryType.setUpdateDate(updateDate); } public AccountEntryGroup getGroup() { return accountEntryType.getGroup(); } public void setGroup(AccountEntryGroup group) { accountEntryType.setGroup(group); } public AccountEntryType getParent() { return accountEntryType.getParent(); } public void setParent(AccountEntryType parent) { accountEntryType.setParent(parent); } /* accountEntryType - generated by stajanov (do not edit/delete) */ /** * Get the list of all parents * * @return the list of all parents */ public List<SelectItem> getParents() { /*List<AccountEntryType> refs = <API key>.getDefault().getAllEntities( null, new SortCriteria("name") ); ArrayList<SelectItem> ret = new ArrayList<SelectItem>(); for( AccountEntryType ref : refs ){ ret.add( new SelectItem( ref, ref.getName() ) ); } return ret; */ return getParentsWithNull(); } public List<SelectItem> getParentsWithNull() { ArrayList<SelectItem> ret = new ArrayList<SelectItem>(); if (accountEntryType != null) { if (this.getId() != null) { search.setDifferentId(this.getId()); } } search.setParent(null); List<AccountEntryType> refs = manager.getAllEntities(search, new SortCriteria("name")); for (AccountEntryType ref : refs) { ret.add(new SelectItem(ref, ref.getName())); } ret.add(0, new SelectItem("-- NINGUNO --")); search.unsetDifferentId(); search.unsetParent(); return ret; } }
<?php namespace Magento\Framework\Interception\Fixture\Intercepted; use Magento\Framework\Interception\Fixture\<API key>; class InterfacePlugin { /** * @param <API key> $subject * @param \Closure $next * @param string $param1 * @return string * @SuppressWarnings(PHPMD.<API key>) */ public function aroundC(<API key> $subject, \Closure $next, $param1) { return '<IP:C>' . $next($param1) . '</IP:C>'; } /** * @param <API key> $subject * @param \Closure $next * @param $param1 * @return string */ public function aroundF(<API key> $subject, \Closure $next, $param1) { return '<IP:F>' . $subject->D($next($subject->C($param1))) . '</IP:F>'; } /** * @SuppressWarnings(PHPMD.<API key>) */ public function beforeG(<API key> $subject, $param1) { return ['<IP:bG>' . $param1 . '</IP:bG>']; } /** * @SuppressWarnings(PHPMD.<API key>) */ public function aroundG(<API key> $subject, \Closure $next, $param1) { return $next('<IP:G>' . $param1 . '</IP:G>'); } /** * @SuppressWarnings(PHPMD.<API key>) */ public function afterG(<API key> $subject, $result) { return '<IP:aG>' . $result . '</IP:aG>'; } }
#include"client.h" #include"sockutil.h" #include<stdio.h> #include<string.h> #include<stdlib.h> #include<unistd.h> #include<errno.h> #include<sys/signal.h> #include<sys/select.h> int sockFd; void sigint_handler(int sig) { close(sockFd); printf("\nConnection has closed.\n"); exit(0); } int main(int argc,char* argv[]) { int n; fd_set oset,nset; char buf[BUFSIZE]; if(argc!=3) errexit("Usage:%s hostname port.\n",argv[0]); sockFd=connectSock(argv[1],argv[2],"tcp"); FD_ZERO(&oset); FD_SET(STDIN_FILENO,&oset); FD_SET(sockFd,&oset); nset=oset; signal(SIGPIPE,SIG_IGN); signal(SIGINT,sigint_handler); while(1) { if(select(4,&nset,NULL,NULL,0)<0) errexit("select err"); if(FD_ISSET(sockFd,&nset)) { n=recv(sockFd,buf,BUFSIZE,0); if(n<0) errexit("recv err"); if(n>0 && write(STDOUT_FILENO,buf,n)!=n) errexit("write err"); } if(FD_ISSET(STDIN_FILENO,&nset)) { fgets(buf,BUFSIZE,stdin); if((n=send(sockFd,buf,strlen(buf),0))<0) errexit("send err"); } nset=oset; } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>DEBUG Panel</title> </head> <body> <form action="/alarm" method="post"> <input type="submit" value="alarm" /> </form> <form action="/clear" method="post"> <input type="submit" value="clear" /> </form> </body> </html>
from datetime import datetime import MaKaC.common.filters as filters from MaKaC.webinterface.common.countries import CountryHolder class AccommFilterField( filters.FilterField ): """Contains the filtering criteria for the track of a contribution. Inherits from: AbstractFilterField Attributes: _values -- (list) List of track identifiers; _showNoValue -- (bool) Tells whether an contribution satisfies the filter if it hasn't belonged to any track. """ _id = "accomm" def satisfies( self, reg ): if reg.getAccommodation().<API key>() is None: return self._showNoValue if reg.getAccommodation().<API key>() not in reg.getRegistrationForm().<API key>().<API key>(): return self._showNoValue return reg.getAccommodation().<API key>().getId() in self._values class SessionFilterField( filters.FilterField ): _id = "session" def satisfies( self, reg ): if reg.getSessionList(): for sess in reg.getSessionList(): if sess.getId() in self._values: return True elif sess not in reg.getRegistrationForm().getSessionsForm().getSessionList(): return self._showNoValue else: return self._showNoValue return False class <API key>( filters.FilterField ): _id = "<API key>" def satisfies( self, reg ): if len(reg.getSessionList()) > 0: sess=reg.getSessionList()[0] if sess.getId() in self._values: return True elif sess not in reg.getRegistrationForm().getSessionsForm().getSessionList(): return self._showNoValue else: return self._showNoValue return False class EventFilterField(filters.FilterField): _id = "event" def satisfies(self, reg): if reg.getSocialEvents(): for event in reg.getSocialEvents(): if event.getId() in self._values: return True elif event.getSocialEventItem() not in reg.getRegistrationForm().getSocialEventForm().getSocialEventList(): return self._showNoValue else: return self._showNoValue return False class RegFilterCrit(filters.FilterCriteria): _availableFields = { \ AccommFilterField.getId():AccommFilterField, SessionFilterField.getId():SessionFilterField, <API key>.getId():<API key>, EventFilterField.getId():EventFilterField} class <API key>(filters.SortingField): def getSpecialId(self): try: if self._specialId: pass except AttributeError, e: return self._id return self._specialId class NameSF(<API key>): _id="Name" def compare( self, r1, r2 ): res1 = r1.getFamilyName().upper() if r1.getFirstName() != "": res1 = "%s, %s"%( res1, r1.getFirstName() ) res2 = r2.getFamilyName().upper() if r2.getFirstName() != "": res2 = "%s, %s"%( res2, r2.getFirstName() ) return cmp( res1, res2 ) class PositionSF( <API key> ): _id = "Position" def compare( self, r1, r2 ): return cmp( r1.getPosition().lower(), r2.getPosition().lower() ) class CountrySF( <API key> ): _id = "Country" def compare( self, r1, r2 ): return cmp( CountryHolder().getCountryById(r1.getCountry()).lower(), CountryHolder().getCountryById(r2.getCountry()).lower() ) class CitySF( <API key> ): _id = "City" def compare( self, r1, r2 ): return cmp( r1.getCity().lower(), r2.getCity().lower() ) class PhoneSF( <API key> ): _id = "Phone" def compare( self, r1, r2 ): return cmp( r1.getPhone().lower(), r2.getPhone().lower() ) class InstitutionSF( <API key> ): _id = "Institution" def compare( self, r1, r2 ): return cmp( r1.getInstitution().lower(), r2.getInstitution().lower() ) class EmailSF( <API key> ): _id = "Email" def compare( self, r1, r2 ): return cmp( r1.getEmail().lower(), r2.getEmail().lower() ) class SessionsSF( <API key> ): _id = "Sessions" def compare( self, r1, r2 ): ses1 = r1.getSessionList() ses2 = r2.getSessionList() i = 0 while(i<min(len(ses1), len(ses2))): v = cmp( ses1[i].getTitle().lower(), ses2[i].getTitle().lower() ) if v != 0: return v i += 1 if len(ses1)>len(ses2): return 1 elif len(ses1)<len(ses2): return -1 else: return 0 class AccommodationSF( <API key> ): _id = "Accommodation" def compare( self, r1, r2 ): if r2.getAccommodation() is None and r1.getAccommodation() is not None: return 1 elif r1.getAccommodation() is None and r2.getAccommodation() is not None: return -1 elif r1.getAccommodation() is None and r2.getAccommodation() is None: return 0 elif r2.getAccommodation().<API key>() is None and r1.getAccommodation().<API key>() is not None: return 1 elif r1.getAccommodation().<API key>() is None and r2.getAccommodation().<API key>() is not None: return -1 elif r1.getAccommodation().<API key>() is None and r2.getAccommodation().<API key>() is None: return 0 else: return cmp(r1.getAccommodation().<API key>().getCaption(), r2.getAccommodation().<API key>().getCaption()) class ArrivalDateSF( <API key> ): _id = "ArrivalDate" def compare( self, r1, r2 ): if r2.getAccommodation() is None and r1.getAccommodation() is not None: return 1 elif r1.getAccommodation() is None and r2.getAccommodation() is not None: return -1 elif r1.getAccommodation() is None and r2.getAccommodation() is None: return 0 elif r2.getAccommodation().getArrivalDate() is None and r1.getAccommodation().getArrivalDate() is not None: return 1 elif r1.getAccommodation().getArrivalDate() is None and r2.getAccommodation().getArrivalDate() is not None: return -1 elif r1.getAccommodation().getArrivalDate() is None and r2.getAccommodation().getArrivalDate() is None: return 0 else: return cmp(r1.getAccommodation().getArrivalDate(), r2.getAccommodation().getArrivalDate()) class DepartureDateSF( <API key> ): _id = "DepartureDate" def compare( self, r1, r2 ): if r2.getAccommodation() is None and r1.getAccommodation() is not None: return 1 elif r1.getAccommodation() is None and r2.getAccommodation() is not None: return -1 elif r1.getAccommodation() is None and r2.getAccommodation() is None: return 0 elif r2.getAccommodation().getDepartureDate() is None and r1.getAccommodation().getDepartureDate() is not None: return 1 elif r1.getAccommodation().getDepartureDate() is None and r2.getAccommodation().getDepartureDate() is not None: return -1 elif r1.getAccommodation().getDepartureDate() is None and r2.getAccommodation().getDepartureDate() is None: return 0 else: return cmp(r1.getAccommodation().getDepartureDate(), r2.getAccommodation().getDepartureDate()) class SocialEventsSF( <API key> ): _id = "SocialEvents" def compare( self, r1, r2 ): ses1 = r1.getSocialEvents() ses2 = r2.getSocialEvents() i = 0 while(i<min(len(ses1), len(ses2))): v = cmp( ses1[i].getCaption().lower(), ses2[i].getCaption().lower() ) if v != 0: return v i += 1 if len(ses1)>len(ses2): return 1 elif len(ses1)<len(ses2): return -1 else: return 0 class <API key>( <API key> ): _id = "ReasonParticipation" def compare( self, r1, r2 ): rp1=r1.<API key>() or "" rp2=r2.<API key>() or "" return cmp( rp1.lower(), rp2.lower() ) class AddressSF( <API key> ): _id = "Address" def compare( self, r1, r2 ): a1=r1.getAddress() or "" a2=r2.getAddress() or "" return cmp( a.lower().strip(), a.lower().strip() ) class RegistrationDateSF( <API key> ): _id = "RegistrationDate" def compare( self, r1, r2 ): rd1=r1.getRegistrationDate() or datetime(1995, 1, 1) rd2=r2.getRegistrationDate() or datetime(1995, 1, 1) return cmp( rd1, rd2 ) class GeneralFieldSF( <API key> ): _id = "<groupID>-<fieldId>" def compare( self, r1, r2 ): if self.getSpecialId() != self._id: ids=self.getSpecialId().split("-") if len(ids)==2: group1=r1.<API key>(ids[0]) group2=r2.<API key>(ids[0]) v1="" if group1 is not None: i1=group1.getResponseItemById(ids[1]) if i1 is not None: v1=i1.getValue() v2="" if group2 is not None: i2=group2.getResponseItemById(ids[1]) if i2 is not None: v2=i2.getValue() return cmp( v1.lower().strip(), v2.lower().strip() ) return 0 class StatusesSF( <API key> ): _id = "s-<statusId>" def compare( self, r1, r2 ): if self.getSpecialId() != self._id: ids=self.getSpecialId().split("-") if len(ids)==2: s1=r1.getStatusById(ids[1]) s2=r2.getStatusById(ids[1]) if s1.getStatusValue() is None and s2.getStatusValue() is None: return 0 if s1.getStatusValue() is None: return -1 if s2.getStatusValue() is None: return 1 return cmp( s1.getStatusValue().getCaption().lower().strip(), s2.getStatusValue().getCaption().lower().strip() ) return 0 class IsPayedSF(<API key>): _id="isPayed" def compare( self, r1, r2 ): return cmp( r1.isPayedText(), r2.isPayedText() ) class IdPayment(<API key>): _id="idpayment" def compare( self, r1, r2 ): return cmp( r1.getIdPay(), r2.getIdPay() ) class SortingCriteria( filters.SortingCriteria ): _availableFields = {NameSF.getId():NameSF, \ PositionSF.getId(): PositionSF, \ CitySF.getId():CitySF, \ PhoneSF.getId():PhoneSF, \ InstitutionSF.getId():InstitutionSF, \ EmailSF.getId():EmailSF, \ SessionsSF.getId():SessionsSF, \ AccommodationSF.getId():AccommodationSF, \ ArrivalDateSF.getId():ArrivalDateSF, \ DepartureDateSF.getId():DepartureDateSF, \ SocialEventsSF.getId():SocialEventsSF, \ <API key>.getId():<API key>, \ GeneralFieldSF.getId():GeneralFieldSF, \ StatusesSF.getId():StatusesSF, \ RegistrationDateSF.getId():RegistrationDateSF, \ CountrySF.getId():CountrySF, \ IsPayedSF.getId():IsPayedSF, \ IdPayment.getId():IdPayment} def __init__( self, crit = []): self._sortingField = None if crit: fieldKlass = self._availableFields.get( crit[0], None ) if fieldKlass: self._sortingField = self._createField( fieldKlass ) elif crit[0].startswith("s-"): self._sortingField = self._createField( StatusesSF ) self._sortingField._specialId=crit[0] else: self._sortingField = self._createField( GeneralFieldSF ) self._sortingField._specialId=crit[0]
var async = require('async'); var DateUtils = require('../util/DateUtils.class'); var <API key> = function(bot) { this.bot = bot; this.<API key> = this.bot.config.edserv.manager; }; <API key>.prototype = { request<API key>: function(requestor, presenter) { var bot = this.bot; var manager = this; async.waterfall([ function(next) { if (requestor != manager.<API key>) { bot.say(requestor, "Sorry, only "+manager.<API key>+" can authorize people as presenters"); return; } bot.persistence.getPlayerByName(presenter, function(player, err) { if (err) { bot.say(requestor, "I couldn't authorize "+presenter+", This happened: "+err); } else if (!player) { bot.say(requestor, "I don't know who is "+presenter+", may be you mistyped it?"); } else { next(); } }); }, function(next) { bot.persistence.<API key>(presenter, function(presenterObject, err) { if (err) { bot.say(requestor, "I couldn't authorize "+presenter+", This happened: "+err); console.log(err); } else if (presenterObject) { bot.say(requestor, presenter+" is already an authorized presenter."); } else { next(); } }); }, function(next) { bot.persistence.<API key>(presenter, function(result, err) { if (err) { bot.say(requestor, "I couldn't authorize "+presenter+", This happened: "+err); } else { bot.say(requestor, presenter+" has been authorized as presenter"); bot.say(presenter, presenter+", you have been authorized by "+requestor+" as a presenter"); } }); } ], function (error) { if (error) { console.log("General error."); console.log(error); console.log(error.stack); bot.say(requestor, "I couldn't authorize "+presenter+", This happened: "+error); } }); }, _endConversation: function(conversation){ this.bot.conversationManager.endConversation(conversation); }, <API key>: function(conversation, from) { var bot = this.bot; var manager = this; async.waterfall([ function(next){ if (from == manager.<API key>) { next(false, {}); } else { bot.persistence.<API key>(from, function(presenterObject, err) { next(err, presenterObject); }); } }, function(presenterObject, next) { if (presenterObject) { next(false); } else { bot.say(from, "Only the EdServ manager or an authorized presenter can check the list, sorry!"); manager._endConversation(conversation) } }, function(next) { bot.persistence.getTrainings(function(trainings, err) { next(err, trainings); }); }, function (trainings, next) { if (!trainings || trainings.length == 0) { bot.say(from, "Hmmm... I know of no training sessions"); manager._endConversation(conversation); } else { bot.say(from, "From which session do you wish to list the attendees?"); for (var i = 0; i < trainings.length; i++) { var training = trainings[i]; bot.say(from, (i+1)+" - \""+training.title+"\" by "+training.presenter); bot.conversationManager.setConversationData(conversation, 'trainingSessions.k'+(i+1), training, function(){}); } } } ], function (error) { if (error) { bot.say(from, "Heck, something happened! : "+err); console.log(error); console.log(error.stack); } }); }, showAttendantsTo: function(conversation, requestor, training) { var bot = this.bot; var manager = this; var message = "You can try with another training, perhaps? Ask me again, in that case"; console.log("Getting attendees for session"); console.log(training); async.waterfall([ function(next) { bot.persistence.getAttendants(training._id, function(attendantsList, err) { next(err, training, attendantsList); }); }, function(training, attendantsList, next) { if (!attendantsList || attendantsList.length == 0) { bot.say(requestor, "Nobody has registered for \""+training.title+"\". "+message); } else { bot.say(requestor, attendantsList.length+" people registered for \""+training.title+"\":"); for (var i = 0; i < attendantsList.length; i++) { var attendant = attendantsList[i]; bot.say(requestor, "- "+attendant.user); } bot.say(requestor, message); } manager._endConversation(conversation); } ], function (error) { if (error) { bot.say(requestor, "Sorry, I couldn't complete your command: "+err); console.log(error); console.log(error.stack); } }); }, <API key>: function(from) { var bot = this.bot; var edsrvManager = bot.config.edserv.manager; async.waterfall([ function(next) { bot.persistence.<API key>(from, function(presenterObject, err) { if (err) { bot.say(from, "I couldn't find authorize: " + from + " as presenter, This happened: " + err); console.log(err); } else if (presenterObject || (edsrvManager == from)) { console.log('presenter:', from, 'manager:', edsrvManager); next(); } else { bot.say(from, "I couldn't find " + from + " as authorized presenter, contact your regional manager to do that"); } }); }, function(next) { bot.conversationManager.startConversation(from, "<API key>", "sessionTitle", function() { bot.say(from, "Wanna create a training session? that's awesome! First, what's this session going to be called? Type in the title for the session as you want it to appear for everyone else:"); }, function(conversation) { // TODO: Add support to resume conversations }) } ], function (err) { if (err) { bot.say(from,"Something happened when I tried to find out... "+err); } }) }, <API key>: function(creator, session, callback) { var bot = this.bot; bot.persistence.<API key>(session, callback); bot.say(creator, "The session '"+session.title+"' has been created by you and published."); }, <API key>: function(from) { var bot = this.bot; async.waterfall([ function(next) { bot.conversationManager.startConversation(from, "registerToSession", "<API key>", function(conversation) { next(false, conversation); }, function(conversation) { // TODO: Add support to resume conversations } ); }, function (conversation, next) { bot.persistence.getTrainingSessions(function(result, err) { next(err, conversation, result); }); }, function (conversation, trainingSessions, next) { if (trainingSessions.length > 0) { var sessions = "Upcoming sessions \n"; for (var i = 0; i < trainingSessions.length; i++) { var string = "" + (i+1) + " - '" + trainingSessions[i].title + "' on "+ trainingSessions[i].desiredDate + " " + trainingSessions[i].time +" ("+trainingSessions[i].duration + "h) @ " + trainingSessions[i].location + " - Presenter: " + trainingSessions[i].presenter + "\n"; sessions += string; trainingSessions[i].customId = i+1; } bot.conversationManager.setConversationData(conversation, 'sessions', trainingSessions, function(){}); sessions += "Let's pick a session from the list (you can either spell the name or the number). If you don't want to enroll, you can say 'NO'."; bot.say(from, sessions); } else { bot.say(from, "No sessions scheduled ahead. Stay tuned!") bot.conversationManager.endConversation(conversation) } } ], function (err) { if (err) { bot.say(from,"Something happened when I tried to find out... "+err); } } ) }, registerToSession: function(from, sessionIdOrName, conversation, callback) { var bot = this.bot; var selectedSession = null; var noSessions = false; console.log("user " +from + " wants to enroll to "+ sessionIdOrName); if (!conversation.data.sessions) { noSessions = true; } else { for (var i = 0; i < conversation.data.sessions.length; i++) { var session = conversation.data.sessions[i]; if (session.customId == sessionIdOrName || session.title == sessionIdOrName) { selectedSession = session; break; } } } if (selectedSession) { var desiredDate = new Date(selectedSession.desiredDate); var <API key> = bot.config.edserv.thresholds.enrollment; desiredDate.subtractHours(<API key>); if (new Date() < desiredDate) { var hasRegistration = false; bot.persistence.getRegisteredUsers(from, selectedSession._id, function(result, err) { if (err) { bot.say(from,"Something happened when I tried to find out... "+err); } else { if (result && result.length > 0) { bot.say(from,"You are already enrolled to the selected training [" + selectedSession.title + "]"); hasRegistration = true; } else { bot.persistence.<API key>(from, selectedSession._id,function(result, err){ if (err) { bot.say(from,"Something happened when I tried to find out... "+err); } else { bot.say(from, "Great. You've been enrolled to '" + selectedSession.title + "' on " + selectedSession.desiredDate + " " + selectedSession.time + " @ " + selectedSession.location + ". See you there!"); bot.conversationManager.endConversation(conversation); } }); callback(selectedSession); } } }); } else { bot.say(from, "Sorry, that session inscriptions have expired! It's now " + new Date() + " but the threshold to register to this session has pased (your last chance was before " + desiredDate + ")"); } } else if (noSessions) { bot.conversationManager.endConversation(conversation); bot.say(from, "We'll be publishing new training sessions soon.") } else if (sessionIdOrName == "NO") { bot.conversationManager.endConversation(conversation); bot.say(from,"You chose not to attend any of the upcoming sessions. I'll remind you of any new sessions scheduled, so you'll have chance to register to those. Have a nice day"); } else { bot.say(from, 'Sorry, that session does not exist!'); } }, initRateSession: function (requestor) { var bot = this.bot async.waterfall([ function (next) { bot.conversationManager.startConversation(requestor, 'rateSession', 'waitingForSession', function(conversation) { next(false, conversation); }, function(conversation) { // TODO: Add support to resume conversations }) bot.say(requestor, "First thing's first, thanks for taking the time to anonymously rate a Breakfast & Learn. This is really important to us! Now, let's begin with selecting a session to rate. Which from the following sessions you've attended do you wish to rate?") }, function (conversation, next) { bot.persistence.getTrainings(function(result, err) { next(err, conversation, result); }); }, function (conversation, trainingSessions, next) { var sessions = "" for (var i = 0; i < trainingSessions.length; i++) { var string = "" + (i+1) + " - '" + trainingSessions[i].title + "' on "+ trainingSessions[i].desiredDate + " " + trainingSessions[i].time +" ("+trainingSessions[i].duration + "h) @ " + trainingSessions[i].location + " - Presenter: " + trainingSessions[i].presenter + "\n" sessions += string trainingSessions[i].customId = i+1 } bot.conversationManager.setConversationData(conversation, 'sessions', trainingSessions, function(){}) var offices = ["BsAs", "Medellin", "Montevideo", "Rosario", "Parana"] bot.conversationManager.setConversationData(conversation, 'offices', offices, function(){}) bot.say(requestor, sessions) } ], function(){}) }, rateSession: function(<API key>, callback) { var bot = this.bot var conversation = <API key>.conversation var user = <API key>.user var sessionRatingData = { sessionId: conversation.data.session._id, sessionTitle: conversation.data.session.title, ratingDate: new Date(), ratingOffice: conversation.data.office, ratings: { understanding: conversation.data.understandingRating, relevance: conversation.data.relevanceRating, performance: conversation.data.performanceRating, content: conversation.data.contentRating, methodology: conversation.data.methodologyRating, overall: conversation.data.overallRating }, recommended: conversation.data.recommended, comments: conversation.data.comments } if (user) { sessionRatingData.user = user } bot.persistence.insertSessionRating(sessionRatingData, callback) } }; module.exports = <API key>;