Example #1
0
void UserActions::Init()
{
	m_actionNames.clear();
	m_actionNames.push_back(_("none"));
	m_actionNames.push_back(_("highlight"));
	m_actionNames.push_back(_("notify login/out"));
	m_actionNames.push_back(_("ignore chat"));
	m_actionNames.push_back(_("ignore pm"));
	m_actionNames.push_back(_("autokick"));
	m_actionNames.push_back(_("notify hosted battle"));
	m_actionNames.push_back(_("notify status change"));

	m_configActionNames.clear();
	m_configActionNames.push_back(_T("none"));
	m_configActionNames.push_back(_T("highlight"));
	m_configActionNames.push_back(_T("notify_login"));
	m_configActionNames.push_back(_T("ignore_chat"));
	m_configActionNames.push_back(_T("ignore_pm"));
	m_configActionNames.push_back(_T("autokick"));
	m_configActionNames.push_back(_T("notify_hosted"));
	m_configActionNames.push_back(_T("notify_status"));

	m_actionTooltips.clear();
	m_actionTooltips.push_back(_("no action at all"));
	m_actionTooltips.push_back(_("highlight user in nick list and battles he participates in"));
	m_actionTooltips.push_back(_("popup a message box when user logs in/out from  the server"));
	m_actionTooltips.push_back(_("you won't see message by these users in normal channels"));
	m_actionTooltips.push_back(_("ignore private messages of these users, no pm window will open if any of these try to contact you privately"));
	m_actionTooltips.push_back(_("automatically kick users from battles hosted by yourself"));
	m_actionTooltips.push_back(_("popup a message box when user hosts a new battle"));
	m_actionTooltips.push_back(_("popup a message box when user changes away status"));

	// setup if empty
	if (!cfg().Exists(_T( "/Groups"))) {
		AddGroup(_("Default"));
		AddGroup(_("Ignore PM"));
		ChangeAction(_("Ignore PM"), UserActions::ActIgnorePM);
		AddGroup(_("Ignore chat"));
		ChangeAction(_("Ignore chat"), UserActions::ActIgnoreChat);
		AddGroup(_("Battle Autokick"));
		ChangeAction(_("Battle Autokick"), UserActions::ActAutokick);
		AddGroup(_("Friends"));
		ChangeAction(_("Friends"), UserActions::ActNotifBattle);
		ChangeAction(_("Friends"), UserActions::ActHighlight);
		ChangeAction(_("Friends"), UserActions::ActNotifLogin);
		// TODO select better color
		SetGroupColor(_("Friends"), wxColour(0, 0, 255));
	}


	// read
	m_groupNames = GetGroups();
	m_groupMap.clear();
	m_groupActions.clear();
	m_actionsGroups.clear();
	m_actionsPeople.clear();
	m_knownUsers.Clear();
	for (unsigned int i = 0; i < m_groupNames.GetCount(); ++i) {
		wxString name = m_groupNames[i];
		m_groupMap[name] = GetPeopleList(name);
		for (unsigned int k = 0; k < m_groupMap[name].GetCount(); ++k) {
			wxString user = m_groupMap[name][k];
			m_knownUsers.Add(user);
			m_peopleGroup[user] = name;
		}
		m_groupActions[name] = GetGroupActions(name);
	}
	for (size_t i = 0; i < m_actionNames.size(); ++i) {
		UserActions::ActionType cur = (UserActions::ActionType)(1 << i);
		wxArrayString tmp;
		for (unsigned int j = 0; j < m_groupNames.GetCount(); ++j) {
			wxString name = m_groupNames[j];
			if ((m_groupActions[name] & cur) != 0) {
				tmp.Add(name);
				for (unsigned int k = 0; k < m_groupMap[name].GetCount(); ++k) {
					m_actionsPeople[cur].Add((m_groupMap[name])[k]);
				}
			}
		}
		tmp.Sort();
		m_actionsGroups[cur] = tmp;
	}
	m_actionsGroups[ActNone] = m_groupNames;
	m_groupNames.Sort();
	m_knownUsers.Sort();
}
Example #2
0
SplitterGUI::~SplitterGUI()
{
    KConfigGroup cfg(KSharedConfig::openConfig(), QStringLiteral("Splitter"));
    cfg.writeEntry("OverWriteFiles", overwriteCb->isChecked());
}
Example #3
0
int         tidyDocCleanAndRepair( TidyDocImpl* doc )
{
    Bool word2K   = cfgBool( doc, TidyWord2000 );
    Bool logical  = cfgBool( doc, TidyLogicalEmphasis );
    Bool clean    = cfgBool( doc, TidyMakeClean );
    Bool dropFont = cfgBool( doc, TidyDropFontTags );
    Bool htmlOut  = cfgBool( doc, TidyHtmlOut );
    Bool xmlOut   = cfgBool( doc, TidyXmlOut );
    Bool xhtmlOut = cfgBool( doc, TidyXhtmlOut );
    Bool xmlDecl  = cfgBool( doc, TidyXmlDecl );
    Bool tidyMark = cfgBool( doc, TidyMark );
    Bool tidyXmlTags = cfgBool( doc, TidyXmlTags );
    Bool wantNameAttr = cfgBool( doc, TidyAnchorAsName );
    Bool mergeEmphasis = cfgBool( doc, TidyMergeEmphasis );
    Node* node;

    if (tidyXmlTags)
        return tidyDocStatus( doc );

    /* simplifies <b><b> ... </b> ...</b> etc. */
    if ( mergeEmphasis )
        TY_(NestedEmphasis)( doc, &doc->root );

    /* cleans up <dir>indented text</dir> etc. */
    TY_(List2BQ)( doc, &doc->root );
    TY_(BQ2Div)( doc, &doc->root );

    /* replaces i by em and b by strong */
    if ( logical )
        TY_(EmFromI)( doc, &doc->root );

    if ( word2K && TY_(IsWord2000)(doc) )
    {
        /* prune Word2000's <![if ...]> ... <![endif]> */
        TY_(DropSections)( doc, &doc->root );

        /* drop style & class attributes and empty p, span elements */
        TY_(CleanWord2000)( doc, &doc->root );
        TY_(DropEmptyElements)(doc, &doc->root);
    }

    /* replaces presentational markup by style rules */
    if ( clean || dropFont )
        TY_(CleanDocument)( doc );

    /*  Move terminating <br /> tags from out of paragraphs  */
    /*!  Do we want to do this for all block-level elements?  */

    /* This is disabled due to http://tidy.sf.net/bug/681116 */
#if 0
    FixBrakes( doc, TY_(FindBody)( doc ));
#endif

    /*  Reconcile http-equiv meta element with output encoding  */
    if (cfg( doc, TidyOutCharEncoding) != RAW
#ifndef NO_NATIVE_ISO2022_SUPPORT
            && cfg( doc, TidyOutCharEncoding) != ISO2022
#endif
       )
        TY_(VerifyHTTPEquiv)( doc, TY_(FindHEAD)( doc ));

    if ( !TY_(CheckNodeIntegrity)( &doc->root ) )
        TidyPanic( doc->allocator, integrity );

    /* remember given doctype for reporting */
    node = TY_(FindDocType)(doc);
    if (node)
    {
        AttVal* fpi = TY_(GetAttrByName)(node, "PUBLIC");
        if (AttrHasValue(fpi))
        {
            if (doc->givenDoctype)
                TidyDocFree(doc, doc->givenDoctype);
            doc->givenDoctype = TY_(tmbstrdup)(doc->allocator,fpi->value);
        }
    }

    if ( doc->root.content )
    {
        /* If we had XHTML input but want HTML output */
        if ( htmlOut && doc->lexer->isvoyager )
        {
            Node* node = TY_(FindDocType)(doc);
            /* Remove reference, but do not free */
            if (node)
                TY_(RemoveNode)(node);
        }

        if (xhtmlOut && !htmlOut)
        {
            TY_(SetXHTMLDocType)(doc);
            /*            TY_(FixAnchors)(doc, &doc->root, wantNameAttr, yes); */
            TY_(FixXhtmlNamespace)(doc, yes);
            TY_(FixLanguageInformation)(doc, &doc->root, yes, yes);
        }
        else
        {
            TY_(FixDocType)(doc);
            TY_(FixAnchors)(doc, &doc->root, wantNameAttr, yes);
            TY_(FixXhtmlNamespace)(doc, no);
            TY_(FixLanguageInformation)(doc, &doc->root, no, yes);
        }

        if (tidyMark )
            TY_(AddGenerator)(doc);
    }

    /* ensure presence of initial <?xml version="1.0"?> */
    if ( xmlOut && xmlDecl )
        TY_(FixXmlDecl)( doc );

    return tidyDocStatus( doc );
}
Example #4
0
/**
 * load(): Load Gens configuration.
 * @param filename Configuration filename.
 * @param Game_Active ???
 */
int Config::load(const string& filename, void* gameActive)
{
    int new_val, i;
    char buf[256];

#ifdef GENS_OS_WIN32
    SetCurrentDirectory(PathNames.Gens_EXE_Path);
#endif /* GENS_OS_WIN32 */

    INI cfg(filename);

    CRam_Flag = 1;

    // Paths
    cfg.getString("General", "ROM Path", PathNames.Gens_Path, Rom_Dir, sizeof(Rom_Dir));
    cfg.getString("General", "Save Path", PathNames.Gens_Path, State_Dir, sizeof(State_Dir));
    cfg.getString("General", "SRAM Path", PathNames.Gens_Path, SRAM_Dir, sizeof(SRAM_Dir));
    cfg.getString("General", "BRAM Path", PathNames.Gens_Path, BRAM_Dir, sizeof(BRAM_Dir));
    cfg.getString("General", "Dump Path", PathNames.Gens_Path, PathNames.Dump_WAV_Dir, sizeof(PathNames.Dump_WAV_Dir));
    cfg.getString("General", "Dump GYM Path", PathNames.Gens_Path, PathNames.Dump_GYM_Dir, sizeof(PathNames.Dump_GYM_Dir));
    cfg.getString("General", "Screen Shot Path", PathNames.Gens_Path, PathNames.Screenshot_Dir, sizeof(PathNames.Screenshot_Dir));
    cfg.getString("General", "Patch Path", PathNames.Gens_Path, Patch_Dir, sizeof(Patch_Dir));
    cfg.getString("General", "IPS Patch Path", PathNames.Gens_Path, IPS_Dir, sizeof(IPS_Dir));

    // Genesis BIOS
    cfg.getString("General", "Genesis BIOS", "", BIOS_Filenames.MD_TMSS, sizeof(BIOS_Filenames.MD_TMSS));

    // SegaCD BIOSes
    cfg.getString("General", "USA CD BIOS", "", BIOS_Filenames.SegaCD_US, sizeof(BIOS_Filenames.SegaCD_US));
    cfg.getString("General", "Europe CD BIOS", "", BIOS_Filenames.MegaCD_EU, sizeof(BIOS_Filenames.MegaCD_EU));
    cfg.getString("General", "Japan CD BIOS", "", BIOS_Filenames.MegaCD_JP, sizeof(BIOS_Filenames.MegaCD_JP));

    // 32X BIOSes
    cfg.getString("General", "32X 68000 BIOS", "", BIOS_Filenames._32X_MC68000, sizeof(BIOS_Filenames._32X_MC68000));
    cfg.getString("General", "32X Master SH2 BIOS", "", BIOS_Filenames._32X_MSH2, sizeof(BIOS_Filenames._32X_MSH2));
    cfg.getString("General", "32X Slave SH2 BIOS", "", BIOS_Filenames._32X_SSH2, sizeof(BIOS_Filenames._32X_SSH2));

    // Last 9 ROMs
    for (i = 0; i < 9; i++)
    {
        sprintf(buf, "ROM %d", i + 1);
        cfg.getString("General", buf, "", Recent_Rom[i], sizeof(Recent_Rom[i]));
    }

#ifdef GENS_CDROM
    // Physical CD-ROM support for SegaCD
#if defined(GENS_OS_WIN32)
    // Win32 ASPI uses a device ID number.
    cdromDeviceID = cfg.getInt("Options", "CD Drive", 0);
#elif defined(GENS_OS_UNIX)
    // Unix uses a device name.
    cfg.getString("General", "CD Drive", "/dev/cdrom", cdromDeviceName, sizeof(cdromDeviceName));
#endif /* GENS_OS_WIN32 / GENS_OS_UNIX */
    cdromSpeed = cfg.getInt("General", "CD Speed", 0);
#endif /* GENS_CDROM */

    Current_State = cfg.getInt("General", "State Number", 0);
    Language = cfg.getInt("General", "Language", 0);
    Window_Pos.x = cfg.getInt("General", "Window X", 0);
    Window_Pos.y = cfg.getInt("General", "Window Y", 0);
    Intro_Style = cfg.getInt("General", "Intro Style", 0);
    draw->setIntroEffectColor(cfg.getInt("General", "Free Mode Color", 7));
    Sleep_Time = cfg.getInt("General", "Allow Idle", 0) & 1;

    // Video adjustments
    Contrast_Level = cfg.getInt("Graphics", "Contrast", 100);
    Brightness_Level = cfg.getInt("Graphics", "Brightness", 100);
    Greyscale = cfg.getInt("Graphics", "Greyscale", 0);
    Invert_Color = cfg.getInt("Graphics", "Invert", 0);

    // Video settings
    Video.VSync_FS = cfg.getInt("Graphics", "Full Screen VSync", 0) & 1;
    Video.VSync_W = cfg.getInt("Graphics", "Windows VSync", 0) & 1;
    draw->setFullScreen(cfg.getBool("Graphics", "Full Screen", false));
    Video.borderColorEmulation = cfg.getBool("Graphics", "Border Color Emulation", true);
    Video.pauseTint = cfg.getBool("Graphics", "Pause Tint", true);

    // Renderer: Full Screen
    string renderTag = cfg.getString("Graphics", "Render Fullscreen", "");
    mapStrToInt::iterator renderMDP;
    if (renderTag.empty())
        Video.Render_FS = 1;
    else
    {
        std::transform(renderTag.begin(), renderTag.end(), renderTag.begin(), ::tolower);
        renderMDP = PluginMgr::tblRenderPlugins.find(renderTag);
        if (renderMDP == PluginMgr::tblRenderPlugins.end())
            Video.Render_FS = 1;
        else
            Video.Render_FS = (*renderMDP).second;
    }

    // Renderer: Windowed
    renderTag = cfg.getString("Graphics", "Render Windowed", "");
    if (renderTag.empty())
        Video.Render_W = 1;
    else
    {
        std::transform(renderTag.begin(), renderTag.end(), renderTag.begin(), ::tolower);
        renderMDP = PluginMgr::tblRenderPlugins.find(renderTag);
        if (renderMDP == PluginMgr::tblRenderPlugins.end())
            Video.Render_W = 1;
        else
            Video.Render_W = (*renderMDP).second;
    }

#ifndef GENS_OS_WIN32
    // TODO: Add a 555/565 override for Win32.
    bppOut = (unsigned char)(cfg.getInt("Graphics", "Bits Per Pixel", 32));
    if (bppOut != 15 && bppOut != 16 && bppOut != 32)
    {
        // Invalid bpp. Set it to 32 by default.
        bppOut = 32;
    }
    bppMD = bppOut;
#endif /* GENS_OS_WIN32 */

#ifdef GENS_OPENGL
    Video.OpenGL = cfg.getInt("Graphics", "Render OpenGL", 0);
    Video.Width_GL = cfg.getInt("Graphics", "OpenGL Width", 640);
    Video.Height_GL = cfg.getInt("Graphics", "OpenGL Height", 480);
    Video.glLinearFilter = cfg.getInt("Graphics", "OpenGL Filter", 0);

    // Set the OpenGL renderer.
    // NOTE: Don't do this while Gens is loading; otherwise, GTK+ raises an assert
    // because the window hasn't been created yet.
    if (is_gens_running())
        Options::setOpenGL(Video.OpenGL);
#endif

    //Set_Render(Full_Screen, -1, 1);

    // Recalculate the MD and 32X palettes using the new color and video mode settings.
    // NOTE: This is only done if Gens is currently running.
    // If Gens isn't running, then this is before Gens had a chance to parse
    // command line arguments, so things may change later.
    if (is_gens_running())
        Recalculate_Palettes();

    Options::setStretch(cfg.getInt("Graphics", "Stretch", 0));
#ifdef GENS_OS_WIN32
    Options::setSwRender(cfg.getBool("Graphics", "Software Blit", false));
#endif /* GENS_OS_WIN32 */
    Sprite_Over = cfg.getInt("Graphics", "Sprite Limit", 1);
    Frame_Skip = cfg.getInt("Graphics", "Frame Skip", -1);

    // Sound settings
    audio->setSoundRate(cfg.getInt("Sound", "Rate", 22050));
    audio->setStereo(cfg.getBool("Sound", "Stereo", true));

    if (cfg.getInt("Sound", "Z80 State", 1))
        Z80_State |= 1;
    else
        Z80_State &= ~1;

    // Only load the IC sound settings if sound can be initialized.
    new_val = cfg.getInt("Sound", "State", 1);
    if (new_val == audio->enabled() ||
            (new_val != audio->enabled() && Options::setSoundEnable(true)))
    {
        YM2612_Enable = cfg.getInt("Sound", "YM2612 State", 1);
        PSG_Enable = cfg.getInt("Sound", "PSG State", 1);
        DAC_Enable = cfg.getInt("Sound", "DAC State", 1);
        PCM_Enable = cfg.getInt("Sound", "PCM State", 1);
        PWM_Enable = cfg.getInt("Sound", "PWM State", 1);
        CDDA_Enable = cfg.getInt("Sound", "CDDA State", 1);

        // Improved sound options
        YM2612_Improv = cfg.getInt("Sound", "YM2612 Improvement", 0);
        DAC_Improv = cfg.getInt("Sound", "DAC Improvement", 0);
        PSG_Improv = cfg.getInt("Sound", "PSG Improvement", 0);
    }

    // Country codes
    Country = cfg.getInt("CPU", "Country", -1);
    Country_Order[0] = cfg.getInt("CPU", "Prefered Country 1", 0);
    Country_Order[1] = cfg.getInt("CPU", "Prefered Country 2", 1);
    Country_Order[2] = cfg.getInt("CPU", "Prefered Country 3", 2);
    Check_Country_Order();

    // CPU options

    SegaCD_Accurate = cfg.getInt("CPU", "Perfect synchro between main and sub CPU (Sega CD)", 0);
    MSH2_Speed = cfg.getInt("CPU", "Main SH2 Speed", 100);
    SSH2_Speed = cfg.getInt("CPU", "Slave SH2 Speed", 100);

    // Make sure the SH2 speeds aren't below 0.
    if (MSH2_Speed < 0)
        MSH2_Speed = 0;
    if (SSH2_Speed < 0)
        SSH2_Speed = 0;

    // Various settings
    draw->setFastBlur(cfg.getBool("Options", "Fast Blur", false));
    draw->setFPSEnabled(cfg.getBool("Options", "FPS", false));
    draw->setFPSStyle(cfg.getInt("Options", "FPS Style", 0));
    draw->setMsgEnabled(cfg.getBool("Options", "Message", true));
    draw->setMsgStyle(cfg.getInt("Options", "Message Style", 0));
    Show_LED = cfg.getInt("Options", "LED", 1);
    Auto_Fix_CS = cfg.getInt("Options", "Auto Fix Checksum", 0);
    Auto_Pause = cfg.getInt("Options", "Auto Pause", 0);

    // SegaCD BRAM cartridge size
    BRAM_Ex_Size = cfg.getInt("Options", "RAM Cart Size", 3);
    if (BRAM_Ex_Size == -1)
    {
        BRAM_Ex_State &= 1;
        BRAM_Ex_Size = 0;
    }
    else if (BRAM_Ex_Size < -1 || BRAM_Ex_Size > 3)
        BRAM_Ex_Size = 3;
    else
        BRAM_Ex_State |= 0x100;

    // Miscellaneous files
#if defined(__WIN32__)
    cfg.getString("Options", "7z Binary", "C:\\Program Files\\7-Zip\\7z.exe",
                  Misc_Filenames._7z_Binary, sizeof(Misc_Filenames._7z_Binary));
    cfg.getString("Options", "RAR Binary", "C:\\Program Files\\WinRAR\\Rar.exe",
                  Misc_Filenames.RAR_Binary, sizeof(Misc_Filenames.RAR_Binary));
#else /* !defined(__WIN32__) */
    cfg.getString("Options", "7z Binary", "/usr/bin/7z",
                  Misc_Filenames._7z_Binary, sizeof(Misc_Filenames._7z_Binary));
    cfg.getString("Options", "RAR Binary", "/usr/bin/rar",
                  Misc_Filenames.RAR_Binary, sizeof(Misc_Filenames.RAR_Binary));
#endif

    // Controller settings
    Controller_1_Type = cfg.getInt("Input", "P1.Type", 1);
    Controller_1B_Type = cfg.getInt("Input", "P1B.Type", 1);
    Controller_1C_Type = cfg.getInt("Input", "P1C.Type", 1);
    Controller_1D_Type = cfg.getInt("Input", "P1D.Type", 1);
    Controller_2_Type = cfg.getInt("Input", "P2.Type", 1);
    Controller_2B_Type = cfg.getInt("Input", "P2B.Type", 1);
    Controller_2C_Type = cfg.getInt("Input", "P2C.Type", 1);
    Controller_2D_Type = cfg.getInt("Input", "P2D.Type", 1);

    for (i = 0; i < 8; i++)
    {
        sprintf(buf, "%s.Up", PlayerNames[i]);
        input->m_keyMap[i].Up = cfg.getInt("Input", buf, keyDefault[i].Up);
        sprintf(buf, "%s.Down", PlayerNames[i]);
        input->m_keyMap[i].Down = cfg.getInt("Input", buf, keyDefault[i].Down);
        sprintf(buf, "%s.Left", PlayerNames[i]);
        input->m_keyMap[i].Left = cfg.getInt("Input", buf, keyDefault[i].Left);
        sprintf(buf, "%s.Right", PlayerNames[i]);
        input->m_keyMap[i].Right = cfg.getInt("Input", buf, keyDefault[i].Right);
        sprintf(buf, "%s.Start", PlayerNames[i]);
        input->m_keyMap[i].Start = cfg.getInt("Input", buf, keyDefault[i].Start);
        sprintf(buf, "%s.A", PlayerNames[i]);
        input->m_keyMap[i].A = cfg.getInt("Input", buf, keyDefault[i].A);
        sprintf(buf, "%s.B", PlayerNames[i]);
        input->m_keyMap[i].B = cfg.getInt("Input", buf, keyDefault[i].B);
        sprintf(buf, "%s.C", PlayerNames[i]);
        input->m_keyMap[i].C = cfg.getInt("Input", buf, keyDefault[i].C);
        sprintf(buf, "%s.Mode", PlayerNames[i]);
        input->m_keyMap[i].Mode = cfg.getInt("Input", buf, keyDefault[i].Mode);
        sprintf(buf, "%s.X", PlayerNames[i]);
        input->m_keyMap[i].X = cfg.getInt("Input", buf, keyDefault[i].X);
        sprintf(buf, "%s.Y", PlayerNames[i]);
        input->m_keyMap[i].Y = cfg.getInt("Input", buf, keyDefault[i].Y);
        sprintf(buf, "%s.Z", PlayerNames[i]);
        input->m_keyMap[i].Z = cfg.getInt("Input", buf, keyDefault[i].Z);
    }

    // Create the TeamPlayer I/O table.
    Make_IO_Table();

    // Done.
    return 1;
}
Example #5
0
/**
 * Regionize a func, so that each node and each arc in its TransCFG is
 * "covered".  A node is covered if any region contains it.  An arc T1->T2
 * is covered if either:
 *
 *   a) T1 and T2 are in the same region R and T2 immediately follows
 *      T1 in R.
 *   b) T2 is the head (first translation) of a region.
 *
 * Basic algorithm:
 *
 *   1) sort nodes in decreasing weight order
 *   2) for each node N:
 *      2.1) if N and all its incoming arcs are covered, then continue
 *      2.2) select a region starting at this node and mark nodes/arcs as
 *           covered appropriately
 */
void regionizeFunc(const Func*            func,
                   JIT::TranslatorX64* tx64,
                   RegionVec&             regions) {
  assert(RuntimeOption::EvalJitPGO);
  FuncId funcId = func->getFuncId();
  ProfData* profData = tx64->profData();
  TransCFG cfg(funcId, profData, tx64->getSrcDB(), tx64->getJmpToTransIDMap());

  if (Trace::moduleEnabled(HPHP::Trace::pgo, 5)) {
    string dotFileName = folly::to<string>("/tmp/func-cfg-", funcId, ".dot");
    cfg.print(dotFileName, funcId, profData, nullptr);
    FTRACE(5, "regionizeFunc: initial CFG for func {} saved to file {}\n",
           funcId, dotFileName);
  }

  TransCFG::ArcPtrVec arcs = cfg.arcs();
  vector<TransID>    nodes = cfg.nodes();

  std::sort(nodes.begin(), nodes.end(),
            [&](TransID tid1, TransID tid2) -> bool {
              if (cfg.weight(tid1) != cfg.weight(tid2)) {
                return cfg.weight(tid1) > cfg.weight(tid2);
              }
              // In case of ties, pick older translations first, in an
              // attempt to start loops at their headers.
              return tid1 < tid2;
            });

  TransCFG::ArcPtrSet coveredArcs;
  TransIDSet          coveredNodes;
  TransIDSet          heads;
  TransIDToRegionMap  headToRegion;
  RegionToTransIDsMap regionToTransIds;
  regions.clear();

  for (auto node : nodes) {
    if (!setContains(coveredNodes, node) ||
        !allArcsCovered(cfg.inArcs(node),  coveredArcs)) {
      TransID newHead = node;
      FTRACE(6, "regionizeFunc: selecting trace to cover node {}\n", newHead);
      TransIDSet selectedSet;
      TransIDVec selectedVec;
      RegionDescPtr region = selectHotTrace(newHead, profData, cfg,
                                            selectedSet, &selectedVec);
      profData->setOptimized(profData->transSrcKey(newHead));
      assert(selectedVec.size() > 0 && selectedVec[0] == newHead);
      regions.push_back(region);
      heads.insert(newHead);
      markCovered(cfg, selectedVec, heads, coveredNodes, coveredArcs);
      regionToTransIds[region] = selectedVec;
      headToRegion[newHead] = region;

      FTRACE(6, "regionizeFunc: selected trace: {}\n",
             folly::join(", ", selectedVec));
    }
  }

  assert(coveredNodes.size() == cfg.nodes().size());
  assert(coveredArcs.size() == arcs.size());

  sortRegion(regions, func, cfg, profData, headToRegion, regionToTransIds);

  if (debug && Trace::moduleEnabled(HPHP::Trace::pgo, 5)) {
    FTRACE(5, "\n--------------------------------------------\n"
           "regionizeFunc({}): computed regions:\n", funcId);
    for (auto region : regions) {
      FTRACE(5, "{}\n\n", show(*region));
    }
  }
}
Example #6
0
void KisSplashScreen::toggleShowAtStartup(bool toggle)
{
    KConfigGroup cfg( KSharedConfig::openConfig(), "SplashScreen");
    cfg.writeEntry("HideSplashAfterStartup", toggle);
}
Example #7
0
int main( int argc, char* argv[] ) {


    std::cout << std::endl << std::endl;
    std::cout << "------------------------------------------------------" << std::endl;
    std::cout << "|                                                    |" << std::endl;
    std::cout << "|                                                    |" << std::endl;
    std::cout << "|               Running runZGAnalysis                |" << std::endl;
    std::cout << "|                                                    |" << std::endl;
    std::cout << "|                                                    |" << std::endl;
    std::cout << "------------------------------------------------------" << std::endl;
    std::cout << std::endl << std::endl;




    if( argc<2 ) {
        std::cout << "USAGE: ./runZGAnalysis [configFileName] [data/MC]" << std::endl;
        std::cout << "Exiting." << std::endl;
        exit(11);
    }


    std::string configFileName(argv[1]);
    ZGConfig cfg(configFileName);



    bool onlyData = false;
    bool onlyMC   = false;
    bool onlySignal = false;
    bool noSignals = false;
    if( argc > 2 ) {

        std::string dataMC(argv[2]);
        if( dataMC=="data" ) onlyData = true;
        else if( dataMC=="MC" || dataMC=="mc" ) onlyMC = true;
        else if( dataMC=="mcbg" || dataMC=="mcBG" || dataMC=="MCBG" || dataMC=="mc_bg" || dataMC=="MC_BG" ) {
            onlyMC = true;
            noSignals = true;
        } else if( dataMC=="signal" ) onlySignal = true;
        else {
            std::cout << "-> You passed a second argument that isn't 'data', nor 'MC', nor 'signal', so I don't know what to do about it." << std::endl;
        }

    } else {

        std::cout << "-> Will run on both data and MC." << std::endl;

    }


    if( onlyMC ) {
        std::cout << "-> Will run only on MC." << std::endl;
        if( noSignals ) {
            std::cout << "-> Will skip signal." << std::endl;
        }
    }

    if( onlyData ) {
        std::cout << "-> Will run only on data." << std::endl;
    }


    std::string outputdir = cfg.getEventYieldDir();
    system(Form("mkdir -p %s", outputdir.c_str()));


    std::string outfileName(Form("%s/trees_tmp.root", outputdir.c_str()));

    TFile* outfile = TFile::Open(outfileName.c_str(), "update");
    outfile->cd();





    if( !onlyData && !onlySignal ) { // run on MC


        std::string samplesFileName = "../samples/samples_" + cfg.mcSamples() + ".dat";
        std::cout << std::endl << std::endl;
        std::cout << "-> Loading samples from file: " << samplesFileName << std::endl;


        std::vector<ZGSample> fSamples = ZGSample::loadSamples(samplesFileName);
        //std::vector<ZGSample> fSamples = ZGSample::loadSamples(samplesFileName, 100, 999);
        if( fSamples.size()==0 ) {
            std::cout << "There must be an error: samples is empty!" << std::endl;
            exit(120);
        }


        //addTreeToFile( outfile, "zg", fSamples, cfg);
        addTreeToFile( outfile, "zg", fSamples, cfg, 851, 852 );
        addTreeToFile( outfile, "dy", fSamples, cfg, 700, 710 );
        //addTreeToFile( outfile, "top", fSamples, cfg, 300, 499 ); // irrelevant


        std::cout << "-> Done looping on MC samples." << std::endl;


    } // if MC samples



    // load signal samples, if any
    if( cfg.mcSamples()!="" && cfg.additionalStuff()!="noSignals" && !noSignals && !onlyData ) {

        std::string samplesFileName = "../samples/samples_" + cfg.mcSamples() + ".dat";
        std::cout << std::endl << std::endl;
        std::cout << "-> Loading signal samples from file: " << samplesFileName << std::endl;

        std::vector<ZGSample> fSamples = ZGSample::loadSamples(samplesFileName, 1000); // only signal (id>=1000)


        if( fSamples.size()==0 ) {

            std::cout << "No signal samples found, skipping." << std::endl;

        } else {

            for( unsigned i=0; i<fSamples.size(); ++i )
                addTreeToFile( outfile, fSamples[i], cfg );

        } // if samples != 0

    } // if mc samples



    if( !(cfg.dummyAnalysis()) && cfg.dataSamples()!="" && !onlyMC  && !onlySignal ) {


        std::string samplesFile_data = "../samples/samples_" + cfg.dataSamples() + ".dat";

        std::cout << std::endl << std::endl;
        std::cout << "-> Loading data from file: " << samplesFile_data << std::endl;

        std::vector<ZGSample> samples_data = ZGSample::loadSamples(samplesFile_data);
        if( samples_data.size()==0 ) {
            std::cout << "There must be an error: samples_data is empty!" << std::endl;
            exit(1209);
        }


        addTreeToFile( outfile, "data" , samples_data, cfg );

        std::cout << "-> Done looping on data." << std::endl;

    }


    outfile->Close();

    std::string finalFileName = outputdir + "/trees.root";
    system( Form("cp %s %s", outfileName.c_str(), finalFileName.c_str()) );

    std::cout << "-> Wrote trees to file: " << finalFileName << std::endl;



    return 0;

}
Example #8
0
void Parachute::Refresh()
{
  if (Game::GetInstance()->GetRemainingTime() <= 0)
    return;
  if (Game::GetInstance()->ReadState() != Game::PLAYING)
    return;

  Character& active = ActiveCharacter();
  Double speed = active.GetSpeedXY().Norm();

  if (active.FootsInVacuum() && speed.IsNotZero()) { // We are falling
    if (!open && (speed > GameMode::GetInstance()->safe_fall)) { // with a sufficient speed
      if (EnoughAmmo() && !m_used_this_turn) { // We have enough ammo => start opening the parachute
        if (!m_used_this_turn) {
          UseAmmo();
          m_used_this_turn = true;
        }

        active.SetAirResistFactor(cfg().air_resist_factor);
        active.SetWindFactor(cfg().wind_factor);
        open = true;
        img->animation.SetPlayBackward(false);
        img->Start();
        active.SetSpeedXY(Point2d(0,0));
        active.SetMovement("parachute");
        Camera::GetInstance()->FollowObject(&active);
      }
    }
  } else { // We are on the ground
    if (open) { // The parachute is opened
      active.SetMovement("walk");
      if (!closing) { // We have just hit the ground. Start closing animation
        img->animation.SetPlayBackward(true);
        img->animation.SetShowOnFinish(SpriteAnimation::show_blank);
        img->Start();
        closing = true;
        return;
      } else { // The parachute is closing
        if (img->IsFinished()) {
          // The animation is finished... We are done with the parachute
          open = false;
          closing = false;
          UseAmmoUnit();
        }
      }
    }
    m_used_this_turn = false;
  }
  if (open) {
    active.UpdateLastMovingTime();

    // If parachute is open => character can move a little to the left or to the right
    const LRMoveIntention * lr_move_intention = active.GetLastLRMoveIntention();
    if (lr_move_intention) {
      LRDirection direction = lr_move_intention->GetDirection();
      active.SetDirection(direction);
      if (direction == DIRECTION_LEFT)
        active.SetExternForce(-cfg().force_side_displacement, 0.0);
      else
        active.SetExternForce(cfg().force_side_displacement, 0.0);
    }
  }
}
Example #9
0
 arith_util & autil() { return cfg().m_autil; }
Example #10
0
ChatOptionsTab::ChatOptionsTab(wxWindow* parent)
    : wxPanel(parent, -1)
{
	GetAui().manager->AddPane(this, wxLEFT, _T( "chatoptionstab" ));

	wxBoxSizer* m_main_sizer = new wxBoxSizer(wxVERTICAL);

	wxStaticBoxSizer* sbColorsSizer;
	sbColorsSizer = new wxStaticBoxSizer(new wxStaticBox(this, -1, _("Colors and font")), wxHORIZONTAL);

	wxBoxSizer* bColorsVSizer;
	bColorsVSizer = new wxBoxSizer(wxVERTICAL);

	m_custom_colors = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxTAB_TRAVERSAL);
	m_custom_colors->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_MENU));

	wxBoxSizer* bCustomColorsSizer;
	bCustomColorsSizer = new wxBoxSizer(wxHORIZONTAL);

	wxBoxSizer* bColorSizer;
	bColorSizer = new wxBoxSizer(wxHORIZONTAL);

	wxBoxSizer* bColorsSizer1;
	bColorsSizer1 = new wxBoxSizer(wxVERTICAL);

	wxBoxSizer* bNormlColorSizer;
	bNormlColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_normal_color = new ColorButton(m_custom_colors, ID_NORMAL, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_normal_color->SetColor(wxColour(0, 0, 0));

	bNormlColorSizer->Add(m_normal_color, 0, wxALL, 5);

	m_normal_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Normal"), wxDefaultPosition, wxDefaultSize, 0);
	m_normal_label->Wrap(-1);
	bNormlColorSizer->Add(m_normal_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorsSizer1->Add(bNormlColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bBGColorSizer;
	bBGColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_bg_color = new ColorButton(m_custom_colors, ID_BG, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_bg_color->SetColor(wxColour(255, 255, 255));

	bBGColorSizer->Add(m_bg_color, 0, wxALL, 5);

	m_bg_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Background"), wxDefaultPosition, wxDefaultSize, 0);
	m_bg_label->Wrap(-1);
	bBGColorSizer->Add(m_bg_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorsSizer1->Add(bBGColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bActionColorSizer;
	bActionColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_action_color = new ColorButton(m_custom_colors, ID_ACTION, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_action_color->SetColor(wxColour(255, 0, 249));

	bActionColorSizer->Add(m_action_color, 0, wxALL, 5);

	m_action_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Action"), wxDefaultPosition, wxDefaultSize, 0);
	m_action_label->Wrap(-1);
	bActionColorSizer->Add(m_action_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorsSizer1->Add(bActionColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bHighlightColorSizer;
	bHighlightColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_highlight_color = new ColorButton(m_custom_colors, ID_HIGHLIGHT, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_highlight_color->SetColor(wxColour(255, 0, 44));

	bHighlightColorSizer->Add(m_highlight_color, 0, wxALL, 5);

	m_highlight_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Highlight"), wxDefaultPosition, wxDefaultSize, 0);
	m_highlight_label->Wrap(-1);
	bHighlightColorSizer->Add(m_highlight_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorsSizer1->Add(bHighlightColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bJoinLeaveColorSizer;
	bJoinLeaveColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_joinleave_color = new ColorButton(m_custom_colors, ID_JOINLEAVE, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_joinleave_color->SetColor(wxColour(24, 255, 0));

	bJoinLeaveColorSizer->Add(m_joinleave_color, 0, wxALL, 5);

	m_joinleave_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Join/Leave"), wxDefaultPosition, wxDefaultSize, 0);
	m_joinleave_label->Wrap(-1);
	bJoinLeaveColorSizer->Add(m_joinleave_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorsSizer1->Add(bJoinLeaveColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bMyColorSizer;
	bMyColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_my_color = new ColorButton(m_custom_colors, ID_MYMESS, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_my_color->SetColor(wxColour(160, 160, 160));

	bMyColorSizer->Add(m_my_color, 0, wxALL, 5);

	m_my_label = new wxStaticText(m_custom_colors, wxID_ANY, _("My messages"), wxDefaultPosition, wxDefaultSize, 0);
	m_my_label->Wrap(-1);
	bMyColorSizer->Add(m_my_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorsSizer1->Add(bMyColorSizer, 1, wxEXPAND, 5);

	bColorSizer->Add(bColorsSizer1, 1, wxEXPAND, 5);

	wxBoxSizer* bColorSizer2;
	bColorSizer2 = new wxBoxSizer(wxVERTICAL);

	wxBoxSizer* bServerColorSizer;
	bServerColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_server_color = new ColorButton(m_custom_colors, ID_SERVER, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_server_color->SetColor(wxColour(255, 189, 0));

	bServerColorSizer->Add(m_server_color, 0, wxALL, 5);

	m_server_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Server"), wxDefaultPosition, wxDefaultSize, 0);
	m_server_label->Wrap(-1);
	bServerColorSizer->Add(m_server_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorSizer2->Add(bServerColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bClientolorSizer;
	bClientolorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_client_color = new ColorButton(m_custom_colors, ID_CLIENT, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_client_color->SetColor(wxColour(255, 189, 0));

	bClientolorSizer->Add(m_client_color, 0, wxALL, 5);

	m_client_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Client"), wxDefaultPosition, wxDefaultSize, 0);
	m_client_label->Wrap(-1);
	bClientolorSizer->Add(m_client_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorSizer2->Add(bClientolorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bErrorColorSizer;
	bErrorColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_error_color = new ColorButton(m_custom_colors, ID_ERROR, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_error_color->SetColor(wxColour(255, 0, 0));

	bErrorColorSizer->Add(m_error_color, 0, wxALL, 5);

	m_error_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Error"), wxDefaultPosition, wxDefaultSize, 0);
	m_error_label->Wrap(-1);
	bErrorColorSizer->Add(m_error_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorSizer2->Add(bErrorColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bTSColorSizer;
	bTSColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_ts_color = new ColorButton(m_custom_colors, ID_TIMESTAMP, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_ts_color->SetColor(wxColour(160, 160, 160));

	bTSColorSizer->Add(m_ts_color, 0, wxALL, 5);

	m_ts_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Timestamp"), wxDefaultPosition, wxDefaultSize, 0);
	m_ts_label->Wrap(-1);
	bTSColorSizer->Add(m_ts_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorSizer2->Add(bTSColorSizer, 0, wxEXPAND, 5);

	wxBoxSizer* bNoteColorSizer;
	bNoteColorSizer = new wxBoxSizer(wxHORIZONTAL);

	m_note_color = new ColorButton(m_custom_colors, ID_NOTIFICATION, wxBitmap(), wxDefaultPosition, wxSize(20, 20), 0);
	m_note_color->SetColor(wxColour(255, 191, 0));

	bNoteColorSizer->Add(m_note_color, 0, wxALL, 5);

	m_note_label = new wxStaticText(m_custom_colors, wxID_ANY, _("Notification"), wxDefaultPosition, wxDefaultSize, 0);
	m_note_label->Wrap(-1);
	bNoteColorSizer->Add(m_note_label, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);

	bColorSizer2->Add(bNoteColorSizer, 0, wxEXPAND, 5);

	bColorSizer->Add(bColorSizer2, 1, wxEXPAND, 5);

	bCustomColorsSizer->Add(bColorSizer, 1, wxEXPAND, 5);

	m_test_text = new wxTextCtrl(m_custom_colors, wxID_ANY, _("[19:35] ** Server ** Connected to Server.\n[22:30] <Dude> hi everyone\n[22:30] ** Dude2 joined the channel.\n[22:30] * Dude2 thinks his colors looks nice\n[22:45] <Dude> Dude2: orl?\n[22:46] <Dude2> But could be better, should tweak them some more...\n"), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH);
	bCustomColorsSizer->Add(m_test_text, 1, wxALL | wxEXPAND, 5);

	m_custom_colors->SetSizer(bCustomColorsSizer);
	m_custom_colors->Layout();
	bCustomColorsSizer->Fit(m_custom_colors);
	bColorsVSizer->Add(m_custom_colors, 1, wxEXPAND | wxALL, 0);

	wxBoxSizer* bFontNameSizer;
	bFontNameSizer = new wxBoxSizer(wxHORIZONTAL);

	m_font_label = new wxStaticText(this, wxID_ANY, _("Font:"), wxDefaultPosition, wxDefaultSize, 0);
	m_font_label->Wrap(-1);
	bFontNameSizer->Add(m_font_label, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5);

	m_fontname = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);
	m_fontname->Wrap(-1);
	bFontNameSizer->Add(m_fontname, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5);

	m_select_font = new wxButton(this, ID_SELFONT, _("Select..."), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
	bFontNameSizer->Add(m_select_font, 0, wxALL, 5);

	bColorsVSizer->Add(bFontNameSizer, 0, wxEXPAND, 5);

	sbColorsSizer->Add(bColorsVSizer, 1, wxEXPAND, 5);

	m_main_sizer->Add(sbColorsSizer, 0, wxEXPAND | wxBOTTOM | wxRIGHT | wxLEFT | wxTOP, 5);


	wxStaticBoxSizer* sbBehaviorSizer;
	sbBehaviorSizer = new wxStaticBoxSizer(new wxStaticBox(this, -1, _("Behavior")), wxHORIZONTAL);

	m_irc_colors = new wxCheckBox(this, wxID_ANY, _("Enable Irc colors in chat messages"), wxDefaultPosition, wxDefaultSize, 0);
	m_irc_colors->SetValue(sett().GetUseIrcColors());

	sbBehaviorSizer->Add(m_irc_colors, 0, wxALL, 5);
#ifndef DISABLE_SOUND
	m_play_sounds = new wxCheckBox(this, ID_PLAY_SOUNDS, _("Play notification sounds"), wxDefaultPosition, wxDefaultSize, 0);
	m_play_sounds->SetValue(sett().GetChatPMSoundNotificationEnabled());
	sbBehaviorSizer->Add(m_play_sounds, 0, wxALL, 5);
#endif

	m_broadcast_check = new wxCheckBox(this, wxID_ANY, _("Copy server messages in current channel"), wxDefaultPosition, wxDefaultSize, 0);
	m_broadcast_check->SetValue(cfg().ReadBool(_T("/Chat/BroadcastEverywhere")));
	sbBehaviorSizer->Add(m_broadcast_check, 0, wxALL, 5);

	m_main_sizer->Add(sbBehaviorSizer, 0, wxEXPAND | wxBOTTOM | wxRIGHT | wxLEFT, 5);

	wxBoxSizer* bBotomSizer;
	bBotomSizer = new wxBoxSizer(wxHORIZONTAL);

	wxStaticBoxSizer* sbChatLogSizer;
	wxStaticBox* sbChatLog = new wxStaticBox(this, -1, _("Chat logs"));
	sbChatLogSizer = new wxStaticBoxSizer(sbChatLog, wxVERTICAL);

	m_save_logs = new wxCheckBox(this, wxID_ANY, _("Save chat logs"), wxDefaultPosition, wxDefaultSize, 0);

	m_save_logs->SetValue(cfg().ReadBool(_T("/ChatLog/chatlog_enable")));

	sbChatLogSizer->Add(m_save_logs, 0, wxALL, 5);

	wxBoxSizer* m_num_lines_sizer = new wxBoxSizer(wxHORIZONTAL);
	m_num_lines = new wxSpinCtrl(this, wxID_ANY);
	m_num_lines_lbl = new wxStaticText(this, wxID_ANY, _("approx. number of lines loaded from log into chat"), wxDefaultPosition, wxDefaultSize, 0);
	m_num_lines_sizer->Add(m_num_lines);
	m_num_lines_sizer->Add(m_num_lines_lbl, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, 5);
	sbChatLogSizer->Add(m_num_lines_sizer, 0, wxALL, 5);

	bBotomSizer->Add(sbChatLogSizer, 1, wxEXPAND | wxRIGHT, 5);

	wxStaticBoxSizer* sbHighlightSizer;
	sbHighlightSizer = new wxStaticBoxSizer(new wxStaticBox(this, -1, _("Highlight words")), wxVERTICAL);

	m_hilight_words_label = new wxStaticText(this, wxID_ANY, _("Words to highlight in chat:"), wxDefaultPosition, wxDefaultSize, 0);
	m_hilight_words_label->Wrap(-1);

	sbHighlightSizer->Add(m_hilight_words_label, 0, wxALL, 5);


	sbHighlightSizer->Add(0, 0, 1, wxEXPAND, 5);

	m_highlight_words = new wxTextCtrl(this, ID_HIWORDS, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);
	m_highlight_words->SetToolTip(_("enter a ; seperated list"));

	sbHighlightSizer->Add(m_highlight_words, 0, wxALL | wxEXPAND, 5);

	m_highlight_req = new wxCheckBox(this, ID_HL_REQ, _("Additionally play sound/flash titlebar "), wxDefaultPosition, wxDefaultSize, 0);
	sbHighlightSizer->Add(m_highlight_req, 0, wxALL | wxEXPAND, 5);

	bBotomSizer->Add(sbHighlightSizer, 1, wxEXPAND, 5);

	m_main_sizer->Add(bBotomSizer, 0, wxEXPAND | wxBOTTOM | wxRIGHT | wxLEFT, 5);

	m_main_sizer->Add(0, 0, 1, wxEXPAND | wxALL, 5);

	SetSizer(m_main_sizer);
	DoRestore();
	UpdateTextSample();
	UpdateFontLabel();
	Layout();
}
Example #11
0
MYExchange::MYExchange(struct my_xchg_cfg& _cfg)
{
    MYExConfigData cfg(_cfg);
    void* fn;
    CreateTradeTunnelFuncType create_trd_tunnel;
    MYExchangeLogUtil::Start("my_exchange_fut_op", 0);
    m_tnl_hdl = NULL;

    // 构建通道
    cur_tunnel_index_ = 0;
    max_tunnel_index_ = 0;
    pp_tunnel_ = new MYTunnelInterface*[2];
    pp_tunnel_[1] = NULL;
    while (max_tunnel_index_ < 1)
    {
        void* hdl;
        /* dlopen */
        hdl = dlopen(_cfg.tunnel_so_path, RTLD_NOW);
        if (NULL == hdl)
        {
            fprintf(stderr, "Failed to dlopen %s, %s \n", _cfg.tunnel_so_path, dlerror());
            break;
        }

        m_tnl_hdl = hdl;

        fn = dlsym(hdl, "CreateTradeTunnel");
        if (NULL == fn)
        {
            fprintf(stderr, "Failed to dlsym CreateTradeTunnel: %s \n", dlerror());
            break;
        }

        create_trd_tunnel = CreateTradeTunnelFuncType(fn);
        pp_tunnel_[max_tunnel_index_] = create_trd_tunnel(_cfg.tunnel_cfg_path);
        if (NULL == pp_tunnel_[max_tunnel_index_])
        {
            fprintf(stderr, "Failed to create_trd_tunnel by config : %s\n", _cfg.tunnel_cfg_path);
            break;
        }

        /* dlsym, get address of CreateTradeTunnel */
        //pp_tunnel_[max_tunnel_index_] = CreateTradeTunnel(cfg.tunnel_cfg_path);
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler((OrderRespondHandler) std::bind(&MYExchange::OrderRespond, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler((CancelRespondHandler) std::bind(&MYExchange::CancelRespond, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler((OrderReturnHandler) std::bind(&MYExchange::OrderReturn, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler((TradeReturnHandler) std::bind(&MYExchange::TradeReturn, this, std::placeholders::_1));

        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (PositionReturnHandler) std::bind(&MYExchange::SendPositionReturn, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (OrderDetailReturnHandler) std::bind(&MYExchange::SendOrderDetailReturn, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (TradeDetailReturnHandler) std::bind(&MYExchange::SendTradeDetailReturn, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (ContractInfoReturnHandler) std::bind(&MYExchange::SendContractReturn, this, std::placeholders::_1));

        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (RspOfReqForQuoteHandler) std::bind(&MYExchange::ReqForQuoteRespond, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler((RtnForQuoteHandler) std::bind(&MYExchange::ForQuoteRtn, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (CancelQuoteRspHandler) std::bind(&MYExchange::CancelQuoteRespond, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (InsertQuoteRspHandler) std::bind(&MYExchange::InsertQuoteRespond, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler((QuoteReturnHandler) std::bind(&MYExchange::QuoteReturn, this, std::placeholders::_1));
        pp_tunnel_[max_tunnel_index_]->SetCallbackHandler(
            (QuoteTradeReturnHandler) std::bind(&MYExchange::QuoteTradeReturn, this, std::placeholders::_1));
        ++max_tunnel_index_;
    }

    // 构造数据管理对象
    p_order_manager_ = new MYOrderDataManager();
    p_position_manager_ = new MYPositionDataManager();
    p_order_req_ = new MYOrderReq(this, p_order_manager_, p_position_manager_, cfg);
    p_order_rsp_ = new MYOrderRsp(this, p_order_manager_, p_position_manager_, p_order_req_);

    // 接口无需暴露的内部实现,隐藏在实现类中,避免接口的修改
    my_exchange_inner_imp_ = new MYExchangeInnerImp(pp_tunnel_[0], cfg, max_tunnel_index_);
    my_exchange_inner_imp_->qry_pos_flag = false;
    my_exchange_inner_imp_->qry_order_flag = false;
    my_exchange_inner_imp_->qry_trade_flag = false;
    my_exchange_inner_imp_->qry_contract_flag = false;

    if (max_tunnel_index_ > 0)
    {
        investorid = pp_tunnel_[0]->GetClientID();
    }

	// TODO: wangying modify here to support saving each strategy's position respectively
    // init model position by ev file of model
    if (cfg.Position_policy().InitPosByEvfile())
    {
        my_exchange_inner_imp_->InitModelPosByEvFile();
    }

    // 读取历史仓位数据,init仓位数据
    if (max_tunnel_index_ > 0 && cfg.Position_policy().init_pos_at_start)
    {
        std::thread t_qry_pos(&MYExchangeInnerImp::QryPosForInit, my_exchange_inner_imp_);
        t_qry_pos.detach();
    }
}
Example #12
0
static bool readConfig(const char *file, Options *opts, Options *def)
#endif
{
#ifdef __cplusplus
    if(file.isEmpty())
    {
        const char *xdg=xdgConfigFolder();

        if(xdg)
        {
            QString filename(xdg);

            filename+="/"QTC_FILE;
            return readConfig(filename, opts, def);
        }
    }
#else
    if(!file)
    {
        const char *xdg=xdgConfigFolder();

        if(xdg)
        {
            char filename[QTC_MAX_FILENAME_LEN];

            sprintf(filename, "%s/"QTC_FILE, xdg);
            return readConfig(filename, opts, def);
        }
    }
#endif
    else
    {
#ifdef __cplusplus
        QtCConfig cfg(file);

        if(cfg.ok())
        {
#else
        GHashTable *cfg=loadConfig(file);

        if(cfg)
        {
#endif
            QTC_CFG_READ_ROUND(round)
            QTC_CFG_READ_DI(highlightFactor)
            QTC_CFG_READ_TB_BORDER(toolbarBorders)
            QTC_CFG_READ_APPEARANCE(appearance, def->appearance)
            QTC_CFG_READ_BOOL(fixParentlessDialogs)
            QTC_CFG_READ_BOOL(stripedProgress)
            QTC_CFG_READ_BOOL(animatedProgress)
            QTC_CFG_READ_BOOL(lighterPopupMenuBgnd)
            QTC_CFG_READ_BOOL(embolden)
            QTC_CFG_READ_DEF_BTN(defBtnIndicator)
            QTC_CFG_READ_LINE(sliderThumbs)
            QTC_CFG_READ_LINE(handles)
            QTC_CFG_READ_BOOL(highlightTab)
            QTC_CFG_READ_SHADE(shadeSliders, false)
            QTC_CFG_READ_SHADE(shadeMenubars, true)
            QTC_CFG_READ_SHADE(shadeCheckRadio, false)
            QTC_CFG_READ_APPEARANCE(menubarAppearance, def->menubarAppearance)
            QTC_CFG_READ_APPEARANCE(menuitemAppearance, opts->appearance)
            QTC_CFG_READ_APPEARANCE(toolbarAppearance, def->toolbarAppearance)
            QTC_CFG_READ_LINE(toolbarSeparators)
            QTC_CFG_READ_LINE(splitters)
            QTC_CFG_READ_BOOL(customMenuTextColor)
            QTC_CFG_READ_MOUSE_OVER(coloredMouseOver)
            QTC_CFG_READ_BOOL(menubarMouseOver)
            QTC_CFG_READ_BOOL(shadeMenubarOnlyWhenActive)
            QTC_CFG_READ_BOOL(thinnerMenuItems)
            QTC_CFG_READ_COLOR(customSlidersColor)
            QTC_CFG_READ_COLOR(customMenubarsColor)
            QTC_CFG_READ_COLOR(customMenuSelTextColor)
            QTC_CFG_READ_COLOR(customMenuNormTextColor)
            QTC_CFG_READ_COLOR(customCheckRadioColor)
            QTC_CFG_READ_SCROLLBAR(scrollbarType)
            QTC_CFG_READ_BOOL(shadowButtons)
            QTC_CFG_READ_APPEARANCE(lvAppearance, opts->appearance)
            QTC_CFG_READ_APPEARANCE(tabAppearance, opts->appearance)
            QTC_CFG_READ_APPEARANCE(sliderAppearance, opts->appearance)
            QTC_CFG_READ_APPEARANCE(progressAppearance, opts->appearance)
#ifndef QTC_PLAIN_FOCUS_ONLY
            QTC_CFG_READ_BOOL(stdFocus)
#endif
            QTC_CFG_READ_BOOL(lvLines)
            QTC_CFG_READ_BOOL(drawStatusBarFrames)
            QTC_CFG_READ_BOOL(fillSlider)
            QTC_CFG_READ_BOOL(roundMbTopOnly)
            QTC_CFG_READ_BOOL(borderMenuitems)
            QTC_CFG_READ_BOOL(gradientPbGroove)
            QTC_CFG_READ_BOOL(darkerBorders)
            QTC_CFG_READ_BOOL(vArrows)
            QTC_CFG_READ_BOOL(colorMenubarMouseOver)
#ifdef __cplusplus
            QTC_CFG_READ_BOOL(stdSidebarButtons)
            QTC_CFG_READ_BOOL(gtkScrollViews);
            QTC_CFG_READ_BOOL(gtkComboMenus);
#endif

#ifndef QTC_COMMON_ONLY_COVERTERS
            QTC_CFG_READ_SHADING(shading, SHADING_HSL);
#endif

#ifndef __cplusplus
            releaseConfig(cfg);
#endif
            if(SHADE_SELECTED==opts->shadeCheckRadio)
                opts->shadeCheckRadio=SHADE_BLEND_SELECTED;

            checkColor(&opts->shadeMenubars, &opts->customMenubarsColor);
            checkColor(&opts->shadeSliders, &opts->customSlidersColor);
            checkColor(&opts->shadeCheckRadio, &opts->customCheckRadioColor);

            if(APPEARANCE_BEVELLED==opts->toolbarAppearance)
                opts->toolbarAppearance=APPEARANCE_GRADIENT;
            else if(APPEARANCE_RAISED==opts->toolbarAppearance)
                opts->toolbarAppearance=APPEARANCE_FLAT;

            if(APPEARANCE_BEVELLED==opts->menubarAppearance)
                opts->menubarAppearance=APPEARANCE_GRADIENT;
            else if(APPEARANCE_RAISED==opts->menubarAppearance)
                opts->menubarAppearance=APPEARANCE_FLAT;

            if(APPEARANCE_BEVELLED==opts->sliderAppearance)
                opts->sliderAppearance=APPEARANCE_GRADIENT;

            if(APPEARANCE_BEVELLED==opts->tabAppearance)
                opts->tabAppearance=APPEARANCE_GRADIENT;

            if(opts->highlightFactor<((100.0+MIN_HIGHLIGHT_FACTOR)/100.0) ||
               opts->highlightFactor>((100.0+MAX_HIGHLIGHT_FACTOR)/100.0))
                opts->highlightFactor=DEFAULT_HIGHLIGHT_FACTOR;

            if(opts->animatedProgress && !opts->stripedProgress)
                opts->animatedProgress=false;

            if(SHADE_CUSTOM==opts->shadeMenubars || SHADE_BLEND_SELECTED==opts->shadeMenubars || !opts->borderMenuitems)
                opts->colorMenubarMouseOver=true;

            return true;
        }
    }

    return false;
}

static bool fileExists(const char *path)
{
    struct stat info;

    return 0==lstat(path, &info) && (info.st_mode&S_IFMT)==S_IFREG;
}

static const char * getSystemConfigFile()
{
    static const char * constFiles[]={ "/etc/qt4/"QTC_FILE, "/etc/qt3/"QTC_FILE, "/etc/qt/"QTC_FILE, NULL };

    int i;

    for(i=0; constFiles[i]; ++i)
        if(fileExists(constFiles[i]))
            return constFiles[i];
    return NULL;
}

static void defaultSettings(Options *opts)
{
    /* Set hard-coded defaults... */
    opts->contrast=7;
    opts->highlightFactor=DEFAULT_HIGHLIGHT_FACTOR;
    opts->round=ROUND_FULL;
    opts->lighterPopupMenuBgnd=true;
    opts->animatedProgress=true;
    opts->stripedProgress=true;
    opts->highlightTab=true;
    opts->embolden=false;
    opts->appearance=APPEARANCE_DULL_GLASS;
    opts->lvAppearance=APPEARANCE_BEVELLED;
    opts->tabAppearance=APPEARANCE_GRADIENT;
    opts->sliderAppearance=APPEARANCE_DULL_GLASS;
    opts->menubarAppearance=APPEARANCE_GRADIENT;
    opts->menuitemAppearance=APPEARANCE_DULL_GLASS;
    opts->toolbarAppearance=APPEARANCE_GRADIENT;
    opts->progressAppearance=APPEARANCE_DULL_GLASS;
    opts->defBtnIndicator=IND_COLORED;
    opts->sliderThumbs=LINE_DOTS;
    opts->handles=LINE_DOTS;
    opts->shadeSliders=SHADE_BLEND_SELECTED;
    opts->shadeMenubars=SHADE_DARKEN;
    opts->shadeCheckRadio=SHADE_NONE;
    opts->toolbarBorders=TB_NONE;
    opts->toolbarSeparators=LINE_DOTS;
    opts->splitters=LINE_DOTS;
    opts->fixParentlessDialogs=false;
    opts->customMenuTextColor=false;
    opts->coloredMouseOver=MO_PLASTIK;
    opts->menubarMouseOver=true;
    opts->shadeMenubarOnlyWhenActive=true;
    opts->thinnerMenuItems=false;
    opts->scrollbarType=SCROLLBAR_KDE;
    opts->shadowButtons=true;
#ifndef QTC_PLAIN_FOCUS_ONLY
    opts->stdFocus=true;
#endif
    opts->lvLines=false;
    opts->drawStatusBarFrames=false;
    opts->fillSlider=true;
    opts->roundMbTopOnly=true;
    opts->borderMenuitems=true;
    opts->gradientPbGroove=true;
    opts->darkerBorders=false;
    opts->vArrows=false;
    opts->colorMenubarMouseOver=false;
#ifdef __cplusplus
    opts->stdSidebarButtons=false;
    opts->gtkScrollViews=false;
    opts->gtkComboMenus=false;
    opts->customMenubarsColor.setRgb(0, 0, 0);
    opts->customSlidersColor.setRgb(0, 0, 0);
    opts->customMenuNormTextColor.setRgb(0, 0, 0);
    opts->customMenuSelTextColor.setRgb(0, 0, 0);
    opts->customCheckRadioColor.setRgb(0, 0, 0);
#else
    opts->customMenubarsColor.red=opts->customMenubarsColor.green=opts->customMenubarsColor.blue=0;
    opts->customSlidersColor.red=opts->customSlidersColor.green=opts->customSlidersColor.blue=0;
    opts->customMenuNormTextColor.red=opts->customMenuNormTextColor.green=opts->customMenuNormTextColor.blue=0;
    opts->customMenuSelTextColor.red=opts->customMenuSelTextColor.green=opts->customMenuSelTextColor.blue=0;
    opts->customCheckRadioColor.red=opts->customCheckRadioColor.green=opts->customCheckRadioColor.blue=0;
#endif

    /* Read system config file... */
    {
    static const char * systemFilename=NULL;

    if(!systemFilename)
        systemFilename=getSystemConfigFile();

    if(systemFilename)
        readConfig(systemFilename, opts, opts);
    }
}
void VTerrainDecorationEntityModel::RecreateIRShaders(VisSurface_cl* pSurface, VShaderEffectLib* pEffectLib)
{
  if (pSurface == NULL)
    return;

  // check for supported transparency types
  if (pSurface->GetTransparencyType() != VIS_TRANSP_NONE &&
      pSurface->GetTransparencyType() != VIS_TRANSP_ALPHATEST &&
      pSurface->GetTransparencyType() != VIS_TRANSP_ALPHA)
    return;

  char szParam[1024];
  VTechniqueConfig baseCfg("INSTANCING;WIND", NULL);

//   if (Vision::Renderer.GetCurrentRendererNode() != NULL && Vision::Renderer.GetRendererNode()->GetMultisampleMode() != VVIDEO_MULTISAMPLE_OFF)
//     baseCfg.AddInclusionTag("MSAA");

  switch (pSurface->GetGeometryTopology())
  {
    case VisSurface_cl::VGT_3DMesh:
      baseCfg.AddInclusionTag("GEO_3D");
      break;

    default:
      Vision::Error.Warning("VTerrainDecorationEntityModel::RecreateIRShaders: Only 3DMesh geometry topology is supported");
      return;
  }

  hkvVec4 vWindPhaseParams(0.0071f, 0.0092f, 0.0f, 0.0f);
  const hkvAlignedBBox& bbox = m_spMesh->GetBoundingBox();
  if (bbox.isValid())
    vWindPhaseParams.w = -bbox.m_vMin.z;

  {
    // 1. Assign G-Pass pass technique
    ////////////////////////////////////
    szParam[0] = '\0';

    // Get params needed for IR shader creation from IR renderer
    char* pszParamPos = GetParamStringForIRSurface(pSurface, szParam);
    pszParamPos += sprintf(pszParamPos, "WindPhaseParams=%g,%g,%g,%g;", vWindPhaseParams.x, vWindPhaseParams.y, vWindPhaseParams.z, vWindPhaseParams.w);

    VTechniqueConfig cfg(baseCfg);

    bool bHasMaterialTex = pSurface->GetAuxiliaryTextureCount() >= 1 && pSurface->GetAuxiliaryTexture(0) != NULL;
    bool bHasHotSpotTex = pSurface->GetAuxiliaryTextureCount() >= 2 && pSurface->GetAuxiliaryTexture(1) != NULL;

    if (bHasMaterialTex)
    {
      // --- Thermal params are taken from auxiliary texture
      cfg.AddInclusionTag("AUX_TEX");
    }
    else
    {
      int iMaterialID = 0;
      if (pSurface->GetMesh() != NULL)
        iMaterialID = (int)pSurface->GetMesh()->GetBaseSubmesh(0)->GetGeometryInfo().m_sUserFlags;
      
      // --- Thermal params are taken from submesh user flags
      pszParamPos += sprintf(pszParamPos, "ThermalMaterialID=%i;", iMaterialID);
    }

    if (bHasHotSpotTex)
      cfg.AddInclusionTag("HEATING_POWER");

    VCompiledEffect* pFX = Vision::Shaders.CreateEffect("InitialPass", szParam, EFFECTCREATEFLAG_NONE, pEffectLib);
    if (pFX == NULL)
    {
      Vision::Error.Warning("VTerrainDecorationEntityModel::RecreateIRShaders: Failed to create InitialPass effect");
      return;
    }
  
    VCompiledTechnique* pTechnique = pFX->FindCompatibleTechnique(&cfg);
    if (pTechnique == NULL)
    {
      Vision::Error.Warning("VTerrainDecorationEntityModel::RecreateIRShaders: No compatible technique found; using default technique");
      pTechnique = pFX->GetDefaultTechnique(); // find default technique
    }

    VASSERT(pTechnique != NULL && pTechnique->GetShaderCount() == 1);
    pTechnique->GetShader(0)->m_bModified = true;

    m_spInstancingTechIRMainPass = pTechnique;
  }

  {
    // 2. Assign Pre-Pass pass technique
    /////////////////////////////////////
    szParam[0] = '\0';
    char* pszParamPos = szParam;
    pszParamPos += sprintf(pszParamPos, "WindPhaseParams=%g,%g,%g,%g;", vWindPhaseParams.x, vWindPhaseParams.y, vWindPhaseParams.z, vWindPhaseParams.w);

    VTechniqueConfig cfg(baseCfg);

    if (pSurface->GetTransparencyType() == VIS_TRANSP_ALPHATEST || pSurface->GetTransparencyType() == VIS_TRANSP_ALPHA)
    {
      cfg.AddInclusionTag("ALPHATEST");
      pszParamPos += sprintf(pszParamPos, "AlphaTestThreshold=%g;", pSurface->GetAlphaTestThreshold());
    }

    VCompiledEffect* pFX = Vision::Shaders.CreateEffect("PrePass", szParam, EFFECTCREATEFLAG_NONE, pEffectLib);
    if (pFX == NULL)
    {
      Vision::Error.Warning("VTerrainDecorationEntityModel::RecreateIRShaders: Failed to create PrePass effect");
      return;
    }

    VCompiledTechnique* pTechnique = pFX->FindCompatibleTechnique(&cfg);
    if (pTechnique == NULL)
    {
      Vision::Error.Warning("VTerrainDecorationEntityModel::RecreateIRShaders: No compatible technique found; using default technique");
      pTechnique = pFX->GetDefaultTechnique(); // find default technique
    }

    VASSERT(pTechnique != NULL && pTechnique->GetShaderCount() == 1);
    pTechnique->GetShader(0)->m_bModified = true;

    m_spInstancingTechIRPrePass = pTechnique;
  }
}
bool AggressiveDCEPass::AggressiveDCE(Function* func) {
  // Mark function parameters as live.
  AddToWorklist(&func->DefInst());
  func->ForEachParam(
      [this](const Instruction* param) {
        AddToWorklist(const_cast<Instruction*>(param));
      },
      false);

  // Compute map from block to controlling conditional branch
  std::list<BasicBlock*> structuredOrder;
  cfg()->ComputeStructuredOrder(func, &*func->begin(), &structuredOrder);
  ComputeBlock2HeaderMaps(structuredOrder);
  bool modified = false;
  // Add instructions with external side effects to worklist. Also add branches
  // EXCEPT those immediately contained in an "if" selection construct or a loop
  // or continue construct.
  // TODO(greg-lunarg): Handle Frexp, Modf more optimally
  call_in_func_ = false;
  func_is_entry_point_ = false;
  private_stores_.clear();
  // Stacks to keep track of when we are inside an if- or loop-construct.
  // When immediately inside an if- or loop-construct, we do not initially
  // mark branches live. All other branches must be marked live.
  std::stack<bool> assume_branches_live;
  std::stack<uint32_t> currentMergeBlockId;
  // Push sentinel values on stack for when outside of any control flow.
  assume_branches_live.push(true);
  currentMergeBlockId.push(0);
  for (auto bi = structuredOrder.begin(); bi != structuredOrder.end(); ++bi) {
    // If exiting if or loop, update stacks
    if ((*bi)->id() == currentMergeBlockId.top()) {
      assume_branches_live.pop();
      currentMergeBlockId.pop();
    }
    for (auto ii = (*bi)->begin(); ii != (*bi)->end(); ++ii) {
      SpvOp op = ii->opcode();
      switch (op) {
        case SpvOpStore: {
          uint32_t varId;
          (void)GetPtr(&*ii, &varId);
          // Mark stores as live if their variable is not function scope
          // and is not private scope. Remember private stores for possible
          // later inclusion.  We cannot call IsLocalVar at this point because
          // private_like_local_ has not been set yet.
          if (IsVarOfStorage(varId, SpvStorageClassPrivate) ||
              IsVarOfStorage(varId, SpvStorageClassWorkgroup))
            private_stores_.push_back(&*ii);
          else if (!IsVarOfStorage(varId, SpvStorageClassFunction))
            AddToWorklist(&*ii);
        } break;
        case SpvOpCopyMemory:
        case SpvOpCopyMemorySized: {
          uint32_t varId;
          (void)GetPtr(ii->GetSingleWordInOperand(kCopyMemoryTargetAddrInIdx),
                       &varId);
          if (IsVarOfStorage(varId, SpvStorageClassPrivate) ||
              IsVarOfStorage(varId, SpvStorageClassWorkgroup))
            private_stores_.push_back(&*ii);
          else if (!IsVarOfStorage(varId, SpvStorageClassFunction))
            AddToWorklist(&*ii);
        } break;
        case SpvOpLoopMerge: {
          assume_branches_live.push(false);
          currentMergeBlockId.push(
              ii->GetSingleWordInOperand(kLoopMergeMergeBlockIdInIdx));
        } break;
        case SpvOpSelectionMerge: {
          assume_branches_live.push(false);
          currentMergeBlockId.push(
              ii->GetSingleWordInOperand(kSelectionMergeMergeBlockIdInIdx));
        } break;
        case SpvOpSwitch:
        case SpvOpBranch:
        case SpvOpBranchConditional:
        case SpvOpUnreachable: {
          if (assume_branches_live.top()) {
            AddToWorklist(&*ii);
          }
        } break;
        default: {
          // Function calls, atomics, function params, function returns, etc.
          // TODO(greg-lunarg): function calls live only if write to non-local
          if (!ii->IsOpcodeSafeToDelete()) {
            AddToWorklist(&*ii);
          }
          // Remember function calls
          if (op == SpvOpFunctionCall) call_in_func_ = true;
        } break;
      }
    }
  }
  // See if current function is an entry point
  for (auto& ei : get_module()->entry_points()) {
    if (ei.GetSingleWordInOperand(kEntryPointFunctionIdInIdx) ==
        func->result_id()) {
      func_is_entry_point_ = true;
      break;
    }
  }
  // If the current function is an entry point and has no function calls,
  // we can optimize private variables as locals
  private_like_local_ = func_is_entry_point_ && !call_in_func_;
  // If privates are not like local, add their stores to worklist
  if (!private_like_local_)
    for (auto& ps : private_stores_) AddToWorklist(ps);
  // Perform closure on live instruction set.
  while (!worklist_.empty()) {
    Instruction* liveInst = worklist_.front();
    // Add all operand instructions if not already live
    liveInst->ForEachInId([&liveInst, this](const uint32_t* iid) {
      Instruction* inInst = get_def_use_mgr()->GetDef(*iid);
      // Do not add label if an operand of a branch. This is not needed
      // as part of live code discovery and can create false live code,
      // for example, the branch to a header of a loop.
      if (inInst->opcode() == SpvOpLabel && liveInst->IsBranch()) return;
      AddToWorklist(inInst);
    });
    if (liveInst->type_id() != 0) {
      AddToWorklist(get_def_use_mgr()->GetDef(liveInst->type_id()));
    }
    // If in a structured if or loop construct, add the controlling
    // conditional branch and its merge.
    BasicBlock* blk = context()->get_instr_block(liveInst);
    Instruction* branchInst = block2headerBranch_[blk];
    if (branchInst != nullptr) {
      AddToWorklist(branchInst);
      Instruction* mergeInst = branch2merge_[branchInst];
      AddToWorklist(mergeInst);
    }
    // If the block is a header, add the next outermost controlling
    // conditional branch and its merge.
    Instruction* nextBranchInst = header2nextHeaderBranch_[blk];
    if (nextBranchInst != nullptr) {
      AddToWorklist(nextBranchInst);
      Instruction* mergeInst = branch2merge_[nextBranchInst];
      AddToWorklist(mergeInst);
    }
    // If local load, add all variable's stores if variable not already live
    if (liveInst->opcode() == SpvOpLoad || liveInst->IsAtomicWithLoad()) {
      uint32_t varId;
      (void)GetPtr(liveInst, &varId);
      if (varId != 0) {
        ProcessLoad(varId);
      }
      // Process memory copies like loads
    } else if (liveInst->opcode() == SpvOpCopyMemory ||
               liveInst->opcode() == SpvOpCopyMemorySized) {
      uint32_t varId;
      (void)GetPtr(liveInst->GetSingleWordInOperand(kCopyMemorySourceAddrInIdx),
                   &varId);
      if (varId != 0) {
        ProcessLoad(varId);
      }
      // If merge, add other branches that are part of its control structure
    } else if (liveInst->opcode() == SpvOpLoopMerge ||
               liveInst->opcode() == SpvOpSelectionMerge) {
      AddBreaksAndContinuesToWorklist(liveInst);
      // If function call, treat as if it loads from all pointer arguments
    } else if (liveInst->opcode() == SpvOpFunctionCall) {
      liveInst->ForEachInId([this](const uint32_t* iid) {
        // Skip non-ptr args
        if (!IsPtr(*iid)) return;
        uint32_t varId;
        (void)GetPtr(*iid, &varId);
        ProcessLoad(varId);
      });
      // If function parameter, treat as if it's result id is loaded from
    } else if (liveInst->opcode() == SpvOpFunctionParameter) {
      ProcessLoad(liveInst->result_id());
      // We treat an OpImageTexelPointer as a load of the pointer, and
      // that value is manipulated to get the result.
    } else if (liveInst->opcode() == SpvOpImageTexelPointer) {
      uint32_t varId;
      (void)GetPtr(liveInst, &varId);
      if (varId != 0) {
        ProcessLoad(varId);
      }
    }
    worklist_.pop();
  }

  // Kill dead instructions and remember dead blocks
  for (auto bi = structuredOrder.begin(); bi != structuredOrder.end();) {
    uint32_t mergeBlockId = 0;
    (*bi)->ForEachInst([this, &modified, &mergeBlockId](Instruction* inst) {
      if (!IsDead(inst)) return;
      if (inst->opcode() == SpvOpLabel) return;
      // If dead instruction is selection merge, remember merge block
      // for new branch at end of block
      if (inst->opcode() == SpvOpSelectionMerge ||
          inst->opcode() == SpvOpLoopMerge)
        mergeBlockId = inst->GetSingleWordInOperand(0);
      to_kill_.push_back(inst);
      modified = true;
    });
    // If a structured if or loop was deleted, add a branch to its merge
    // block, and traverse to the merge block and continue processing there.
    // We know the block still exists because the label is not deleted.
    if (mergeBlockId != 0) {
      AddBranch(mergeBlockId, *bi);
      for (++bi; (*bi)->id() != mergeBlockId; ++bi) {
      }

      auto merge_terminator = (*bi)->terminator();
      if (merge_terminator->opcode() == SpvOpUnreachable) {
        // The merge was unreachable. This is undefined behaviour so just
        // return (or return an undef). Then mark the new return as live.
        auto func_ret_type_inst = get_def_use_mgr()->GetDef(func->type_id());
        if (func_ret_type_inst->opcode() == SpvOpTypeVoid) {
          merge_terminator->SetOpcode(SpvOpReturn);
        } else {
          // Find an undef for the return value and make sure it gets kept by
          // the pass.
          auto undef_id = Type2Undef(func->type_id());
          auto undef = get_def_use_mgr()->GetDef(undef_id);
          live_insts_.Set(undef->unique_id());
          merge_terminator->SetOpcode(SpvOpReturnValue);
          merge_terminator->SetInOperands({{SPV_OPERAND_TYPE_ID, {undef_id}}});
          get_def_use_mgr()->AnalyzeInstUse(merge_terminator);
        }
        live_insts_.Set(merge_terminator->unique_id());
      }
    } else {
      ++bi;
    }
  }

  return modified;
}
Example #15
0
SSAOScene::SSAOScene(Context * ctx):
CameraScene(ctx),
cryModel("assets/models/nanosuit/nanosuit.obj")
{
   FramebufferConfiguration cfg(ctx->getWindowWidth(),ctx->getWindowHeight());
   TextureConfig posBfrConfig("positionDepth",GL_RGBA16F,GL_RGBA,GL_FLOAT);
   posBfrConfig.setTextureFilter(GL_NEAREST);
   posBfrConfig.setWrapMode(GL_CLAMP_TO_EDGE);
   TextureAttachment posBfr(posBfrConfig,GL_COLOR_ATTACHMENT0);

   TextureConfig norBfrConfig("normal",GL_RGB16F,GL_RGB,GL_FLOAT);
   posBfrConfig.setTextureFilter(GL_NEAREST);
   TextureAttachment norBfr(norBfrConfig,GL_COLOR_ATTACHMENT1);

   TextureConfig spec_albedoConfig("color",GL_RGBA,GL_RGBA,GL_FLOAT);
   posBfrConfig.setTextureFilter(GL_NEAREST);


   TextureAttachment spec_albedoBfr(spec_albedoConfig,GL_COLOR_ATTACHMENT2);

   cfg.addTexturebuffer(posBfr);
   cfg.addTexturebuffer(norBfr);
   cfg.addTexturebuffer(spec_albedoBfr);
   cfg.addRenderbuffer(RenderbufferAttachment(GL_DEPTH24_STENCIL8,GL_DEPTH_STENCIL_ATTACHMENT));
   gBuffer.init(cfg);


   FramebufferConfiguration aoConfig(ctx->getWindowWidth(),ctx->getWindowHeight());
   TextureConfig aoTexture("occlusion",GL_RED,GL_RGB,GL_FLOAT);
   aoTexture.setTextureFilter(GL_NEAREST);
   TextureAttachment ssaoBufferAttachment(aoTexture,GL_COLOR_ATTACHMENT0);
   aoConfig.addTexturebuffer(ssaoBufferAttachment);
   ssaoBuffer.init(aoConfig);
   GL_Logger::LogError("Could not configure ssaoBuffer");

   //Blur buffer has same properties as ao buffer.
   FramebufferConfiguration blurConfiguration(ctx->getWindowWidth(),ctx->getWindowHeight());
   TextureConfig blurTexture("occlusion",GL_RED,GL_RGB,GL_FLOAT);
   blurTexture.setTextureFilter(GL_NEAREST);
   TextureAttachment blurBufferAttachment(blurTexture,GL_COLOR_ATTACHMENT0);
   blurConfiguration.addTexturebuffer(blurBufferAttachment);
   ssaoBlurBuffer.init(blurConfiguration);

   std::uniform_real_distribution<GLfloat> randomFloats(0.0, 1.0); // random floats between 0.0 - 1.0
   std::default_random_engine generator;
   //Set up a noise texture
   std::vector<glm::vec3> ssaoNoiseVec;
   for (GLuint i = 0; i < 16; i++)
   {
       glm::vec3 noise(
           randomFloats(generator) * 2.0 - 1.0,
           randomFloats(generator) * 2.0 - 1.0,
           0.0f);
       ssaoNoiseVec.push_back(noise);
   }

   TextureConfig ssaoConfig("ssaoNoise",GL_RGB16F,GL_RGB,GL_FLOAT);
   ssaoConfig.setWrapMode(GL_REPEAT);
   ssaoConfig.setTextureFilter(GL_NEAREST);
   ssaoNoise.init(ssaoConfig,&ssaoNoiseVec[0],4,4);
   GL_Logger::LogError("Could not configure ssaoNoise");

   deferredGBufferProg = createProgram("SSAO GBuffer fill program");
   ssaoProgram = createProgram("SSAO creation program");
   
   postProcessProg = createProgram("Display AO map program");
   ssaoBlurProgram = createProgram("SSAO blur program");
   finalPassProgram = createProgram("Final Pass Program");

   geomPlane.transform.setScale(glm::vec3(20.0));
   geomPlane.transform.setPosition(glm::vec3(0,-1,0));

   cryModel.transform.setScale(glm::vec3(0.5));
   cryModel.transform.setPosition(glm::vec3(0,0,3.5));
   cryModel.transform.rotate(-M_PI/2, glm::vec3(1.0,0,0));


}
Example #16
0
void LnkProperties::done(int ok)
{
    if ( ok ) {
	bool changed=FALSE;
	bool reloadMime=FALSE;

	if ( lnk->name() != d->docname->text() ) {
	    lnk->setName(d->docname->text());
	    changed=TRUE;
	}
	if ( d->categoryEdit->isVisible() ) {
	    QArray<int> tmp = d->categoryEdit->newCategories();
	    if ( lnk->categories() != tmp ) {
		lnk->setCategories( tmp );
		changed = TRUE;
	    }
	}
	if ( !d->rotate->isHidden()) {
	    QString newrot;

	    if ( d->rotate->isChecked() ) {
		int rot=0;
		for(; rot<4; rot++) {
		    if (d->rotateButtons->find(rot)->isOn())
		        break;
		}
		newrot = QString::number((rot*90)%360);
	    }
	    if ( newrot != lnk->rotation() ) {
		lnk-> setRotation(newrot);
		changed = TRUE;
		reloadMime = TRUE;
	    }
	}
    if ( d->arguments->text() != lnk->property( "Arguments" ) ) {
        lnk->setProperty( "Arguments", d->arguments->text() );
        changed = TRUE;
    }
	if ( d->preload->isHidden() && d->locationCombo->currentItem() != currentLocation ) {
	    moveLnk();
	} else if ( changed ) {
	    lnk->writeLink();
	}

	if ( !d->preload->isHidden() ) {
	    Config cfg("Launcher");
	    cfg.setGroup("Preload");
	    QStringList apps = cfg.readListEntry("Apps",',');
	    QString exe = lnk->exec();
	    if ( apps.contains(exe) != d->preload->isChecked() ) {
		if ( d->preload->isChecked() ) {
		    apps.append(exe);
#ifndef QT_NO_COP
		    QCopEnvelope e("QPE/Application/"+exe.local8Bit(),
				   "enablePreload()");
#endif
		} else {
		    apps.remove(exe);
#ifndef QT_NO_COP
		    QCopEnvelope e("QPE/Application/"+exe.local8Bit(),
				   "quitIfInvisible()");
#endif
		}
		cfg.writeEntry("Apps",apps,',');
	    }
	}
	if ( reloadMime )
	    MimeType::updateApplications ( );
    }
    QDialog::done( ok );
}
bool CLangData::ReadTranslation(PCTSTR pszFile, bool bUpdateTranslation, bool bIgnoreVersion)
{
	try
	{
		if(!bUpdateTranslation)
			Clear();

		// load data from file
		icpf::config cfg(icpf::config::eIni);
		const uint_t uiLangName = cfg.register_string(_T("Info/Lang Name"), _t(""));
		const uint_t uiFontFace = cfg.register_string(_T("Info/Font Face"), _T(""));
		const uint_t uiSize = cfg.register_signed_num(_T("Info/Size"), 0, 0, 0xffff);
		const uint_t uiRTL = cfg.register_bool(_T("Info/RTL reading order"), false);
		const uint_t uiHelpName = cfg.register_string(_T("Info/Help name"), _T(""));
		const uint_t uiAuthor = cfg.register_string(_T("Info/Author"), _T(""));
		const uint_t uiVersion = cfg.register_string(_T("Info/Format version"), _T("1"));

		cfg.read(pszFile);

		// we don't support old language versions unless requested specifically
		if(!bIgnoreVersion)
		{
			const tchar_t* pszVersion = cfg.get_string(uiVersion);
			if(_tcscmp(pszVersion, TRANSLATION_FORMAT_VERSION) != 0)
				return false;
		}

		const tchar_t* psz = cfg.get_string(uiLangName);
		if(!psz || psz[0] == _t('\0'))
			return false;
		SetLangName(psz);

		psz = cfg.get_string(uiFontFace);
		if(!psz || psz[0] == _t('\0'))
			return false;
		SetFontFace(psz);

		ll_t ll = cfg.get_signed_num(uiSize);
		if(ll == 0)
			return false;
		SetPointSize((WORD)ll);

		SetDirection(cfg.get_bool(uiRTL));

		psz = cfg.get_string(uiHelpName);
		if(!psz || psz[0] == _t('\0'))
			return false;
		SetHelpName(psz);

		psz = cfg.get_string(uiAuthor);
		if(!psz || psz[0] == _t('\0'))
			return false;
		SetAuthor(psz);

		m_bUpdating = bUpdateTranslation;
		m_uiSectionID = 0;
		if(!cfg.enum_properties(_t("*"), EnumAttributesCallback, this))
		{
			m_bUpdating = false;
			return false;
		}
		m_bUpdating = false;

		SetFilename(pszFile);

		m_bModified = false;

		return true;
	}
	catch(...)
	{
		return false;
	}
}
Example #18
0
LnkProperties::LnkProperties( AppLnk* l, QWidget* parent )
    : QDialog( parent, 0, TRUE ), lnk(l), fileSize( 0 )
{
    setCaption( tr("Properties") );

    QVBoxLayout *vbox = new QVBoxLayout( this );
    d = new LnkPropertiesBase( this );
    vbox->add( d );

    // hide custom rotation feature for now, need a new implementation to fit quicklauch,
    // is confusing for the user and doubtable useful since life rotation
    d->rotate->hide();
    d->rotateButtons->hide();

    d->docname->setText(l->name());
    QString inf;
    if ( l->type().isEmpty() ) {
	d->type->hide();
	d->typeLabel->hide();
    } else {
	d->type->setText( l->type() );
    }

    if ( l->comment().isEmpty() ) {
	d->comment->hide();
	d->commentLabel->hide();
    } else {
	d->comment->setText( l->comment() );
    }

    connect(d->beam,SIGNAL(clicked()),this,SLOT(beamLnk()));
    if ( lnk->type().contains('/') ) { // A document? (#### better predicate needed)
	connect(d->unlink,SIGNAL(clicked()),this,SLOT(unlinkLnk()));
	connect(d->duplicate,SIGNAL(clicked()),this,SLOT(duplicateLnk()));

	d->docname->setReadOnly( FALSE );
	d->preload->hide();
	d->rotate->hide();
	d->rotateButtons->hide();
	d->labelspacer->hide();

	// ### THIS MUST GO, FIX WIERD BUG in QLAYOUT
	d->categoryEdit->kludge();

	d->categoryEdit->setCategories( lnk->categories(),
					"Document View",
					tr("Document View") );
	setupLocations();
    } else {
	d->unlink->hide();
	d->duplicate->hide();
	d->beam->hide();
	d->hline->hide();
 	d->locationLabel->hide();
	d->locationCombo->hide();

	// Can't edit categories, since the app .desktop files are global,
	// possibly read-only.
 	d->categoryEdit->hide();

	d->docname->setReadOnly( TRUE );

	if ( l->property("CanFastload") == "0" )
	    d->preload->hide();
	if ( !l->property("Rotation"). isEmpty ()) {
	    d->rotate->setChecked ( true );
            //don't use rotate buttons for now (see comment above)
	    //d->rotateButtons->setButton((l->rotation().toInt()%360)/90);
	}
	else {
	    d->rotateButtons->setEnabled(false);
	}

        if ( !l->property( "Arguments" ).isEmpty() )
            d->arguments->setText( l->property( "Arguments" ) );

	Config cfg("Launcher");
	cfg.setGroup("Preload");
	QStringList apps = cfg.readListEntry("Apps",',');
	d->preload->setChecked( apps.contains(l->exec()) );
	if ( Global::isBuiltinCommand(lnk->exec()) )
	    d->preload->hide(); // builtins are always fast

	currentLocation = 0; // apps not movable (yet)
    }
}
Example #19
0
KisSplashScreen::KisSplashScreen(const QString &version, const QPixmap &pixmap, bool themed, QWidget *parent, Qt::WindowFlags f)
    : QWidget(parent, Qt::SplashScreen | Qt::FramelessWindowHint | f)
{
    setupUi(this);
    setWindowIcon(KisIconUtils::loadIcon("calligrakrita"));

    QString color = "#FFFFFF";
    if (themed && qApp->palette().background().color().value() >100) {
        color = "#000000";
    }


    lblSplash->setPixmap(pixmap);
    bnClose->hide();
    connect(bnClose, SIGNAL(clicked()), this, SLOT(close()));
    chkShowAtStartup->hide();
    connect(chkShowAtStartup, SIGNAL(toggled(bool)), this, SLOT(toggleShowAtStartup(bool)));

    KConfigGroup cfg( KSharedConfig::openConfig(), "SplashScreen");
    bool hideSplash = cfg.readEntry("HideSplashAfterStartup", false);
    chkShowAtStartup->setChecked(hideSplash);

    lblLinks->setTextFormat(Qt::RichText);
    lblLinks->setText(i18n("<html>"
                           "<head/>"
                           "<body>"
                           "<p align=\"center\"><span style=\" color:%1;\"><b>Links</b></span></p>"

                           "<p><a href=\"https://krita.org/support-us/donations/\"><span style=\" text-decoration: underline; color:%1;\">Support Krita</span></a></p>"

                           "<p><a href=\"http://krita.org/resources\"><span style=\" text-decoration: underline; color:%1;\">Getting Started</span></a></p>"
                           "<p><a href=\"http://userbase.kde.org/Krita/Manual\"><span style=\" text-decoration: underline; color:%1;\">Manual</span></a></p>"
                           "<p><a href=\"http://krita.org\"><span style=\" text-decoration: underline; color:%1;\">Krita Website</span></a></p>"
                           "<p><a href=\"http://forum.kde.org/viewforum.php?f=136\"><span style=\" text-decoration: underline; color:%1;\">User Community</span></a></p>"

                           "<p><a href=\"https://projects.kde.org/projects/calligra\"><span style=\" text-decoration: underline; color:%1;\">Source Code</span></a></p>"

                           "<p><a href=\"http://store.steampowered.com/app/280680/\"><span style=\" text-decoration: underline; color:%1;\">Krita on Steam</span></a></p>"
                           "</body>"
                           "</html>").arg(color));

    lblVersion->setText(i18n("Version: %1", version));
    lblVersion->setStyleSheet("color:" + color);

    KConfigGroup cfg2( KSharedConfig::openConfig(), "RecentFiles");
    int i = 1;

    QString recent = i18n("<html>"
                          "<head/>"
                          "<body>"
                          "<p align=\"center\"><b><span style=\" color:%1;\">Recent Files</span></b></p>").arg(color);

    QString path;
    QStringList recentfiles;

    do {
        path = cfg2.readPathEntry(QString("File%1").arg(i), QString());
        if (!path.isEmpty()) {
            QString name = cfg2.readPathEntry(QString("Name%1").arg(i), QString());
            QUrl url(path);
            if (name.isEmpty())
                name = url.fileName();

            if (!url.isLocalFile() || QFile::exists(url.toLocalFile())) {
                recentfiles.insert(0, QString("<p><a href=\"%1\"><span style=\"color:%3;\">%2</span></a></p>").arg(path).arg(name).arg(color));
            }
        }

        i++;
    } while (!path.isEmpty() || i <= 8);

    recent += recentfiles.join("\n");
    recent += "</body>"
            "</html>";
    lblRecent->setText(recent);
    connect(lblRecent, SIGNAL(linkActivated(QString)), SLOT(linkClicked(QString)));
}
Example #20
0
//common config
void MainWindow::readConfig(KSharedConfigPtr config)
{
    KConfigGroup cfg(config, "General Options");

    m_recentFiles->loadEntries(config->group("Recent Files"));
}
Example #21
0
/**
 * save(): Save Gens configuration.
 * @param filename Configuration filename.
 */
int Config::save(const string& filename)
{
    int i;
    char buf[256];

#ifdef GENS_OS_WIN32
    SetCurrentDirectory(PathNames.Gens_EXE_Path);
#endif /* GENS_OS_WIN32 */

    // Load the configuration file into the INI handler.
    INI cfg(filename);

    // Paths
    cfg.writeString("General", "ROM Path", Rom_Dir);
    cfg.writeString("General", "Save Path", State_Dir);
    cfg.writeString("General", "SRAM Path", SRAM_Dir);
    cfg.writeString("General", "BRAM Path", BRAM_Dir);
    cfg.writeString("General", "Dump Path", PathNames.Dump_WAV_Dir);
    cfg.writeString("General", "Dump GYM Path", PathNames.Dump_GYM_Dir);
    cfg.writeString("General", "Screen Shot Path", PathNames.Screenshot_Dir);
    cfg.writeString("General", "Patch Path", Patch_Dir);
    cfg.writeString("General", "IPS Patch Path", IPS_Dir);

    // Genesis BIOS
    cfg.writeString("General", "Genesis BIOS", BIOS_Filenames.MD_TMSS);

    // SegaCD BIOSes
    cfg.writeString("General", "USA CD BIOS", BIOS_Filenames.SegaCD_US);
    cfg.writeString("General", "Europe CD BIOS", BIOS_Filenames.MegaCD_EU);
    cfg.writeString("General", "Japan CD BIOS", BIOS_Filenames.MegaCD_JP);

    // 32X BIOSes
    cfg.writeString("General", "32X 68000 BIOS", BIOS_Filenames._32X_MC68000);
    cfg.writeString("General", "32X Master SH2 BIOS", BIOS_Filenames._32X_MSH2);
    cfg.writeString("General", "32X Slave SH2 BIOS", BIOS_Filenames._32X_SSH2);

    // Last 9 ROMs
    for (i = 0; i < 9; i++)
    {
        sprintf(buf, "ROM %d", i + 1);
        cfg.writeString("General", buf, Recent_Rom[i]);
    }

#ifdef GENS_CDROM
    // Physical CD-ROM support for SegaCD
#if defined(GENS_OS_WIN32)
    // Win32 ASPI uses a device ID number.
    cfg.writeInt("Options", "CD Drive", cdromDeviceID);
#elif defined(GENS_OS_UNIX)
    // Unix uses a device name.
    cfg.writeString("General", "CD Drive", cdromDeviceName);
#endif /* GENS_OS_WIN32 / GENS_OS_UNIX */
    cfg.writeInt("General", "CD Speed", cdromSpeed);
#endif /* GENS_CDROM */

    cfg.writeInt("General", "State Number", Current_State);
    cfg.writeInt("General", "Language", Language);
    cfg.writeInt("General", "Window X", Window_Pos.x);
    cfg.writeInt("General", "Window Y", Window_Pos.y);
    cfg.writeInt("General", "Intro Style", Intro_Style);
    cfg.writeInt("General", "Free Mode Color", draw->introEffectColor());

    // Video adjustments
    cfg.writeInt("Graphics", "Contrast", Contrast_Level);
    cfg.writeInt("Graphics", "Brightness", Brightness_Level);
    cfg.writeInt("Graphics", "Greyscale", Greyscale & 1);
    cfg.writeInt("Graphics", "Invert", Invert_Color & 1);

    // Video settings
    // Render_Mode is incremented by 1 for compatibility with old Gens.
    cfg.writeBool("Graphics", "Full Screen", draw->fullScreen());
    cfg.writeString("Graphics", "Render Fullscreen", PluginMgr::getPluginFromID_Render(Video.Render_FS)->tag);
    cfg.writeString("Graphics", "Render Windowed", PluginMgr::getPluginFromID_Render(Video.Render_W)->tag);
    cfg.writeInt("Graphics", "Full Screen VSync", Video.VSync_FS & 1);
    cfg.writeInt("Graphics", "Windows VSync", Video.VSync_W & 1);
    cfg.writeBool("Graphics", "Border Color Emulation", Video.borderColorEmulation);
    cfg.writeBool("Graphics", "Pause Tint", Video.pauseTint);

#ifndef GENS_OS_WIN32
    cfg.writeInt("Graphics", "Bits Per Pixel", bppOut);
#endif /* GENS_OS_WIN32 */

#ifdef GENS_OPENGL
    cfg.writeInt("Graphics", "Render OpenGL", (Video.OpenGL ? 1 : 0));
    cfg.writeInt("Graphics", "OpenGL Width", Video.Width_GL);
    cfg.writeInt("Graphics", "OpenGL Height", Video.Height_GL);
    cfg.writeInt("Graphics", "OpenGL Filter", Video.glLinearFilter);
#endif /* GENS_OPENGL */

    cfg.writeInt("Graphics", "Stretch", Options::stretch());
#ifdef GENS_OS_WIN32
    cfg.writeBool("Graphics", "Software Blit", Options::swRender());
#endif /* GENS_OS_WIN32 */
    cfg.writeInt("Graphics", "Sprite Limit", Sprite_Over & 1);
    cfg.writeInt("Graphics", "Frame Skip", Frame_Skip);

    // Sound settings
    cfg.writeBool("Sound", "State", audio->enabled());
    cfg.writeInt("Sound", "Rate", audio->soundRate());
    cfg.writeBool("Sound", "Stereo", audio->stereo());

    cfg.writeInt("Sound", "Z80 State", Z80_State & 1);
    cfg.writeInt("Sound", "YM2612 State", YM2612_Enable & 1);
    cfg.writeInt("Sound", "PSG State", PSG_Enable & 1);
    cfg.writeInt("Sound", "DAC State", DAC_Enable & 1);
    cfg.writeInt("Sound", "PCM State", PCM_Enable & 1);
    cfg.writeInt("Sound", "PWM State", PWM_Enable & 1);
    cfg.writeInt("Sound", "CDDA State", CDDA_Enable & 1);

    // Improved sound options
    cfg.writeInt("Sound", "YM2612 Improvement", YM2612_Improv & 1);
    cfg.writeInt("Sound", "DAC Improvement", DAC_Improv & 1);
    cfg.writeInt("Sound", "PSG Improvement", PSG_Improv & 1);

    // Country codes
    cfg.writeInt("CPU", "Country", Country);
    cfg.writeInt("CPU", "Prefered Country 1", Country_Order[0]);
    cfg.writeInt("CPU", "Prefered Country 2", Country_Order[1]);
    cfg.writeInt("CPU", "Prefered Country 3", Country_Order[2]);

    // CPU options

    cfg.writeInt("CPU", "Perfect synchro between main and sub CPU (Sega CD)", SegaCD_Accurate);

    cfg.writeInt("CPU", "Main SH2 Speed", MSH2_Speed);
    cfg.writeInt("CPU", "Slave SH2 Speed", SSH2_Speed);

    // Various settings
    cfg.writeBool("Options", "Fast Blur", draw->fastBlur());
    cfg.writeBool("Options", "FPS", draw->fpsEnabled());
    cfg.writeInt("Options", "FPS Style", draw->fpsStyle());
    cfg.writeBool("Options", "Message", draw->msgEnabled());
    cfg.writeInt("Options", "Message Style", draw->msgStyle());
    cfg.writeInt("Options", "LED", Show_LED & 1);
    cfg.writeInt("Options", "Auto Fix Checksum", Auto_Fix_CS & 1);
    cfg.writeInt("Options", "Auto Pause", Auto_Pause & 1);

    // SegaCD BRAM cartridge
    if (BRAM_Ex_State & 0x100)
        cfg.writeInt("Options", "RAM Cart Size", BRAM_Ex_Size);
    else
        cfg.writeInt("Options", "RAM Cart Size", -1);

    // Miscellaneous files
    cfg.writeString("Options", "7z Binary", Misc_Filenames._7z_Binary);
    cfg.writeString("Options", "RAR Binary", Misc_Filenames.RAR_Binary);

    // Controller settings
    cfg.writeInt("Input", "P1.Type", Controller_1_Type & 0x13);
    cfg.writeInt("Input", "P1B.Type", Controller_2B_Type & 0x13);
    cfg.writeInt("Input", "P1C.Type", Controller_2C_Type & 0x13);
    cfg.writeInt("Input", "P1D.Type", Controller_2D_Type & 0x13);
    cfg.writeInt("Input", "P2.Type", Controller_2_Type & 0x13);
    cfg.writeInt("Input", "P2B.Type", Controller_2B_Type & 0x13);
    cfg.writeInt("Input", "P2C.Type", Controller_2C_Type & 0x13);
    cfg.writeInt("Input", "P2D.Type", Controller_2D_Type & 0x13);

    char tmpKey[16];
    for (i = 0; i < 8; i++)
    {
        sprintf(tmpKey, "%s.Up", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Up, true, 4);
        sprintf(tmpKey, "%s.Down", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Down, true, 4);
        sprintf(tmpKey, "%s.Left", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Left, true, 4);
        sprintf(tmpKey, "%s.Right", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Right, true, 4);
        sprintf(tmpKey, "%s.Start", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Start, true, 4);
        sprintf(tmpKey, "%s.A", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].A, true, 4);
        sprintf(tmpKey, "%s.B", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].B, true, 4);
        sprintf(tmpKey, "%s.C", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].C, true, 4);
        sprintf(tmpKey, "%s.Mode", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Mode, true, 4);
        sprintf(tmpKey, "%s.X", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].X, true, 4);
        sprintf(tmpKey, "%s.Y", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Y, true, 4);
        sprintf(tmpKey, "%s.Z", PlayerNames[i]);
        cfg.writeInt("Input", tmpKey, input->m_keyMap[i].Z, true, 4);
    }

    // Save the INI file.
    cfg.save(filename);

    // Done.
    return 1;
}
void ElogEntryI::saveSettings() {
  KstELOGAttribStruct	attrib;
  KConfig cfg("kstrc", false, false);
  QButton* button;
  QString str;
  unsigned int i;
  int j;

  _strAttributes.truncate( 0 );
  for( i=0; i<_attribs.count(); i++ ) {
    attrib = _attribs[i];

    switch( attrib.type ) {
      case AttribTypeText:
      str.sprintf( "%s=%s\n", attrib.attribName.latin1(), ((QLineEdit*)(attrib.pWidget))->text().latin1() );
      _strAttributes += str;
      break;

      case AttribTypeBool:
      if( ((QCheckBox*)(attrib.pWidget))->isChecked() ) {
        str.sprintf( "%s=1\n", attrib.attribName.latin1() );
        _strAttributes += str;
      }
      break;

      case AttribTypeCombo:
        str.sprintf( "%s=%s\n", attrib.attribName.latin1(), ((QComboBox*)(attrib.pWidget))->currentText().latin1() );
        _strAttributes += str;
      break;

      case AttribTypeRadio:
      button = ((QHButtonGroup*)(attrib.pWidget))->selected( );
      if( button != NULL ) {
        str.sprintf( "%s=%s\n", attrib.attribName.latin1(), button->text( ).latin1() );
        _strAttributes += str;
      }
      break;

      case AttribTypeCheck:
      for( j=0; j<((QHButtonGroup*)(attrib.pWidget))->count(); j++ ) {
        button = ((QHButtonGroup*)(attrib.pWidget))->find( j );
        if( button != NULL ) {
          if( ((QRadioButton*)button)->isChecked() ) {
            str.sprintf( "%s#%d=%s\n", attrib.attribName.latin1(), j, button->text( ).latin1() );
            _strAttributes += str;
          }
        }
      }
      break;
    }
  }

  _strText = textEditText->text();
  _bIncludeCapture = checkBoxIncludeCapture->isChecked();
  _bIncludeConfiguration = checkBoxIncludeConfiguration->isChecked();
  _bIncludeDebugInfo = checkBoxIncludeDebugInfo->isChecked();

  cfg.setGroup("ELOG");
  str.sprintf( "Attributes:%s:%d:%s", 
               _elog->configuration()->ipAddress().ascii(),
               _elog->configuration()->portNumber(),
               _elog->configuration()->name().ascii() );  
  cfg.writeEntry(str, _strAttributes);
  cfg.writeEntry("IncludeCapture", _bIncludeCapture);
  cfg.writeEntry("IncludeConfiguration", _bIncludeConfiguration);
  cfg.writeEntry("IncludeDebugInfo", _bIncludeDebugInfo);
  cfg.sync();
}
Example #23
0
void KviNickServRuleSet::save(const QString & szConfigFile)
{
	KviConfigurationFile cfg(szConfigFile, KviConfigurationFile::Write);
	cfg.clear();
	save(&cfg, QString(""));
}
Example #24
0
result_list runner::test_one(runner::path_type const& style_path,
                             report_type & report,
                             std::atomic<std::size_t> & fail_count) const
{
    config cfg(defaults_);
    mapnik::Map map(cfg.sizes.front().width, cfg.sizes.front().height);
    result_list results;

    try
    {
        mapnik::load_map(map, style_path.string(), true);
    }
    catch (std::exception const& ex)
    {
        std::string what = ex.what();
        if (what.find("Could not create datasource") != std::string::npos ||
            what.find("Postgis Plugin: could not connect to server") != std::string::npos)
        {
            return results;
        }
        throw;
    }

    mapnik::parameters const & params = map.get_extra_parameters();

    boost::optional<mapnik::value_integer> status = params.get<mapnik::value_integer>("status", cfg.status);

    if (!*status)
    {
        return results;
    }

    boost::optional<std::string> sizes = params.get<std::string>("sizes");

    if (sizes)
    {
        cfg.sizes.clear();
        parse_map_sizes(*sizes, cfg.sizes);
    }

    boost::optional<std::string> tiles = params.get<std::string>("tiles");

    if (tiles)
    {
        cfg.tiles.clear();
        parse_map_sizes(*tiles, cfg.tiles);
    }

    boost::optional<std::string> bbox_string = params.get<std::string>("bbox");
    mapnik::box2d<double> box;

    if (bbox_string)
    {
        box.from_string(*bbox_string);
    }

    std::string name(style_path.stem().string());

    for (auto const & size : cfg.sizes)
    {
        for (auto const & scale_factor : cfg.scales)
        {
            for (auto const & tiles_count : cfg.tiles)
            {
                if (!tiles_count.width || !tiles_count.height)
                {
                    throw std::runtime_error("Cannot render zero tiles.");
                }
                if (size.width % tiles_count.width || size.height % tiles_count.height)
                {
                    throw std::runtime_error("Tile size is not an integer.");
                }

                for (auto const & ren : renderers_)
                {
                    map.resize(size.width * scale_factor, size.height * scale_factor);
                    if (box.valid())
                    {
                        map.zoom_to_box(box);
                    }
                    else
                    {
                        map.zoom_all();
                    }
                    mapnik::util::apply_visitor(renderer_visitor(name,
                                                                 map,
                                                                 tiles_count,
                                                                 scale_factor,
                                                                 results,
                                                                 report,
                                                                 iterations_,
                                                                 fail_limit_,
                                                                 fail_count), ren);
                    if (fail_limit_ && fail_count >= fail_limit_)
                    {
                        return results;
                    }
                }
            }
        }
    }

    return results;
}
Example #25
0
int main(int argc, char* argv[]) {
  signal(SIGSEGV, crash_backtrace);
  signal(SIGABRT, crash_backtrace);
  signal(SIGBUS, crash_backtrace);

  g_redex = new RedexContext();

  auto passes = create_passes();

  Arguments args;
  std::vector<KeepRule> rules;
  // Currently there are two sources that specify the library jars:
  // 1. The jar_path argument, which may specify one library jar.
  // 2. The library_jars vector, which lists the library jars specified in
  //    the ProGuard configuration.
  // If -jarpath specified a library jar it is appended to the
  // library_jars vector so this vector can be used to iterate over
  // all the library jars regardless of whether they were specified
  // on the command line or ProGuard file.
  // TODO: Make the command line -jarpath option like a colon separated
  //       list of library JARS.
  std::set<std::string> library_jars;
  auto start = parse_args(argc, argv, args);
  if (!dir_is_writable(args.out_dir)) {
    fprintf(stderr,
            "outdir %s is not a writable directory\n",
            args.out_dir.c_str());
    exit(1);
  }

  if (!args.proguard_config.empty()) {
    if (!load_proguard_config_file(
            args.proguard_config.c_str(), &rules, &library_jars)) {
      fprintf(stderr,
              "ERROR: Unable to open proguard config %s\n",
              args.proguard_config.c_str());
      // For now tolerate missing or unparseable ProGuard configuration files.
      // start = 0;
    }
  } else {
    TRACE(MAIN,
          1,
          "Skipping parsing the proguard config file "
          "because no file was specified\n");
  }

  for (const auto jar_path : args.jar_paths) {
    std::stringstream jar_stream(jar_path);
    std::string dependent_jar_path;
    while (std::getline(jar_stream, dependent_jar_path, ':')) {
      TRACE(MAIN,
            2,
            "Dependent JAR specified on command-line: %s\n",
            dependent_jar_path.c_str());
      library_jars.emplace(dependent_jar_path);
    }
  }

  if (start == 0 || start == argc) {
    usage();
    exit(1);
  }

  DexClassesVector dexen;
  for (int i = start; i < argc; i++) {
    dexen.emplace_back(load_classes_from_dex(argv[i]));
  }

  for (const auto& library_jar : library_jars) {
    TRACE(MAIN, 1, "LIBRARY JAR: %s\n", library_jar.c_str());
    if (!load_jar_file(library_jar.c_str())) {
      fprintf(
          stderr,
          "WARNING: Error in jar %s - continue. This may lead to unexpected "
          "behavior, please check your jars\n",
          library_jar.c_str());
    }
  }

  ConfigFiles cfg(args.config);
  cfg.using_seeds = false;
  if (!args.seeds_filename.empty()) {
    cfg.using_seeds = init_seed_classes(args.seeds_filename) > 0;
  }

  PassManager manager(passes, rules, args.config);
  manager.run_passes(dexen, cfg);

  TRACE(MAIN, 1, "Writing out new DexClasses...\n");

  LocatorIndex* locator_index = nullptr;
  if (args.config.get("emit_locator_strings", false).asBool()) {
    TRACE(LOC,
          1,
          "Will emit class-locator strings for classloader optimization\n");
    locator_index = new LocatorIndex(make_locator_index(dexen));
  }

  dex_output_stats_t totals;
  std::vector<dex_output_stats_t> dexes_stats;

  auto pos_output = args.config.get("line_number_map", "").asString();
  std::unique_ptr<PositionMapper> pos_mapper(PositionMapper::make(pos_output));

  for (size_t i = 0; i < dexen.size(); i++) {
    std::stringstream ss;
    ss << args.out_dir + "/classes";
    if (i > 0) {
      ss << (i + 1);
    }
    ss << ".dex";
    auto stats = write_classes_to_dex(
      ss.str(),
      &dexen[i],
      locator_index,
      i,
      cfg,
      args.config,
      pos_mapper.get());
    totals += stats;
    dexes_stats.push_back(stats);
  }

  auto stats_output = args.config.get("stats_output", "").asString();
  auto method_move_map = args.config.get("method_move_map", "").asString();

  pos_mapper->write_map();
  output_stats(stats_output.c_str(), totals, dexes_stats, manager);
  output_moved_methods_map(method_move_map.c_str(), dexen, cfg);
  print_warning_summary();
  delete g_redex;
  TRACE(MAIN, 1, "Done.\n");

  return 0;
}
static void iwl_ucode_callback(const struct firmware *ucode_raw, void *context)
{
	struct iwl_drv *drv = context;
	const struct iwl_cfg *cfg = cfg(drv);
	struct iwl_fw *fw = &drv->fw;
	struct iwl_ucode_header *ucode;
	int err;
	struct iwl_firmware_pieces pieces;
	const unsigned int api_max = cfg->ucode_api_max;
	unsigned int api_ok = cfg->ucode_api_ok;
	const unsigned int api_min = cfg->ucode_api_min;
	u32 api_ver;
	int i;

	fw->ucode_capa.max_probe_length = 200;
	fw->ucode_capa.standard_phy_calibration_size =
			IWL_DEFAULT_STANDARD_PHY_CALIBRATE_TBL_SIZE;

	if (!api_ok)
		api_ok = api_max;

	memset(&pieces, 0, sizeof(pieces));

	if (!ucode_raw) {
		if (drv->fw_index <= api_ok)
			IWL_ERR(drv,
				"request for firmware file '%s' failed.\n",
				drv->firmware_name);
		goto try_again;
	}

	IWL_DEBUG_INFO(drv, "Loaded firmware file '%s' (%zd bytes).\n",
		       drv->firmware_name, ucode_raw->size);

	
	if (ucode_raw->size < 4) {
		IWL_ERR(drv, "File size way too small!\n");
		goto try_again;
	}

	
	ucode = (struct iwl_ucode_header *)ucode_raw->data;

	if (ucode->ver)
		err = iwl_parse_v1_v2_firmware(drv, ucode_raw, &pieces);
	else
		err = iwl_parse_tlv_firmware(drv, ucode_raw, &pieces,
					   &fw->ucode_capa);

	if (err)
		goto try_again;

	api_ver = IWL_UCODE_API(drv->fw.ucode_ver);

	
	if (drv->fw_index != UCODE_EXPERIMENTAL_INDEX) {
		if (api_ver < api_min || api_ver > api_max) {
			IWL_ERR(drv,
				"Driver unable to support your firmware API. "
				"Driver supports v%u, firmware is v%u.\n",
				api_max, api_ver);
			goto try_again;
		}

		if (api_ver < api_ok) {
			if (api_ok != api_max)
				IWL_ERR(drv, "Firmware has old API version, "
					"expected v%u through v%u, got v%u.\n",
					api_ok, api_max, api_ver);
			else
				IWL_ERR(drv, "Firmware has old API version, "
					"expected v%u, got v%u.\n",
					api_max, api_ver);
			IWL_ERR(drv, "New firmware can be obtained from "
				      "http://www.intellinuxwireless.org/.\n");
		}
	}

	IWL_INFO(drv, "loaded firmware version %s", drv->fw.fw_version);


	IWL_DEBUG_INFO(drv, "f/w package hdr ucode version raw = 0x%x\n",
		       drv->fw.ucode_ver);
	IWL_DEBUG_INFO(drv, "f/w package hdr runtime inst size = %Zd\n",
		get_sec_size(&pieces, IWL_UCODE_REGULAR,
			     IWL_UCODE_SECTION_INST));
	IWL_DEBUG_INFO(drv, "f/w package hdr runtime data size = %Zd\n",
		get_sec_size(&pieces, IWL_UCODE_REGULAR,
			     IWL_UCODE_SECTION_DATA));
	IWL_DEBUG_INFO(drv, "f/w package hdr init inst size = %Zd\n",
		get_sec_size(&pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST));
	IWL_DEBUG_INFO(drv, "f/w package hdr init data size = %Zd\n",
		get_sec_size(&pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA));

	
	if (get_sec_size(&pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST) >
							cfg->max_inst_size) {
		IWL_ERR(drv, "uCode instr len %Zd too large to fit in\n",
			get_sec_size(&pieces, IWL_UCODE_REGULAR,
				     IWL_UCODE_SECTION_INST));
		goto try_again;
	}

	if (get_sec_size(&pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA) >
							cfg->max_data_size) {
		IWL_ERR(drv, "uCode data len %Zd too large to fit in\n",
			get_sec_size(&pieces, IWL_UCODE_REGULAR,
				     IWL_UCODE_SECTION_DATA));
		goto try_again;
	}

	if (!fw->mvm_fw && validate_sec_sizes(drv, &pieces, cfg))
		goto try_again;

	

	for (i = 0; i < IWL_UCODE_TYPE_MAX; i++)
		if (alloc_pci_desc(drv, &pieces, i))
			goto err_pci_alloc;

	

	fw->init_evtlog_ptr = pieces.init_evtlog_ptr;
	if (pieces.init_evtlog_size)
		fw->init_evtlog_size = (pieces.init_evtlog_size - 16)/12;
	else
		fw->init_evtlog_size =
			cfg->base_params->max_event_log_size;
	fw->init_errlog_ptr = pieces.init_errlog_ptr;
	fw->inst_evtlog_ptr = pieces.inst_evtlog_ptr;
	if (pieces.inst_evtlog_size)
		fw->inst_evtlog_size = (pieces.inst_evtlog_size - 16)/12;
	else
		fw->inst_evtlog_size =
			cfg->base_params->max_event_log_size;
	fw->inst_errlog_ptr = pieces.inst_errlog_ptr;

	if (fw->ucode_capa.standard_phy_calibration_size >
	    IWL_MAX_PHY_CALIBRATE_TBL_SIZE)
		fw->ucode_capa.standard_phy_calibration_size =
			IWL_MAX_STANDARD_PHY_CALIBRATE_TBL_SIZE;

	
	release_firmware(ucode_raw);
	complete(&drv->request_firmware_complete);

	drv->op_mode = iwl_dvm_ops.start(drv->shrd->trans, &drv->fw);

	if (!drv->op_mode)
		goto out_unbind;

	return;

 try_again:
	
	release_firmware(ucode_raw);
	if (iwl_request_firmware(drv, false))
		goto out_unbind;
	return;

 err_pci_alloc:
	IWL_ERR(drv, "failed to allocate pci memory\n");
	iwl_dealloc_ucode(drv);
	release_firmware(ucode_raw);
 out_unbind:
	complete(&drv->request_firmware_complete);
	device_release_driver(trans(drv)->dev);
}
Example #27
0
SplitterGUI::SplitterGUI(QWidget* parent,  QUrl fileURL, QUrl defaultDir) :
        QDialog(parent),
        userDefinedSize(0x100000), lastSelectedDevice(-1), resultCode(QDialog::Rejected),
        division(1)
{
    setModal(true);

    QGridLayout *grid = new QGridLayout(this);
    grid->setSpacing(6);
    grid->setContentsMargins(11, 11, 11, 11);

    QLabel *splitterLabel = new QLabel(this);
    splitterLabel->setText(i18n("Split the file %1 to folder:", fileURL.toDisplayString(QUrl::PreferLocalFile)));
    splitterLabel->setMinimumWidth(400);
    grid->addWidget(splitterLabel, 0 , 0);

    urlReq = new KUrlRequester(this);
    urlReq->setUrl(defaultDir);
    urlReq->setMode(KFile::Directory);
    grid->addWidget(urlReq, 1 , 0);

    QWidget *splitSizeLine = new QWidget(this);
    QHBoxLayout * splitSizeLineLayout = new QHBoxLayout;
    splitSizeLineLayout->setContentsMargins(0, 0, 0, 0);
    splitSizeLine->setLayout(splitSizeLineLayout);

    deviceCombo = new QComboBox(splitSizeLine);
    for (int i = 0; i != predefinedDevices().count(); i++)
        deviceCombo->addItem(predefinedDevices()[i].name);
    deviceCombo->addItem(i18n("User Defined"));
    splitSizeLineLayout->addWidget(deviceCombo);

    QLabel *spacer = new QLabel(splitSizeLine);
    spacer->setText(" ");
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    splitSizeLineLayout->addWidget(spacer);

    QLabel *bytesPerFile = new QLabel(splitSizeLine);
    bytesPerFile->setText(i18n("Max file size:"));
    splitSizeLineLayout->addWidget(bytesPerFile);

    spinBox = new QDoubleSpinBox(splitSizeLine);
    spinBox->setMaximum(9999999999.0);
    spinBox->setMinimumWidth(85);
    spinBox->setEnabled(false);
    splitSizeLineLayout->addWidget(spinBox);

    sizeCombo = new QComboBox(splitSizeLine);
    sizeCombo->addItem(i18n("Byte"));
    sizeCombo->addItem(i18n("kByte"));
    sizeCombo->addItem(i18n("MByte"));
    sizeCombo->addItem(i18n("GByte"));
    splitSizeLineLayout->addWidget(sizeCombo);

    grid->addWidget(splitSizeLine, 2 , 0);

    overwriteCb = new QCheckBox(i18n("Overwrite files without confirmation"), this);
    grid->addWidget(overwriteCb, 3, 0);

    QFrame *separator = new QFrame(this);
    separator->setFrameStyle(QFrame::HLine | QFrame::Sunken);
    separator->setFixedHeight(separator->sizeHint().height());

    grid->addWidget(separator, 4 , 0);

    QHBoxLayout *splitButtons = new QHBoxLayout;
    splitButtons->setSpacing(6);
    splitButtons->setContentsMargins(0, 0, 0, 0);

    QSpacerItem* spacer2 = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
    splitButtons->addItem(spacer2);

    QPushButton *splitBtn = new QPushButton(this);
    splitBtn->setText(i18n("&Split"));
    splitBtn->setIcon(QIcon::fromTheme("dialog-ok"));
    splitButtons->addWidget(splitBtn);

    QPushButton *cancelBtn = new QPushButton(this);
    cancelBtn->setText(i18n("&Cancel"));
    cancelBtn->setIcon(QIcon::fromTheme("dialog-cancel"));
    splitButtons->addWidget(cancelBtn);

    grid->addLayout(splitButtons, 5 , 0);

    setWindowTitle(i18n("Krusader::Splitter"));


    KConfigGroup cfg(KSharedConfig::openConfig(), QStringLiteral("Splitter"));
    overwriteCb->setChecked(cfg.readEntry("OverWriteFiles", false));

    connect(sizeCombo, SIGNAL(activated(int)), this, SLOT(sizeComboActivated(int)));
    connect(deviceCombo, SIGNAL(activated(int)), this, SLOT(predefinedComboActivated(int)));
    connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));
    connect(splitBtn , SIGNAL(clicked()), this, SLOT(splitPressed()));

    predefinedComboActivated(0);
    resultCode = exec();
}
Example #28
0
/**
 * iwl_init_geos - Initialize mac80211's geo/channel info based from eeprom
 */
int iwl_init_geos(struct iwl_priv *priv)
{
	struct iwl_channel_info *ch;
	struct ieee80211_supported_band *sband;
	struct ieee80211_channel *channels;
	struct ieee80211_channel *geo_ch;
	struct ieee80211_rate *rates;
	int i = 0;
	s8 max_tx_power = IWLAGN_TX_POWER_TARGET_POWER_MIN;

	if (priv->bands[IEEE80211_BAND_2GHZ].n_bitrates ||
	    priv->bands[IEEE80211_BAND_5GHZ].n_bitrates) {
		IWL_DEBUG_INFO(priv, "Geography modes already initialized.\n");
		set_bit(STATUS_GEO_CONFIGURED, &priv->shrd->status);
		return 0;
	}

	channels = kcalloc(priv->channel_count,
			   sizeof(struct ieee80211_channel), GFP_KERNEL);
	if (!channels)
		return -ENOMEM;

	rates = kcalloc(IWL_RATE_COUNT_LEGACY, sizeof(struct ieee80211_rate),
			GFP_KERNEL);
	if (!rates) {
		kfree(channels);
		return -ENOMEM;
	}

	/* 5.2GHz channels start after the 2.4GHz channels */
	sband = &priv->bands[IEEE80211_BAND_5GHZ];
	sband->channels = &channels[ARRAY_SIZE(iwl_eeprom_band_1)];
	/* just OFDM */
	sband->bitrates = &rates[IWL_FIRST_OFDM_RATE];
	sband->n_bitrates = IWL_RATE_COUNT_LEGACY - IWL_FIRST_OFDM_RATE;

	if (cfg(priv)->sku & EEPROM_SKU_CAP_11N_ENABLE)
		iwl_init_ht_hw_capab(priv, &sband->ht_cap,
					 IEEE80211_BAND_5GHZ);

	sband = &priv->bands[IEEE80211_BAND_2GHZ];
	sband->channels = channels;
	/* OFDM & CCK */
	sband->bitrates = rates;
	sband->n_bitrates = IWL_RATE_COUNT_LEGACY;

	if (cfg(priv)->sku & EEPROM_SKU_CAP_11N_ENABLE)
		iwl_init_ht_hw_capab(priv, &sband->ht_cap,
					 IEEE80211_BAND_2GHZ);

	priv->ieee_channels = channels;
	priv->ieee_rates = rates;

	for (i = 0;  i < priv->channel_count; i++) {
		ch = &priv->channel_info[i];

		/* FIXME: might be removed if scan is OK */
		if (!is_channel_valid(ch))
			continue;

		sband =  &priv->bands[ch->band];

		geo_ch = &sband->channels[sband->n_channels++];

		geo_ch->center_freq =
			ieee80211_channel_to_frequency(ch->channel, ch->band);
		geo_ch->max_power = ch->max_power_avg;
		geo_ch->max_antenna_gain = 0xff;
		geo_ch->hw_value = ch->channel;

		if (is_channel_valid(ch)) {
			if (!(ch->flags & EEPROM_CHANNEL_IBSS))
				geo_ch->flags |= IEEE80211_CHAN_NO_IBSS;

			if (!(ch->flags & EEPROM_CHANNEL_ACTIVE))
				geo_ch->flags |= IEEE80211_CHAN_PASSIVE_SCAN;

			if (ch->flags & EEPROM_CHANNEL_RADAR)
				geo_ch->flags |= IEEE80211_CHAN_RADAR;

			geo_ch->flags |= ch->ht40_extension_channel;

			if (ch->max_power_avg > max_tx_power)
				max_tx_power = ch->max_power_avg;
		} else {
			geo_ch->flags |= IEEE80211_CHAN_DISABLED;
		}

		IWL_DEBUG_INFO(priv, "Channel %d Freq=%d[%sGHz] %s flag=0x%X\n",
				ch->channel, geo_ch->center_freq,
				is_channel_a_band(ch) ?  "5.2" : "2.4",
				geo_ch->flags & IEEE80211_CHAN_DISABLED ?
				"restricted" : "valid",
				 geo_ch->flags);
	}

	priv->tx_power_device_lmt = max_tx_power;
	priv->tx_power_user_lmt = max_tx_power;
	priv->tx_power_next = max_tx_power;

	if ((priv->bands[IEEE80211_BAND_5GHZ].n_channels == 0) &&
	     cfg(priv)->sku & EEPROM_SKU_CAP_BAND_52GHZ) {
		char buf[32];
		bus_get_hw_id_string(bus(priv), buf, sizeof(buf));
		IWL_INFO(priv, "Incorrectly detected BG card as ABG. "
			"Please send your %s to maintainer.\n", buf);
		cfg(priv)->sku &= ~EEPROM_SKU_CAP_BAND_52GHZ;
	}

	IWL_INFO(priv, "Tunable channels: %d 802.11bg, %d 802.11a channels\n",
		   priv->bands[IEEE80211_BAND_2GHZ].n_channels,
		   priv->bands[IEEE80211_BAND_5GHZ].n_channels);

	set_bit(STATUS_GEO_CONFIGURED, &priv->shrd->status);

	return 0;
}
Example #29
0
int         tidyDocSaveStream( TidyDocImpl* doc, StreamOut* out )
{
    Bool showMarkup  = cfgBool( doc, TidyShowMarkup );
    Bool forceOutput = cfgBool( doc, TidyForceOutput );
#if SUPPORT_UTF16_ENCODINGS
    Bool outputBOM   = ( cfgAutoBool(doc, TidyOutputBOM) == TidyYesState );
    Bool smartBOM    = ( cfgAutoBool(doc, TidyOutputBOM) == TidyAutoState );
#endif
    Bool xmlOut      = cfgBool( doc, TidyXmlOut );
    Bool xhtmlOut    = cfgBool( doc, TidyXhtmlOut );
    TidyTriState bodyOnly    = cfgAutoBool( doc, TidyBodyOnly );

    Bool dropComments = cfgBool(doc, TidyHideComments);
    Bool makeClean    = cfgBool(doc, TidyMakeClean);
    Bool asciiChars   = cfgBool(doc, TidyAsciiChars);
    Bool makeBare     = cfgBool(doc, TidyMakeBare);
    Bool escapeCDATA  = cfgBool(doc, TidyEscapeCdata);
    TidyAttrSortStrategy sortAttrStrat = cfg(doc, TidySortAttributes);

    if (escapeCDATA)
        TY_(ConvertCDATANodes)(doc, &doc->root);

    if (dropComments)
        TY_(DropComments)(doc, &doc->root);

    if (makeClean)
    {
        /* noop */
        TY_(DropFontElements)(doc, &doc->root, NULL);
        TY_(WbrToSpace)(doc, &doc->root);
    }

    if ((makeClean && asciiChars) || makeBare)
        TY_(DowngradeTypography)(doc, &doc->root);

    if (makeBare)
        /* Note: no longer replaces &nbsp; in */
        /* attribute values / non-text tokens */
        TY_(NormalizeSpaces)(doc->lexer, &doc->root);
    else
        TY_(ReplacePreformattedSpaces)(doc, &doc->root);

    if ( sortAttrStrat != TidySortAttrNone )
        TY_(SortAttributes)(&doc->root, sortAttrStrat);

    if ( showMarkup && (doc->errors == 0 || forceOutput) )
    {
#if SUPPORT_UTF16_ENCODINGS
        /* Output a Byte Order Mark if required */
        if ( outputBOM || (doc->inputHadBOM && smartBOM) )
            TY_(outBOM)( out );
#endif

        /* No longer necessary. No DOCTYPE == HTML 3.2,
        ** which gives you only the basic character entities,
        ** which are safe in any browser.
        ** if ( !TY_(FindDocType)(doc) )
        **    TY_(SetOptionBool)( doc, TidyNumEntities, yes );
        */

        doc->docOut = out;
        if ( xmlOut && !xhtmlOut )
            TY_(PPrintXMLTree)( doc, NORMAL, 0, &doc->root );
        else if ( showBodyOnly( doc, bodyOnly ) )
            TY_(PrintBody)( doc );
        else
            TY_(PPrintTree)( doc, NORMAL, 0, &doc->root );

        TY_(PFlushLine)( doc, 0 );
        doc->docOut = NULL;
    }

    TY_(ResetConfigToSnapshot)( doc );
    return tidyDocStatus( doc );
}
Example #30
0
wxArrayString UserActions::GetGroups()
{
	return cfg().GetGroupList(_T( "/Groups/" ));
}