void DarkBlueStyle::drawControl(ControlElement element, const QStyleOption* opt, QPainter* p, const QWidget* widget) const { switch(element) { case CE_ToolBar: { // This does nothing.... //const QStyleOptionToolBar* toolBar = qstyleoption_cast<const QStyleOptionToolBar *>(opt); //proxy()->drawPrimitive(PE_PanelToolBar, opt, p, widget); break; } case CE_RadioButton: { const QStyleOptionButton* btn = qstyleoption_cast<const QStyleOptionButton *>(opt); QStyleOptionButton subopt = *btn; subopt.rect = subElementRect(SE_RadioButtonIndicator, btn, widget); proxy()->drawPrimitive(PE_IndicatorRadioButton, &subopt, p, widget); subopt.rect = subElementRect(SE_RadioButtonContents, btn, widget); proxy()->drawControl(CE_RadioButtonLabel, &subopt, p, widget); break; } case CE_CheckBox: { const QStyleOptionButton* btn = qstyleoption_cast<const QStyleOptionButton *>(opt); QStyleOptionButton subopt = *btn; subopt.rect = subElementRect(SE_CheckBoxIndicator, btn, widget); proxy()->drawPrimitive(PE_IndicatorCheckBox, &subopt, p, widget); subopt.rect = subElementRect(SE_CheckBoxContents, btn, widget); proxy()->drawControl(CE_CheckBoxLabel, &subopt, p, widget); break; } case CE_RadioButtonLabel: case CE_CheckBoxLabel: { const QStyleOptionButton* btn = qstyleoption_cast<const QStyleOptionButton *>(opt); if(!btn->text.isEmpty()) { p->setPen(QColor(200, 200, 200)); p->drawText(btn->rect, Qt::AlignLeft | Qt::AlignVCenter, btn->text); } break; } case CE_PushButton: { const QStyleOptionButton* btn = qstyleoption_cast<const QStyleOptionButton *>(opt); proxy()->drawControl(CE_PushButtonBevel, btn, p, widget); QStyleOptionButton subopt = *btn; subopt.rect = subElementRect(SE_PushButtonContents, btn, widget); proxy()->drawControl(CE_PushButtonLabel, &subopt, p, widget); break; } case CE_PushButtonBevel: { const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt); QRect br = btn->rect; if(btn->features & QStyleOptionButton::DefaultButton) { proxy()->drawPrimitive(PE_FrameDefaultButton, opt, p, widget); } if(!(btn->features & (QStyleOptionButton::Flat | QStyleOptionButton::CommandLinkButton)) || btn->state & (State_Sunken | State_On) || (btn->features & QStyleOptionButton::CommandLinkButton && btn->state & State_MouseOver)) { QStyleOptionButton tmpBtn = *btn; tmpBtn.rect = br; proxy()->drawPrimitive(PE_PanelButtonCommand, &tmpBtn, p, widget); } break; } default: { mStyle->drawControl(element, opt, p, widget); break; } } }
// Detect any proxy configuration settings automatically. // static void windows_detect_autoproxy_settings() { if (log_flags.proxy_debug) { post_sysmon_msg("[proxy] automatic proxy check in progress"); } HINTERNET hWinHttp = NULL; WINHTTP_AUTOPROXY_OPTIONS autoproxy_options; WINHTTP_PROXY_INFO proxy_info; PARSED_URL purl; std::wstring network_test_url; size_t pos; memset(&autoproxy_options, 0, sizeof(autoproxy_options)); memset(&proxy_info, 0, sizeof(proxy_info)); autoproxy_options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoproxy_options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoproxy_options.fAutoLogonIfChallenged = TRUE; network_test_url = boinc_ascii_to_wide(cc_config.network_test_url).c_str(); hWinHttp = WinHttpOpen( L"BOINC client", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, NULL ); char msg[1024], buf[1024]; safe_strcpy(msg, "[proxy] "); if (WinHttpGetProxyForUrl(hWinHttp, network_test_url.c_str(), &autoproxy_options, &proxy_info)) { // Apparently there are some conditions where WinHttpGetProxyForUrl can return // success but where proxy_info.lpszProxy is null. Maybe related to UPNP? // // For the time being check to see if proxy_info.lpszProxy is non-null. // if (proxy_info.lpszProxy) { std::string proxy(boinc_wide_to_ascii(std::wstring(proxy_info.lpszProxy))); std::string new_proxy; if (log_flags.proxy_debug) { safe_strcat(msg, "proxy list: "); safe_strcat(msg, proxy.c_str()); } if (!proxy.empty()) { // Trim string if more than one proxy is defined // proxy list is defined as: // ([<scheme>=][<scheme>"://"]<server>[":"<port>]) // Find and erase first delimeter type. pos = proxy.find(';'); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Find and erase second delimeter type. pos = proxy.find(' '); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Parse the remaining url parse_url(proxy.c_str(), purl); // Store the results for future use. if (0 != strcmp(working_proxy_info.autodetect_server_name, purl.host)) { // Reset clients connection error detection path net_status.need_physical_connection = false; working_proxy_info.autodetect_protocol = purl.protocol; safe_strcpy(working_proxy_info.autodetect_server_name, purl.host); working_proxy_info.autodetect_port = purl.port; } if (log_flags.proxy_debug) { snprintf(buf, sizeof(buf), "proxy detected %s:%d", purl.host, purl.port); safe_strcat(msg, buf); } } } // Clean up if (proxy_info.lpszProxy) GlobalFree(proxy_info.lpszProxy); if (proxy_info.lpszProxyBypass) GlobalFree(proxy_info.lpszProxyBypass); } else { // We can get here if the user is switching from a network that // requires a proxy to one that does not require a proxy. working_proxy_info.autodetect_protocol = 0; safe_strcpy(working_proxy_info.autodetect_server_name, ""); working_proxy_info.autodetect_port = 0; if (log_flags.proxy_debug) { safe_strcat(msg, "no automatic proxy detected"); } } if (hWinHttp) WinHttpCloseHandle(hWinHttp); if (log_flags.proxy_debug) { post_sysmon_msg(msg); } }
proxy operator*() { return proxy(); }
void QTMStyle::drawComplexControl (ComplexControl cc, const QStyleOptionComplex* opt, QPainter* p, const QWidget* widget) const { switch (cc) { case CC_ToolButton: if (const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) { QRect button, menuarea; button = proxy()->subControlRect(cc, toolbutton, SC_ToolButton, widget); menuarea = proxy()->subControlRect(cc, toolbutton, SC_ToolButtonMenu, widget); State bflags = toolbutton->state & ~State_Sunken; if (bflags & State_AutoRaise) { if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) { bflags &= ~State_Raised; } } State mflags = bflags; if (toolbutton->state & State_Sunken) { if (toolbutton->activeSubControls & SC_ToolButton) bflags |= State_Sunken; mflags |= State_Sunken; } QStyleOption tool(0); tool.palette = toolbutton->palette; if (toolbutton->subControls & SC_ToolButton) { if (bflags & (State_Sunken | State_On | State_Raised)) { tool.rect = button; tool.state = bflags; proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget); } } if (toolbutton->state & State_HasFocus) { QStyleOptionFocusRect fr; fr.QStyleOption::operator=(*toolbutton); fr.rect.adjust(3, 3, -3, -3); if (toolbutton->features & QStyleOptionToolButton::MenuButtonPopup) fr.rect.adjust(0, 0, -proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, toolbutton, widget), 0); proxy()->drawPrimitive(PE_FrameFocusRect, &fr, p, widget); } QStyleOptionToolButton label = *toolbutton; label.state = bflags; int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget); label.rect = button.adjusted(fw, fw, -fw, -fw); proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget); if (toolbutton->subControls & SC_ToolButtonMenu) { tool.rect = menuarea; tool.state = mflags; if (mflags & (State_Sunken | State_On | State_Raised)) proxy()->drawPrimitive(PE_IndicatorButtonDropDown, &tool, p, widget); proxy()->drawPrimitive(PE_IndicatorArrowDown, &tool, p, widget); } else if ((toolbutton->features & QStyleOptionToolButton::HasMenu) && (mflags & State_MouseOver)) { int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, toolbutton, widget); QRect ir = toolbutton->rect; QStyleOptionToolButton newBtn = *toolbutton; newBtn.rect = QRect(ir.right() + 5 - mbi, ir.y() + ir.height() - mbi + 4, mbi - 6, mbi - 6); proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget); } } break; default: baseStyle()->drawComplexControl (cc, opt, p, widget); } }
int CNetworkSetup::showNetworkSetup() { struct dirent **namelist; //if select int ifcount = scandir("/sys/class/net", &namelist, my_filter, alphasort); CMenuOptionStringChooser * ifSelect = new CMenuOptionStringChooser(LOCALE_NETWORKMENU_SELECT_IF, &g_settings.ifname, ifcount > 1, this, CRCInput::RC_nokey, "", true); ifSelect->setHint("", LOCALE_MENU_HINT_NET_IF); bool found = false; for(int i = 0; i < ifcount; i++) { ifSelect->addOption(namelist[i]->d_name); if(strcmp(g_settings.ifname.c_str(), namelist[i]->d_name) == 0) found = true; free(namelist[i]); } if (ifcount >= 0) free(namelist); if(!found) g_settings.ifname = "eth0"; networkConfig->readConfig(g_settings.ifname); readNetworkSettings(); backupNetworkSettings(); //menue init CMenuWidget* networkSettings = new CMenuWidget(LOCALE_MAINSETTINGS_HEAD, NEUTRINO_ICON_SETTINGS, width, MN_WIDGET_ID_NETWORKSETUP); networkSettings->setWizardMode(is_wizard); //apply button CMenuForwarder *m0 = new CMenuForwarder(LOCALE_NETWORKMENU_SETUPNOW, true, NULL, this, "networkapply", CRCInput::RC_red); m0->setHint("", LOCALE_MENU_HINT_NET_SETUPNOW); //eth id CMenuForwarder *mac = new CMenuForwarder("MAC", false, mac_addr); //prepare input entries CIPInput networkSettings_NetworkIP(LOCALE_NETWORKMENU_IPADDRESS , &network_address , LOCALE_IPSETUP_HINT_1, LOCALE_IPSETUP_HINT_2, this); CIPInput networkSettings_NetMask (LOCALE_NETWORKMENU_NETMASK , &network_netmask , LOCALE_IPSETUP_HINT_1, LOCALE_IPSETUP_HINT_2, this); CIPInput networkSettings_Gateway (LOCALE_NETWORKMENU_GATEWAY , &network_gateway , LOCALE_IPSETUP_HINT_1, LOCALE_IPSETUP_HINT_2); CIPInput networkSettings_NameServer(LOCALE_NETWORKMENU_NAMESERVER, &network_nameserver, LOCALE_IPSETUP_HINT_1, LOCALE_IPSETUP_HINT_2); //hostname CKeyboardInput networkSettings_Hostname(LOCALE_NETWORKMENU_HOSTNAME, &network_hostname, 0, NULL, NULL, LOCALE_NETWORKMENU_HOSTNAME_HINT1, LOCALE_NETWORKMENU_HOSTNAME_HINT2); //auto start CMenuOptionChooser* o1 = new CMenuOptionChooser(LOCALE_NETWORKMENU_SETUPONSTARTUP, &network_automatic_start, OPTIONS_OFF0_ON1_OPTIONS, OPTIONS_OFF0_ON1_OPTION_COUNT, true); o1->setHint("", LOCALE_MENU_HINT_NET_SETUPONSTARTUP); //dhcp network_dhcp = networkConfig->inet_static ? NETWORK_DHCP_OFF : NETWORK_DHCP_ON; CMenuForwarder *m1 = new CMenuForwarder(LOCALE_NETWORKMENU_IPADDRESS , networkConfig->inet_static, network_address , &networkSettings_NetworkIP ); CMenuForwarder *m2 = new CMenuForwarder(LOCALE_NETWORKMENU_NETMASK , networkConfig->inet_static, network_netmask , &networkSettings_NetMask ); setBroadcast(); CMenuForwarder *m3 = new CMenuForwarder(LOCALE_NETWORKMENU_BROADCAST , false, network_broadcast); CMenuForwarder *m4 = new CMenuForwarder(LOCALE_NETWORKMENU_GATEWAY , networkConfig->inet_static, network_gateway , &networkSettings_Gateway ); CMenuForwarder *m5 = new CMenuForwarder(LOCALE_NETWORKMENU_NAMESERVER, networkConfig->inet_static, network_nameserver, &networkSettings_NameServer); CMenuForwarder *m8 = new CMenuForwarder(LOCALE_NETWORKMENU_HOSTNAME , true , network_hostname , &networkSettings_Hostname ); m1->setHint("", LOCALE_MENU_HINT_NET_IPADDRESS); m2->setHint("", LOCALE_MENU_HINT_NET_NETMASK); m3->setHint("", LOCALE_MENU_HINT_NET_BROADCAST); m4->setHint("", LOCALE_MENU_HINT_NET_GATEWAY); m5->setHint("", LOCALE_MENU_HINT_NET_NAMESERVER); m8->setHint("", LOCALE_MENU_HINT_NET_HOSTNAME); dhcpDisable.Add(m1); dhcpDisable.Add(m2); dhcpDisable.Add(m3); dhcpDisable.Add(m4); dhcpDisable.Add(m5); CMenuOptionChooser* o2 = new CMenuOptionChooser(LOCALE_NETWORKMENU_DHCP, &network_dhcp, OPTIONS_OFF0_ON1_OPTIONS, OPTIONS_OFF0_ON1_OPTION_COUNT, true, this); o2->setHint("", LOCALE_MENU_HINT_NET_DHCP); //paint menu items networkSettings->addIntroItems(LOCALE_MAINSETTINGS_NETWORK); //intros //------------------------------------------------- networkSettings->addItem( m0 ); //apply CMenuForwarder * mf = new CMenuForwarder(LOCALE_NETWORKMENU_TEST, true, NULL, this, "networktest", CRCInput::RC_green); mf->setHint("", LOCALE_MENU_HINT_NET_TEST); networkSettings->addItem(mf); //test mf = new CMenuForwarder(LOCALE_NETWORKMENU_SHOW, true, NULL, this, "networkshow", CRCInput::RC_info); mf->setHint("", LOCALE_MENU_HINT_NET_SHOW); networkSettings->addItem(mf); //show settings networkSettings->addItem(GenericMenuSeparatorLine); //------------------------------------------------ if(ifcount) networkSettings->addItem(ifSelect); //if select else delete ifSelect; networkSettings->addItem(o1); //set on start networkSettings->addItem(GenericMenuSeparatorLine); //------------------------------------------------ networkSettings->addItem(mac); //eth id networkSettings->addItem(GenericMenuSeparatorLine); //------------------------------------------------- networkSettings->addItem(o2); //dhcp on/off networkSettings->addItem( m8); //hostname networkSettings->addItem(GenericMenuSeparatorLine); //------------------------------------------------- networkSettings->addItem( m1); //adress networkSettings->addItem( m2); //mask networkSettings->addItem( m3); //broadcast networkSettings->addItem(GenericMenuSeparatorLine); //------------------------------------------------ networkSettings->addItem( m4); //gateway networkSettings->addItem( m5); //nameserver networkSettings->addItem(GenericMenuSeparatorLine); //------------------------------------------------ if(ifcount > 1) // if there is only one, its probably wired { //ssid CKeyboardInput * networkSettings_ssid = new CKeyboardInput(LOCALE_NETWORKMENU_SSID, &network_ssid); //key CKeyboardInput * networkSettings_key = new CKeyboardInput(LOCALE_NETWORKMENU_PASSWORD, &network_key); CMenuForwarder *m9 = new CMenuDForwarder(LOCALE_NETWORKMENU_SSID , networkConfig->wireless, network_ssid , networkSettings_ssid ); CMenuForwarder *m10 = new CMenuDForwarder(LOCALE_NETWORKMENU_PASSWORD , networkConfig->wireless, network_key , networkSettings_key ); CMenuForwarder *m11 = new CMenuForwarder(LOCALE_NETWORKMENU_SSID_SCAN , networkConfig->wireless, NULL, this, "scanssid"); CMenuOptionChooser* m12 = new CMenuOptionChooser(LOCALE_NETWORKMENU_WLAN_SECURITY, &network_encryption, OPTIONS_WLAN_SECURITY_OPTIONS, OPTIONS_WLAN_SECURITY_OPTION_COUNT, true); m9->setHint("", LOCALE_MENU_HINT_NET_SSID); m10->setHint("", LOCALE_MENU_HINT_NET_PASS); m11->setHint("", LOCALE_MENU_HINT_NET_SSID_SCAN); wlanEnable.Add(m9); wlanEnable.Add(m10); wlanEnable.Add(m11); wlanEnable.Add(m12); networkSettings->addItem( m11); //ssid scan networkSettings->addItem( m9); //ssid networkSettings->addItem( m10); //key networkSettings->addItem( m12); //encryption networkSettings->addItem(GenericMenuSeparatorLine); } //------------------------------------------------ //ntp submenu sectionsdConfigNotifier = new CSectionsdConfigNotifier; CMenuWidget ntp(LOCALE_MAINSETTINGS_NETWORK, NEUTRINO_ICON_SETTINGS, width, MN_WIDGET_ID_NETWORKSETUP_NTP); mf = new CMenuForwarder(LOCALE_NETWORKMENU_NTPTITLE, true, NULL, &ntp, NULL, CRCInput::RC_yellow); mf->setHint("", LOCALE_MENU_HINT_NET_NTP); networkSettings->addItem(mf); showNetworkNTPSetup(&ntp); #ifdef ENABLE_GUI_MOUNT //nfs mount submenu CMenuWidget networkmounts(LOCALE_MAINSETTINGS_NETWORK, NEUTRINO_ICON_SETTINGS, width, MN_WIDGET_ID_NETWORKSETUP_MOUNTS); mf = new CMenuForwarder(LOCALE_NETWORKMENU_MOUNT, true, NULL, &networkmounts, NULL, CRCInput::RC_blue); mf->setHint("", LOCALE_MENU_HINT_NET_MOUNT); networkSettings->addItem(mf); showNetworkNFSMounts(&networkmounts); #endif //proxyserver submenu CProxySetup proxy(LOCALE_MAINSETTINGS_NETWORK); mf = new CMenuForwarder(LOCALE_FLASHUPDATE_PROXYSERVER_SEP, true, NULL, &proxy, NULL, CRCInput::RC_0); mf->setHint("", LOCALE_MENU_HINT_NET_PROXY); networkSettings->addItem(mf); //services CNetworkServiceSetup services; mf = new CMenuForwarder(LOCALE_NETWORKMENU_SERVICES, true, NULL, &services, NULL, CRCInput::RC_1); mf->setHint("", LOCALE_MENU_HINT_NET_SERVICES); networkSettings->addItem(mf); int ret = 0; while(true) { int res = menu_return::RETURN_EXIT; ret = networkSettings->exec(NULL, ""); if (settingsChanged()) res = saveChangesDialog(); if(res == menu_return::RETURN_EXIT) break; } dhcpDisable.Clear(); wlanEnable.Clear(); delete networkSettings; delete sectionsdConfigNotifier; return ret; }
void ScriptableWorker::run() { MONITOR_LOG("starting"); QScriptEngine engine; ScriptableProxy proxy(m_wnd); Scriptable scriptable(&proxy); scriptable.initEngine( &engine, QString::fromUtf8(m_args.at(Arguments::CurrentPath)), m_args.at(Arguments::ActionId) ); if (m_socket) { QObject::connect( &scriptable, SIGNAL(sendMessage(QByteArray,int)), m_socket, SLOT(sendMessage(QByteArray,int)) ); QObject::connect( m_socket, SIGNAL(messageReceived(QByteArray,int)), &scriptable, SLOT(setInput(QByteArray)) ); QObject::connect( m_socket, SIGNAL(disconnected()), &scriptable, SLOT(abort()) ); QObject::connect( &scriptable, SIGNAL(destroyed()), m_socket, SLOT(deleteAfterDisconnected()) ); if ( m_socket->isClosed() ) { MONITOR_LOG("terminated"); return; } m_socket->start(); } QObject::connect( &scriptable, SIGNAL(requestApplicationQuit()), qApp, SLOT(quit()) ); QByteArray response; int exitCode; if ( m_args.length() <= Arguments::Rest ) { MONITOR_LOG("Error: bad command syntax"); exitCode = CommandBadSyntax; } else { const QString cmd = QString::fromUtf8( m_args.at(Arguments::Rest) ); if ( hasLogLevel(LogDebug) ) { MONITOR_LOG("Client arguments:"); for (int i = Arguments::Rest; i < m_args.length(); ++i) MONITOR_LOG( " " + QString::fromUtf8(m_args.at(i)) ); } #ifdef HAS_TESTS if ( cmd == "flush" && m_args.length() == Arguments::Rest + 2 ) { MONITOR_LOG( "flush ID: " + QString::fromUtf8(m_args.at(Arguments::Rest + 1)) ); scriptable.sendMessageToClient(QByteArray(), CommandFinished); return; } #endif QScriptValue fn = engine.globalObject().property(cmd); if ( !fn.isFunction() ) { MONITOR_LOG("Error: unknown command"); response = createLogMessage("CopyQ client", Scriptable::tr("Name \"%1\" doesn't refer to a function.") .arg(cmd), LogError).toUtf8(); exitCode = CommandError; } else { QScriptValueList fnArgs; for ( int i = Arguments::Rest + 1; i < m_args.length(); ++i ) fnArgs.append( scriptable.newByteArray(m_args.at(i)) ); QScriptValue result = fn.call(QScriptValue(), fnArgs); if ( engine.hasUncaughtException() ) { const QString exceptionText = engine.uncaughtException().toString(); MONITOR_LOG( QString("Error: exception in command \"%1\": %2") .arg(cmd).arg(exceptionText) ); response = createLogMessage("CopyQ client", exceptionText, LogError).toUtf8(); exitCode = CommandError; } else { response = serializeScriptValue(result); exitCode = CommandFinished; } } } scriptable.sendMessageToClient(response, exitCode); MONITOR_LOG("finished"); }
void KviIrcServer::save(KviConfigurationFile * pCfg, const QString & szPrefix) { QString szTmp; szTmp = QString("%1Hostname").arg(szPrefix); pCfg->writeEntry(szTmp,m_szHostname); szTmp = QString("%1Id").arg(szPrefix); pCfg->writeEntry(szTmp,m_szId); if(!m_szIp.isEmpty()) { szTmp = QString("%1Ip").arg(szPrefix); pCfg->writeEntry(szTmp,m_szIp); } if(!m_szDescription.isEmpty()) { szTmp = QString("%1Description").arg(szPrefix); pCfg->writeEntry(szTmp,m_szDescription); } if(!m_szUser.isEmpty()) { szTmp = QString("%1User").arg(szPrefix); pCfg->writeEntry(szTmp,m_szUser); } if(!m_szPass.isEmpty()) { szTmp = QString("%1Pass").arg(szPrefix); pCfg->writeEntry(szTmp,m_szPass); } if(!m_szNick.isEmpty()) { szTmp = QString("%1Nick").arg(szPrefix); pCfg->writeEntry(szTmp,m_szNick); } if(!m_szAlternativeNick.isEmpty()) { szTmp = QString("%1AlternativeNick").arg(szPrefix); pCfg->writeEntry(szTmp,m_szAlternativeNick); } if(!m_szSaslPass.isEmpty()) { szTmp = QString("%1SaslPass").arg(szPrefix); pCfg->writeEntry(szTmp,m_szSaslPass); } if(!m_szSaslNick.isEmpty()) { szTmp = QString("%1SaslNick").arg(szPrefix); pCfg->writeEntry(szTmp,m_szSaslNick); } if(!m_szRealName.isEmpty()) { szTmp = QString("%1RealName").arg(szPrefix); pCfg->writeEntry(szTmp,m_szRealName); } if(!m_szInitUMode.isEmpty()) { szTmp = QString("%1InitUMode").arg(szPrefix); pCfg->writeEntry(szTmp,m_szInitUMode); } if(autoJoinChannelList()) { szTmp = QString("%1AutoJoinChannels").arg(szPrefix); pCfg->writeEntry(szTmp,*(autoJoinChannelList())); } if(autoConnect()) // otherwise it defaults to false anyway { szTmp = QString("%1AutoConnect").arg(szPrefix); pCfg->writeEntry(szTmp,autoConnect()); } if(!m_szEncoding.isEmpty()) { szTmp = QString("%1Encoding").arg(szPrefix); pCfg->writeEntry(szTmp,m_szEncoding); } if(!m_szTextEncoding.isEmpty()) { szTmp = QString("%1TextEncoding").arg(szPrefix); pCfg->writeEntry(szTmp,m_szTextEncoding); } if(!m_szOnConnectCommand.isEmpty()) { szTmp = QString("%1OnConnectCommand").arg(szPrefix); pCfg->writeEntry(szTmp,m_szOnConnectCommand); } if(!m_szOnLoginCommand.isEmpty()) { szTmp = QString("%1OnLoginCommand").arg(szPrefix); pCfg->writeEntry(szTmp,m_szOnLoginCommand); } if(!m_szLinkFilter.isEmpty()) { szTmp = QString("%1LinkFilter").arg(szPrefix); pCfg->writeEntry(szTmp,m_szLinkFilter); } if(m_uPort != 6667) { szTmp = QString("%1Port").arg(szPrefix); pCfg->writeEntry(szTmp,m_uPort); } if(isIPv6()) { szTmp = QString("%1IPv6").arg(szPrefix); pCfg->writeEntry(szTmp,isIPv6()); } if(cacheIp()) { szTmp = QString("%1CacheIp").arg(szPrefix); pCfg->writeEntry(szTmp,cacheIp()); } if(useSSL()) { szTmp = QString("%1SSL").arg(szPrefix); pCfg->writeEntry(szTmp,useSSL()); } if(!enabledCAP()) { szTmp = QString("%1EnabledCAP").arg(szPrefix); pCfg->writeEntry(szTmp,enabledCAP()); } if(!enabledSTARTTLS()) { szTmp = QString("%1EnabledSTARTTLS").arg(szPrefix); pCfg->writeEntry(szTmp,enabledSTARTTLS()); } if(enabledSASL()) { szTmp = QString("%1EnabledSASL").arg(szPrefix); pCfg->writeEntry(szTmp,enabledSASL()); } if(proxy()!=-2) { szTmp = QString("%1Proxy").arg(szPrefix); pCfg->writeEntry(szTmp,proxy()); } if(!m_szUserIdentityId.isEmpty()) { szTmp = QString("%1UserIdentityId").arg(szPrefix); pCfg->writeEntry(szTmp,m_szUserIdentityId); } if(favorite()) { szTmp = QString("%1Favorite").arg(szPrefix); pCfg->writeEntry(szTmp,favorite()); } }
void ScriptableWorker::run() { if ( hasLogLevel(LogDebug) ) { bool isEval = m_args.length() == Arguments::Rest + 2 && m_args.at(Arguments::Rest) == "eval"; for (int i = Arguments::Rest + (isEval ? 1 : 0); i < m_args.length(); ++i) { QString indent = isEval ? QString("EVAL:") : (QString::number(i - Arguments::Rest + 1) + " "); foreach (const QByteArray &line, m_args.at(i).split('\n')) { SCRIPT_LOG( indent + getTextData(line) ); indent = " "; } } } bool ok; const quintptr id = m_args.at(Arguments::ActionId).toULongLong(&ok); QVariantMap data; if (ok) data = Action::data(id); const QString currentPath = getTextData(m_args.at(Arguments::CurrentPath)); QScriptEngine engine; ScriptableProxy proxy(m_wnd, data); Scriptable scriptable(&proxy); scriptable.initEngine(&engine, currentPath, data); if (m_socket) { QObject::connect( proxy.signaler(), SIGNAL(sendMessage(QByteArray,int)), m_socket, SLOT(sendMessage(QByteArray,int)) ); QObject::connect( &scriptable, SIGNAL(sendMessage(QByteArray,int)), m_socket, SLOT(sendMessage(QByteArray,int)) ); QObject::connect( m_socket, SIGNAL(messageReceived(QByteArray,int)), &scriptable, SLOT(setInput(QByteArray)) ); QObject::connect( m_socket, SIGNAL(disconnected()), &scriptable, SLOT(abort()) ); QObject::connect( &scriptable, SIGNAL(destroyed()), m_socket, SLOT(deleteAfterDisconnected()) ); if ( m_socket->isClosed() ) { SCRIPT_LOG("TERMINATED"); return; } m_socket->start(); } QObject::connect( &scriptable, SIGNAL(requestApplicationQuit()), qApp, SLOT(quit()) ); QByteArray response; int exitCode; if ( m_args.length() <= Arguments::Rest ) { SCRIPT_LOG("Error: bad command syntax"); exitCode = CommandBadSyntax; } else { const QString cmd = getTextData( m_args.at(Arguments::Rest) ); #ifdef HAS_TESTS if ( cmd == "flush" && m_args.length() == Arguments::Rest + 2 ) { log( "flush ID: " + getTextData(m_args.at(Arguments::Rest + 1)), LogAlways ); scriptable.sendMessageToClient(QByteArray(), CommandFinished); return; } #endif QScriptValue fn = engine.globalObject().property(cmd); if ( !fn.isFunction() ) { SCRIPT_LOG("Error: unknown command"); const QString msg = Scriptable::tr("Name \"%1\" doesn't refer to a function.").arg(cmd); response = createLogMessage(msg, LogError).toUtf8(); exitCode = CommandError; } else { /* Special arguments: * "-" read this argument from stdin * "--" read all following arguments without control sequences */ QScriptValueList fnArgs; bool readRaw = false; for ( int i = Arguments::Rest + 1; i < m_args.length(); ++i ) { const QByteArray &arg = m_args.at(i); if (!readRaw && arg == "--") { readRaw = true; } else { const QScriptValue value = readRaw || arg != "-" ? scriptable.newByteArray(arg) : scriptable.input(); fnArgs.append(value); } } engine.evaluate(m_pluginScript); QScriptValue result = fn.call(QScriptValue(), fnArgs); if ( engine.hasUncaughtException() ) { const QString exceptionText = QString("%1\n--- backtrace ---\n%2\n--- end backtrace ---") .arg( engine.uncaughtException().toString(), engine.uncaughtExceptionBacktrace().join("\n") ); SCRIPT_LOG( QString("Error: Exception in command \"%1\": %2") .arg(cmd, exceptionText) ); response = createLogMessage(exceptionText, LogError).toUtf8(); exitCode = CommandError; } else { response = serializeScriptValue(result); exitCode = CommandFinished; } } } scriptable.sendMessageToClient(response, exitCode); SCRIPT_LOG("DONE"); }
static struct PCP_new_eventid *readnewevent(struct PCP *pcp) { struct PCP_save_event se; struct readnewevent_s rne; struct PCP_new_eventid *ne; const char *cp; struct proxy_list *p; int first_save=1; if (!deleted_eventid) proxy_list_rset(); /* Open new proxy connections */ while ((cp=strtok(NULL, " ")) != NULL) { char *errmsg, *q; char *n=strdup(cp); struct proxy_list *pcp; if (!n) { syslog(LOG_ALERT, "Out of memory."); exit(1); } if (proxy_userid) { printf("500-Cannot create proxy in proxy mode.\n"); free(n); errno=EIO; return (NULL); } strcpy(n, cp); pcp=proxy(n, &errmsg); if (pcp) { pcp->flags |= PROXY_NEW; free(n); continue; } if (force_flag) { pcp->flags |= PROXY_IGNORE; free(n); continue; } while (errmsg && (q=strchr(errmsg, '\n')) != 0) *q='/'; printf("500-%s: %s\n", n, errmsg ? errmsg:"Failed to create a proxy connection."); free(n); proxy_list_rset(); return (NULL); } memset(&se, 0, sizeof(se)); if ((rne.tmpfile=tmpfile()) == NULL) return (NULL); time(&rne.last_noop_time); rne.seeneol=1; rne.seendot=0; rne.seeneof=0; rne.cnt=0; rne.pcp=pcp; pcpdtimer_init(&rne.inactivity_timeout); rne.inactivity_timeout.handler=&inactive; pcpdtimer_install(&rne.inactivity_timeout, 300); for (p=proxy_list; p; p=p->next) { struct PCP_save_event se; if ( !(p->flags & PROXY_NEW)) continue; if (fseek(rne.tmpfile, 0L, SEEK_SET) < 0 || lseek(fileno(rne.tmpfile), 0L, SEEK_SET) < 0) { int save_errno=errno; proxy_list_rset(); pcpdtimer_triggered(&rne.inactivity_timeout); fclose(rne.tmpfile); errno=save_errno; return (NULL); } memset(&se, 0, sizeof(se)); if (first_save) { se.write_event_func_misc_ptr= &rne; se.write_event_func=readnewevent_callback; } else se.write_event_fd=fileno(rne.tmpfile); if ((p->newevent=pcp_new_eventid(p->proxy, p->old_event_id, &se)) == NULL) { pcpdtimer_triggered(&rne.inactivity_timeout); if (force_flag) { /* Force it through */ p->flags &= ~PROXY_NEW; p->flags |= PROXY_IGNORE; continue; } proxy_error(p->userid, pcp_errmsg(p->proxy)); proxy_list_rset(); fclose(rne.tmpfile); errno=EIO; return (NULL); } if (first_save) pcpdtimer_triggered(&rne.inactivity_timeout); first_save=0; } if (first_save) { se.write_event_func_misc_ptr= &rne; se.write_event_func=readnewevent_callback; } else se.write_event_fd=fileno(rne.tmpfile); if (mkparticipants(&se) || fseek(rne.tmpfile, 0L, SEEK_SET) < 0 || lseek(fileno(rne.tmpfile), 0L, SEEK_SET) < 0) { int save_errno=errno; proxy_list_rset(); fclose(rne.tmpfile); errno=save_errno; return (NULL); } if ((ne=pcp_new_eventid(pcp, deleted_eventid, &se)) == NULL) { while (!rne.seeneof) { char buf[512]; readnewevent_callback(buf, sizeof(buf), &se); } } pcpdtimer_triggered(&rne.inactivity_timeout); if (first_save) { if (fflush(rne.tmpfile) || ferror(rne.tmpfile)) { int save_errno=errno; proxy_list_rset(); fclose(rne.tmpfile); errno=save_errno; return (NULL); } } notbooked=1; fclose(rne.tmpfile); return (ne); }
void Phantom::init() { if (m_config.helpFlag()) { Terminal::instance()->cout(QString("%1").arg(m_config.helpText())); Terminal::instance()->cout("Any of the options that accept boolean values ('true'/'false') can also accept 'yes'/'no'."); Terminal::instance()->cout(""); Terminal::instance()->cout("Without any argument, PhantomJS will launch in interactive mode (REPL)."); Terminal::instance()->cout(""); Terminal::instance()->cout("Documentation can be found at the web site, http://phantomjs.org."); Terminal::instance()->cout(""); m_terminated = true; return; } if (m_config.versionFlag()) { m_terminated = true; Terminal::instance()->cout(QString("%1").arg(PHANTOMJS_VERSION_STRING)); return; } if (!m_config.unknownOption().isEmpty()) { Terminal::instance()->cerr(m_config.unknownOption()); m_terminated = true; return; } // Initialize the CookieJar CookieJar::instance(m_config.cookiesFile()); m_page = new WebPage(this, QUrl::fromLocalFile(m_config.scriptFile())); m_pages.append(m_page); QString proxyType = m_config.proxyType(); if (proxyType != "none") { if (m_config.proxyHost().isEmpty()) { QNetworkProxyFactory::setUseSystemConfiguration(true); } else { QNetworkProxy::ProxyType networkProxyType = QNetworkProxy::HttpProxy; if (proxyType == "socks5") { networkProxyType = QNetworkProxy::Socks5Proxy; } if(!m_config.proxyAuthUser().isEmpty() && !m_config.proxyAuthPass().isEmpty()) { QNetworkProxy proxy(networkProxyType, m_config.proxyHost(), m_config.proxyPort(), m_config.proxyAuthUser(), m_config.proxyAuthPass()); QNetworkProxy::setApplicationProxy(proxy); } else { QNetworkProxy proxy(networkProxyType, m_config.proxyHost(), m_config.proxyPort()); QNetworkProxy::setApplicationProxy(proxy); } } } // Set output encoding Terminal::instance()->setEncoding(m_config.outputEncoding()); // Set script file encoding m_scriptFileEnc.setEncoding(m_config.scriptEncoding()); connect(m_page, SIGNAL(javaScriptConsoleMessageSent(QString)), SLOT(printConsoleMessage(QString))); connect(m_page, SIGNAL(initialized()), SLOT(onInitialized())); m_defaultPageSettings[PAGE_SETTINGS_LOAD_IMAGES] = QVariant::fromValue(m_config.autoLoadImages()); m_defaultPageSettings[PAGE_SETTINGS_CLEAR_MEMORY_CACHES] = QVariant::fromValue(false); m_defaultPageSettings[PAGE_SETTINGS_JS_ENABLED] = QVariant::fromValue(true); m_defaultPageSettings[PAGE_SETTINGS_XSS_AUDITING] = QVariant::fromValue(false); m_defaultPageSettings[PAGE_SETTINGS_USER_AGENT] = QVariant::fromValue(m_page->userAgent()); m_defaultPageSettings[PAGE_SETTINGS_LOCAL_ACCESS_REMOTE] = QVariant::fromValue(m_config.localToRemoteUrlAccessEnabled()); m_defaultPageSettings[PAGE_SETTINGS_WEB_SECURITY_ENABLED] = QVariant::fromValue(m_config.webSecurityEnabled()); m_defaultPageSettings[PAGE_SETTINGS_JS_CAN_OPEN_WINDOWS] = QVariant::fromValue(m_config.javascriptCanOpenWindows()); m_defaultPageSettings[PAGE_SETTINGS_JS_CAN_CLOSE_WINDOWS] = QVariant::fromValue(m_config.javascriptCanCloseWindows()); m_page->applySettings(m_defaultPageSettings); setLibraryPath(QFileInfo(m_config.scriptFile()).dir().absolutePath()); }
//Punto de entrada al programa int main(int argc, char **argv){ //Con esto redirigimos STDERR_FILENO --> STDOUT_FILENO dup2(STDOUT_FILENO, STDERR_FILENO); //dup2(1, 2); int buf[tamano]; int dfifos, dfifoe, numbytes; char nombrefifoe[longnombre], nombrefifos[longnombre]; setbuf(stdout, NULL); if (argc != 2) { printf ("Uso: %s <nombre_fifo>\n",argv[0]); exit(1); } // Compone los nombres de los FIFOs conocidos a partir del parametro, // uno de entrada y otro de salida (desde el punto de vista del servidor). sprintf(nombrefifoe,"%se",argv[1]); sprintf(nombrefifos,"%ss",argv[1]); //borramos los archivos fifo por si existieran previamente unlink(nombrefifoe); unlink(nombrefifos); int pid; umask(0); //Creamos un cauce con nombre para la entrada if((mkfifo(nombrefifoe, 0777)) == -1){ perror("Error en mkfifo\n"); exit(EXIT_FAILURE); } //Creamos un cauce con nombre para la salida if((mkfifo(nombrefifos, 0777)) == -1){ perror("Error en mkfifo\n"); exit(EXIT_FAILURE); } printf ("crear caucd salida\n"); //Abrimos los cauces dfifos=open(nombrefifos,O_RDWR); dfifoe=open(nombrefifoe,O_RDWR); printf ("creados\n"); numbytes=read(dfifos,buf,sizeof(buf)); while(numbytes>0){ printf ("Leyendo fifo salida\n"); pid=fork(); if(pid==0){ //Hijo proxy(getpid()); } else if (pid > 0) { //Padre printf("padre pid es %d\n",pid); if(write(dfifoe,&pid,sizeof(int))<0){ perror("Error en write\n"); exit(EXIT_FAILURE); } } else if (pid == -1) { perror("fallo en fork\n"); exit(EXIT_FAILURE); } numbytes=read(dfifos,buf,sizeof(buf)); } if(numbytes==-1){ perror("\nError en read\n"); exit(EXIT_FAILURE); } pid = wait(NULL); while (pid > 0) { pid = wait(NULL); } /* si hay error, ignoramos si no hay más hijos a esperar. */ if (pid == -1 && errno != ECHILD) { perror("fallo en wait"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
int wmain(int argc, wchar_t* argv[]) { //::MessageBox(NULL, L"Stop here", L"STOP!", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON3); std:cout << "Edge Diagnostics Adapter" << std::endl; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Prints this help text.") ("launch,l", po::value<string>(), "Launches Edge. Optionally at the URL specified in the value") ("killall,k", "Kills all running Edge processes.") ("chrome,c", "Launches Crhome in the background to serve the Chrome Developer Tools frontend.") ("port,p", po::value<string>(), "The port number to listen on. Default is 9222."); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << desc << std::endl; return E_FAIL; } if (vm.count("help")) { std::cout << desc << std::endl; return S_OK; } // Initialize COM and deinitialize when we go out of scope HRESULT hrCoInit = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); shared_ptr<HRESULT> spCoInit(&hrCoInit, [](const HRESULT* hrCom) -> void { if (SUCCEEDED(*hrCom)) { ::CoUninitialize(); } }); { // Set a close handler to shutdown the chrome instance we launch ::SetConsoleCtrlHandler(OnClose, TRUE); // Launch chrome if (vm.count("chrome")) { CString chromePath; // Find the chrome install location via the registry CString keyPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"; CRegKey regKey; // First see if we can find where Chrome is installed from the registry. This will only succeed if Chrome is installed for all users if (regKey.Open(HKEY_LOCAL_MACHINE, keyPath, KEY_READ) == ERROR_SUCCESS) { ULONG bufferSize = MAX_PATH; CString path; LRESULT result = regKey.QueryStringValue(nullptr, path.GetBufferSetLength(bufferSize), &bufferSize); path.ReleaseBufferSetLength(bufferSize); if (result == ERROR_SUCCESS) { chromePath = path; } } if (chromePath.GetLength() == 0) { // If Chrome is only installed for the current user, look in \AppData\Local\Google\Chrome\Application\ for Chrome.exe CString appPath; ::SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appPath.GetBuffer(MAX_PATH + 1)); appPath.ReleaseBuffer(); chromePath = appPath + L"\\Google\\Chrome\\Application\\chrome.exe"; } // Get a temp location CString temp; Helpers::ExpandEnvironmentString(L"%Temp%", temp); // Set arguments for the chrome that we launch CString arguments; arguments.Format(L"about:blank --remote-debugging-port=9223 --window-size=0,0 --silent-launch --no-first-run --no-default-browser-check --user-data-dir=\"%s\"", temp); // Launch the process STARTUPINFO si = { 0 }; PROCESS_INFORMATION pi = { 0 }; si.cb = sizeof(si); si.wShowWindow = SW_MINIMIZE; BOOL result = ::CreateProcess( chromePath, arguments.GetBuffer(), nullptr, nullptr, FALSE, 0, nullptr, temp, &si, &pi); arguments.ReleaseBuffer(); if (result) { // Store the handles CHandle hThread(pi.hThread); hChromeProcess.Attach(pi.hProcess); DWORD waitResult = ::WaitForInputIdle(hChromeProcess, 30000); } else { std::cerr << "Could not open Chrome. Please ensure that Chrome is installed." << std::endl; system("pause"); return -1; } } // Kill all Edge instances if their is an aegument /killall if (vm.count("killall")) { //killAllProcessByExe(L"MicrosoftEdgeCP.exe"); Helpers::KillAllProcessByExe(L"MicrosoftEdge.exe"); } // Launch Edge if their is an argument set /launch:<url> if (vm.count("launch")) { CString url(vm["launch"].as<string>().c_str()); if (url.GetLength() == 0) { url = L"https://www.bing.com"; } HRESULT hr = Helpers::OpenUrlInMicrosoftEdge(url); if (FAILED(hr)) { std::cout << L"Failed to launch Microsoft Edge"; } } string port = EdgeDiagnosticsAdapter::s_Default_Port; if (vm.count("port")) { port = vm["port"].as<string>(); } // We don't care if this fails as the developer can set it manually. setSecurityACLs(); // We don't care if this fails or not as maybe the developer wants to do something that won't hit the PLM. In case errors went to the console. setEdgeForDebugging(true); // Load the proxy server EdgeDiagnosticsAdapter proxy(getPathToCurrentExeContainer(), port); if (proxy.IsServerRunning) { // Create a message pump MSG msg; ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); // Thread message loop BOOL getMessageRet; while ((getMessageRet = ::GetMessage(&msg, NULL, 0, 0)) != 0) { if (getMessageRet != -1) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } } // Leave the window open so we can read the log file wcout << endl << L"Press [ENTER] to exit." << endl; cin.ignore(); } else { wcout << L"Error starting. Quiting."; return E_FAIL; } } return S_OK; }
void setupProxy() { QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy; QString proxyHost; quint64 proxyPort = 0; QString proxyUser; QString proxyPassword; const QStringList args = QCoreApplication::arguments(); Q_FOREACH(QString arg, args) { static const QString kProxyTypeArg = "--proxy-type="; static const QString kProxyHostArg = "--proxy-host="; static const QString kProxyPortArg = "--proxy-port="; static const QString kProxyUserArg = "--proxy-user="******"--proxy-password="******"socks5") { proxyType = QNetworkProxy::Socks5Proxy; } else if(proxyTypeStr == "http") { proxyType = QNetworkProxy::HttpProxy; } else { throw InvalidArgException("Invalid '" + kProxyTypeArg + "' parameter"); } } else if(arg.startsWith(kProxyHostArg)) { proxyHost = arg.remove(kProxyHostArg).simplified(); } else if(arg.startsWith(kProxyPortArg)) { bool ok; proxyPort = arg.remove(kProxyPortArg).simplified().toUShort(&ok); if(!ok) { throw InvalidArgException("Invalid '" + kProxyPortArg + "' parameter"); } if(proxyPort == 0) { throw InvalidArgException("Proxy port is set to 0"); } } else if(arg.startsWith(kProxyUserArg)) { proxyUser = arg.remove(kProxyUserArg).simplified(); } else if(arg.startsWith(kProxyPasswordArg)) { proxyPassword = arg.remove(kProxyPasswordArg).simplified(); } } if(proxyHost.isEmpty()) { return; } if(proxyUser.isEmpty() != proxyPassword.isEmpty()) // Logical XOR :-) { throw InvalidArgException("Invalid proxy authorization parameters"); } QNetworkProxy proxy(proxyType, proxyHost, proxyPort, proxyUser, proxyPassword); QNetworkProxy::setApplicationProxy(proxy); }
QRect DarkBlueStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex* opt, SubControl sc, const QWidget* widget) const { switch(cc) { case CC_GroupBox: { const QStyleOptionGroupBox* groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt); int m = 5; int titleH = 20; switch(sc) { case SC_GroupBoxFrame: { return groupBox->rect; } case SC_GroupBoxContents: { return groupBox->rect.adjusted(m, titleH + m, -m, -m); } case SC_GroupBoxCheckBox: { int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, opt, widget); int indicatorHeight = proxy()->pixelMetric(PM_IndicatorHeight, opt, widget); QRect r = groupBox->rect; r.setLeft(r.left() + m); r.setTop(r.top() + (titleH - indicatorHeight)/2); r.setWidth(indicatorWidth); r.setHeight(indicatorHeight); return r; } case SC_GroupBoxLabel: { QFontMetrics fontMetrics = groupBox->fontMetrics; int w = fontMetrics.size(Qt::TextShowMnemonic, groupBox->text + QLatin1Char(' ')).width(); int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, opt, widget); int indicatorSpace = proxy()->pixelMetric(PM_CheckBoxLabelSpacing, opt, widget) - 1; bool hasCheckBox = groupBox->subControls & QStyle::SC_GroupBoxCheckBox; QRect r = groupBox->rect; r.setLeft(r.left() + m); r.setWidth(w); r.setHeight(titleH); if(hasCheckBox) r.setLeft(r.left() + indicatorWidth + indicatorSpace); return r; } default: break; } } default: { return mStyle->subControlRect(cc, opt, sc, widget); } } }
void Phantom::init() { if (m_config.helpFlag()) { m_terminated = true; Utils::showUsage(); return; } if (m_config.versionFlag()) { m_terminated = true; Terminal::instance()->cout(QString("%1").arg(PHANTOMJS_VERSION_STRING)); return; } if (!m_config.unknownOption().isEmpty()) { Terminal::instance()->cerr(m_config.unknownOption()); m_terminated = true; return; } m_page = new WebPage(this, QUrl::fromLocalFile(m_config.scriptFile())); m_pages.append(m_page); if (m_config.proxyHost().isEmpty()) { QNetworkProxyFactory::setUseSystemConfiguration(true); } else { QString proxyType = m_config.proxyType(); QNetworkProxy::ProxyType networkProxyType = QNetworkProxy::HttpProxy; if (proxyType == "socks5") { networkProxyType = QNetworkProxy::Socks5Proxy; } if(!m_config.proxyAuthUser().isEmpty() && !m_config.proxyAuthPass().isEmpty()) { QNetworkProxy proxy(networkProxyType, m_config.proxyHost(), m_config.proxyPort(), m_config.proxyAuthUser(), m_config.proxyAuthPass()); QNetworkProxy::setApplicationProxy(proxy); } else { QNetworkProxy proxy(networkProxyType, m_config.proxyHost(), m_config.proxyPort()); QNetworkProxy::setApplicationProxy(proxy); } } // Set output encoding Terminal::instance()->setEncoding(m_config.outputEncoding()); // Set script file encoding m_scriptFileEnc.setEncoding(m_config.scriptEncoding()); connect(m_page, SIGNAL(javaScriptConsoleMessageSent(QString)), SLOT(printConsoleMessage(QString))); connect(m_page, SIGNAL(initialized()), SLOT(onInitialized())); m_defaultPageSettings[PAGE_SETTINGS_LOAD_IMAGES] = QVariant::fromValue(m_config.autoLoadImages()); m_defaultPageSettings[PAGE_SETTINGS_JS_ENABLED] = QVariant::fromValue(true); m_defaultPageSettings[PAGE_SETTINGS_XSS_AUDITING] = QVariant::fromValue(false); m_defaultPageSettings[PAGE_SETTINGS_USER_AGENT] = QVariant::fromValue(m_page->userAgent()); m_defaultPageSettings[PAGE_SETTINGS_LOCAL_ACCESS_REMOTE] = QVariant::fromValue(m_config.localToRemoteUrlAccessEnabled()); m_defaultPageSettings[PAGE_SETTINGS_WEB_SECURITY_ENABLED] = QVariant::fromValue(m_config.webSecurityEnabled()); m_defaultPageSettings[PAGE_SETTINGS_JS_CAN_OPEN_WINDOWS] = QVariant::fromValue(m_config.javascriptCanOpenWindows()); m_defaultPageSettings[PAGE_SETTINGS_JS_CAN_CLOSE_WINDOWS] = QVariant::fromValue(m_config.javascriptCanCloseWindows()); m_page->applySettings(m_defaultPageSettings); setLibraryPath(QFileInfo(m_config.scriptFile()).dir().absolutePath()); }
void QuickInterpreter::init() { m_dynamic_slots = new QSMetaObject(this); qsa_setup_meta_objects(); debuggerEngine()->clear(); staticGlobals.clear(); staticGlobals << QString::fromLatin1("NaN") << QString::fromLatin1("undefined") << QString::fromLatin1("Infinity") << QString::fromLatin1("Application"); // add some common objects to the Global object QSObject global(env()->globalObject()); QSClass *objClass = env()->objectClass(); wrpClass = new QSWrapperClass(objClass); ptrClass = new QSPointerClass(objClass); varClass = new QSVariantClass(objClass); appClass = new QSApplicationClass(objClass); global.put(QString::fromLatin1("Application"), appClass->createWritable()); pntClass = new QSPointClass(objClass, this); registerType(pntClass); sizClass = new QSSizeClass(objClass, this); registerType(sizClass); rctClass = new QSRectClass(objClass, this); registerType(rctClass); baClass = new QSByteArrayClass(objClass); registerType(baClass); #ifndef QSA_NO_GUI colClass = new QSColorClass(objClass); registerType(colClass); fntClass = new QSFontClass(objClass); registerType(fntClass); pixClass = new QSPixmapClass(objClass, this); registerType(pixClass); palClass = new QSPaletteClass(objClass); registerType(palClass); colGrpClass = new QSColorGroupClass(objClass); registerType(colGrpClass); #endif enableDebug(); // adds "debug" function which uses qDebug() // // env()->globalClass()->addMember(QString::fromLatin1("connect"), QSMember(qsa_connect)); env()->globalClass()->addMember(QString::fromLatin1("disconnect"), QSMember(qsa_disconnect)); env()->globalClass()->addMember(QString::fromLatin1("startTimer"), QSMember(qsStartTimer)); env()->globalClass()->addMember(QString::fromLatin1("killTimer"), QSMember(qsKillTimer)); env()->globalClass()->addMember(QString::fromLatin1("killTimers"), QSMember(qsKillTimers)); QMap<QString,QObject*> statDescr = factory->staticDescriptors(); QMap<QString,QString> instDescr = factory->instanceDescriptors(); QList<QString> features = instDescr.keys(); for (QList<QString>::ConstIterator it = features.begin(); it != features.end(); ++it) { if (env()->globalClass()->definedMembers()->contains(*it)) { qWarning("QSObjectFactory: Trying to register existing class: '%s'", (*it).toLatin1().constData()); continue; } QSObject staticInst; if(statDescr.contains(*it)) { // has static? QObject *sinst = statDescr[ *it ]; Q_ASSERT(sinst); staticInst = wrap(sinst); statDescr.remove(*it); } QSObjectConstructor *constr = new QSObjectConstructor(objClass, *it); QSFactoryObjectProxy *ptype = new QSFactoryObjectProxy(env()->typeClass(), staticInst, constr); constr->setFactoryObjectProxy(ptype); QSObject proxy(ptype, env()->typeClass()->createTypeShared(constr)); env()->globalClass()->addStaticVariableMember(constr->identifier(), proxy, AttributeExecutable); } for(QMap<QString,QObject*>::ConstIterator sit = statDescr.begin(); sit != statDescr.end(); ++sit) { if (env()->globalClass()->definedMembers()->contains(sit.key())) { qWarning("QSObjectFactory: Trying to register existing class: '%s'", sit.key().toLatin1().constData()); continue; } QSObject staticInst; QObject *sinst = statDescr[ sit.key() ]; Q_ASSERT(sinst); staticInst = wrap(sinst); env()->globalClass()->addStaticVariableMember(sit.key(), staticInst, AttributeNone); } }
// public: Phantom::Phantom(QObject *parent) : REPLCompletable(parent) , m_terminated(false) , m_returnValue(0) , m_filesystem(0) , m_system(0) { // second argument: script name QStringList args = QApplication::arguments(); // Skip the first argument, i.e. the application executable (phantomjs). args.removeFirst(); m_config.init(&args); if (m_config.helpFlag()) { m_terminated = true; Utils::showUsage(); return; } if (m_config.versionFlag()) { m_terminated = true; Terminal::instance()->cout(QString("%1").arg(PHANTOMJS_VERSION_STRING)); return; } if (!m_config.unknownOption().isEmpty()) { Terminal::instance()->cerr(m_config.unknownOption()); m_terminated = true; return; } m_page = new WebPage(this, &m_config, QUrl::fromLocalFile(m_config.scriptFile())); m_pages.append(m_page); if (m_config.proxyHost().isEmpty()) { QNetworkProxyFactory::setUseSystemConfiguration(true); } else { QString proxyType = m_config.proxyType(); QNetworkProxy::ProxyType networkProxyType = QNetworkProxy::HttpProxy; if (proxyType == "socks5") { networkProxyType = QNetworkProxy::Socks5Proxy; } if(!m_config.proxyAuthUser().isEmpty() && !m_config.proxyAuthPass().isEmpty()) { QNetworkProxy proxy(networkProxyType, m_config.proxyHost(), m_config.proxyPort(), m_config.proxyAuthUser(), m_config.proxyAuthPass()); QNetworkProxy::setApplicationProxy(proxy); } else { QNetworkProxy proxy(networkProxyType, m_config.proxyHost(), m_config.proxyPort()); QNetworkProxy::setApplicationProxy(proxy); } } // Set output encoding Terminal::instance()->setEncoding(m_config.outputEncoding()); // Set script file encoding m_scriptFileEnc.setEncoding(m_config.scriptEncoding()); connect(m_page, SIGNAL(javaScriptConsoleMessageSent(QString)), SLOT(printConsoleMessage(QString))); connect(m_page, SIGNAL(initialized()), SLOT(onInitialized())); m_defaultPageSettings[PAGE_SETTINGS_LOAD_IMAGES] = QVariant::fromValue(m_config.autoLoadImages()); m_defaultPageSettings[PAGE_SETTINGS_LOAD_PLUGINS] = QVariant::fromValue(m_config.pluginsEnabled()); m_defaultPageSettings[PAGE_SETTINGS_JS_ENABLED] = QVariant::fromValue(true); m_defaultPageSettings[PAGE_SETTINGS_XSS_AUDITING] = QVariant::fromValue(false); m_defaultPageSettings[PAGE_SETTINGS_USER_AGENT] = QVariant::fromValue(m_page->userAgent()); m_defaultPageSettings[PAGE_SETTINGS_LOCAL_ACCESS_REMOTE] = QVariant::fromValue(m_config.localToRemoteUrlAccessEnabled()); m_defaultPageSettings[PAGE_SETTINGS_WEB_SECURITY_ENABLED] = QVariant::fromValue(m_config.webSecurityEnabled()); m_page->applySettings(m_defaultPageSettings); setLibraryPath(QFileInfo(m_config.scriptFile()).dir().absolutePath()); }
void BreakpointListView::WatchpointChanged(Watchpoint* watchpoint) { BreakpointProxy proxy(NULL, watchpoint); fBreakpointsTableModel->UpdateBreakpoint(&proxy); }
StreamWindow::StreamWindow(QWidget *parent) : QWidget(parent) { ui.setupUi(this); setWindowFlags(Qt::Window); setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_QuitOnClose, false); m_requestReply = 0; //buttons ui.addPushButton->setIcon(QIcon::fromTheme("list-add")); ui.updatePushButton->setIcon(QIcon::fromTheme("view-refresh")); //icecast model m_iceCastModel = new QStandardItemModel(this); m_iceCastModel->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Genre") << tr("Bitrate") << tr("Format")); m_iceCastFilterModel = new StreamsProxyModel(this); m_iceCastFilterModel->setSourceModel(m_iceCastModel); m_iceCastFilterModel->setDynamicSortFilter(true); m_iceCastFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); //icecast table ui.icecastTableView->setModel(m_iceCastFilterModel); ui.icecastTableView->verticalHeader()->setDefaultSectionSize(fontMetrics().height()); ui.icecastTableView->verticalHeader()->setResizeMode(QHeaderView::Fixed); ui.icecastTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui.icecastTableView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui.icecastTableView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(execIceCastMenu(QPoint))); //favorites model m_favoritesModel = new QStandardItemModel(this); m_favoritesModel->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Genre") << tr("Bitrate") << tr("Format")); m_favoritesFilterModel = new StreamsProxyModel(this); m_favoritesFilterModel->setSourceModel(m_favoritesModel); m_favoritesFilterModel->setDynamicSortFilter(true); m_favoritesFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); //favorites table ui.favoritesTableView->setModel(m_favoritesFilterModel); ui.favoritesTableView->verticalHeader()->setDefaultSectionSize(fontMetrics().height()); ui.favoritesTableView->verticalHeader()->setResizeMode(QHeaderView::Fixed); ui.favoritesTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui.favoritesTableView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui.favoritesTableView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(execFavoritesMenu(QPoint))); ui.statusLabel->hide(); m_http = new QNetworkAccessManager(this); //load global proxy settings QmmpSettings *gs = QmmpSettings::instance(); if (gs->isProxyEnabled()) { QNetworkProxy proxy(QNetworkProxy::HttpProxy, gs->proxy().host(), gs->proxy().port()); if(gs->useProxyAuth()) { proxy.setUser(gs->proxy().userName()); proxy.setPassword(gs->proxy().password()); } m_http->setProxy(proxy); } connect(m_http, SIGNAL(finished (QNetworkReply *)), SLOT(showText(QNetworkReply *))); //read settings QSettings settings(Qmmp::configFile(), QSettings::IniFormat); settings.beginGroup("StreamBrowser"); restoreGeometry(settings.value("geometry").toByteArray()); ui.icecastTableView->horizontalHeader()->restoreState(settings.value("icecast_headers").toByteArray()); ui.favoritesTableView->horizontalHeader()->restoreState(settings.value("favorites_headers").toByteArray()); ui.tabWidget->setCurrentIndex(settings.value("current_tab", 1).toInt()); settings.endGroup(); //create cache dir QDir dir(Qmmp::configDir()); if(!dir.exists("streambrowser")) dir.mkdir("streambrowser"); //read cache QFile file(Qmmp::configDir() + "/streambrowser/icecast.xml"); if(file.open(QIODevice::ReadOnly)) readXml(&file, m_iceCastModel); else on_updatePushButton_clicked(); QFile file2(Qmmp::configDir() + "/streambrowser/favorites.xml"); if(file2.open(QIODevice::ReadOnly)) readXml(&file2, m_favoritesModel); //create menus m_iceCastMenu = new QMenu(this); m_iceCastMenu->addAction(tr("&Add to favorites"), this, SLOT(addToFavorites())); QAction *addAction = m_iceCastMenu->addAction(tr("&Add to playlist"), this, SLOT(on_addPushButton_clicked())); m_favoritesMenu = new QMenu(this); m_favoritesMenu->addAction(addAction); m_favoritesMenu->addSeparator(); m_favoritesMenu->addAction(tr("&Remove"), this, SLOT(removeFromFavorites()), QKeySequence::Delete); addActions(m_favoritesMenu->actions()); }
// public: Phantom::Phantom(QObject *parent) : QObject(parent) , m_terminated(false) , m_returnValue(0) , m_netAccessMan(0) , m_filesystem(0) { // second argument: script name QStringList args = QApplication::arguments(); // Skip the first argument, i.e. the application executable (phantomjs). args.removeFirst(); m_config.init(&args); if (m_config.versionFlag()) { m_terminated = true; Terminal::instance()->cout(QString("%1 (development)").arg(PHANTOMJS_VERSION_STRING)); return; } if (!m_config.unknownOption().isEmpty()) { Terminal::instance()->cerr(m_config.unknownOption()); m_terminated = true; return; } m_page = new WebPage(this); m_pages.append(m_page); if (m_config.scriptFile().isEmpty()) { Utils::showUsage(); return; } if (m_config.proxyHost().isEmpty()) { QNetworkProxyFactory::setUseSystemConfiguration(true); } else { QNetworkProxy proxy(QNetworkProxy::HttpProxy, m_config.proxyHost(), m_config.proxyPort()); QNetworkProxy::setApplicationProxy(proxy); } // Set output encoding Terminal::instance()->setEncoding(m_config.outputEncoding()); // Set script file encoding m_scriptFileEnc.setEncoding(m_config.scriptEncoding()); // Provide WebPage with a non-standard Network Access Manager m_netAccessMan = new NetworkAccessManager(this, m_config.diskCacheEnabled(), m_config.cookieFile(), m_config.ignoreSslErrors(), m_config.authUser(), m_config.authPass(), m_config.maxDiskCacheSize()); m_page->setNetworkAccessManager(m_netAccessMan); connect(m_page, SIGNAL(javaScriptConsoleMessageSent(QString, int, QString)), SLOT(printConsoleMessage(QString, int, QString))); m_defaultPageSettings[PAGE_SETTINGS_LOAD_IMAGES] = QVariant::fromValue(m_config.autoLoadImages()); m_defaultPageSettings[PAGE_SETTINGS_LOAD_PLUGINS] = QVariant::fromValue(m_config.pluginsEnabled()); m_defaultPageSettings[PAGE_SETTINGS_JS_ENABLED] = QVariant::fromValue(true); m_defaultPageSettings[PAGE_SETTINGS_XSS_AUDITING] = QVariant::fromValue(false); m_defaultPageSettings[PAGE_SETTINGS_USER_AGENT] = QVariant::fromValue(m_page->userAgent()); m_defaultPageSettings[PAGE_SETTINGS_LOCAL_ACCESS_REMOTE] = QVariant::fromValue(m_config.localToRemoteUrlAccessEnabled()); m_page->applySettings(m_defaultPageSettings); setLibraryPath(QFileInfo(m_config.scriptFile()).dir().absolutePath()); // Add 'phantom' and 'fs' object to the global scope m_page->mainFrame()->addToJavaScriptWindowObject("phantom", this); // Load all the required JavaScript 'shims' QString jsShims[1] = { ":/bootstrap.js" }; for (int i = 0, len = 1; i < len; ++i) { QFile f(jsShims[i]); f.open(QFile::ReadOnly); //< It's OK to assume this succeed. If it doesn't, we have a bigger problem. m_page->mainFrame()->evaluateJavaScript(QString::fromUtf8(f.readAll())); } }
void CollisionMesh::loadImpl (void) { APP_ASSERT(masterShape==NULL); Ogre::DataStreamPtr file; try { file = Ogre::ResourceGroupManager::getSingleton().openResource(name.substr(1), "GRIT"); } catch (Ogre::Exception &e) { GRIT_EXCEPT(e.getDescription()); } std::string ext = name.substr(name.length()-5); uint32_t fourcc = 0; for (int i=0 ; i<4 ; ++i) { unsigned char c; file->read(&c, 1); fourcc |= c << (i*8); } file->seek(0); std::string dir = grit_dirname(name); const btVector3 ZV(0,0,0); const btQuaternion ZQ(0,0,0,1); bool compute_inertia = false; bool is_static = false; if (fourcc==0x4c4f4342) { //BCOL Ogre::MemoryDataStreamPtr mem = Ogre::MemoryDataStreamPtr(OGRE_NEW Ogre::MemoryDataStream(name,file)); BColFile &bcol = *reinterpret_cast<BColFile*>(mem->getPtr()); is_static = bcol.mass == 0.0f; // static masterShape = new btCompoundShape(); BColMaterialMap mmap(dir,name); for (unsigned i=0 ; i<bcol.hullNum ; ++i) { BColHull &p = *bcol.hulls(i); btConvexHullShape *s2 = new btConvexHullShape(); s2->setMargin(p.margin); for (unsigned j=0 ; j<p.vertNum ; ++j) { BColVert &v = *p.verts(j); s2->addPoint(btVector3(v.x, v.y, v.z)); } masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.boxNum ; ++i) { BColBox &p = *bcol.boxes(i); btBoxShape *s2 = new btBoxShape(btVector3(p.dx/2,p.dy/2,p.dz/2)); s2->setMargin(p.margin); masterShape->addChildShape(btTransform(btQuaternion(p.qx,p.qy,p.qz,p.qw), btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.cylNum ; ++i) { BColCyl &p = *bcol.cyls(i); btCylinderShape *s2 = new btCylinderShapeZ(btVector3(p.dx/2,p.dy/2,p.dz/2)); s2->setMargin(p.margin); masterShape->addChildShape(btTransform(btQuaternion(p.qx,p.qy,p.qz,p.qw), btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.coneNum ; ++i) { BColCone &p = *bcol.cones(i); btConeShape *s2 = new btConeShapeZ(p.radius,p.height); s2->setMargin(p.margin); masterShape->addChildShape(btTransform(btQuaternion(p.qx,p.qy,p.qz,p.qw), btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.planeNum ; ++i) { BColPlane &p = *bcol.planes(i); btStaticPlaneShape *s2 = new btStaticPlaneShape(btVector3(p.nx,p.ny,p.nz),p.d); masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.sphereNum ; ++i) { BColSphere &p = *bcol.spheres(i); btSphereShape *s2 = new btSphereShape(p.radius); masterShape->addChildShape(btTransform(ZQ, btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } if (bcol.triMeshFaceNum > 0) { bcolVerts.resize(bcol.triMeshVertNum); bcolFaces.resize(bcol.triMeshFaceNum); memcpy(&bcolVerts[0], bcol.triMeshVerts(0), bcol.triMeshVertNum * sizeof(BColVert)); memcpy(&bcolFaces[0], bcol.triMeshFaces(0), bcol.triMeshFaceNum * sizeof(BColFace)); faceMaterials.reserve(bcol.triMeshFaceNum); int counter = 0; float accum_area = 0; for (unsigned i=0 ; i<bcol.triMeshFaceNum ; ++i) { BColFace &face = *bcol.triMeshFaces(i); PhysicalMaterial *mat = mmap(face.mat.name()); faceMaterials.push_back(mat); CollisionMesh::ProcObjFace po_face(to_v3(bcolVerts[face.v1]), to_v3(bcolVerts[face.v2]), to_v3(bcolVerts[face.v3])); procObjFaceDB[mat->id].faces.push_back(po_face); float area = (po_face.AB.cross(po_face.AC)).length(); APP_ASSERT(area>=0); procObjFaceDB[mat->id].areas.push_back(area); procObjFaceDB[mat->id].totalArea += area; if (++counter = 10) { counter = 0; accum_area = 0; procObjFaceDB[mat->id].areas10.push_back(accum_area); } accum_area += area; } btTriangleIndexVertexArray *v = new btTriangleIndexVertexArray( bcolFaces.size(), reinterpret_cast<int*>(&(bcolFaces[0].v1)), sizeof(BColFace), bcolVerts.size(), &(bcolVerts[0].x), sizeof(BColVert)); if (is_static) { btBvhTriangleMeshShape *tm = new btBvhTriangleMeshShape(v,true,true); tm->setMargin(bcol.triMeshMargin); btTriangleInfoMap* tri_info_map = new btTriangleInfoMap(); tri_info_map->m_edgeDistanceThreshold = bcol.triMeshEdgeDistanceThreshold; btGenerateInternalEdgeInfo(tm,tri_info_map); masterShape->addChildShape(btTransform::getIdentity(), tm); } else { // skip over dynamic trimesh } } setMass(bcol.mass); setLinearDamping(bcol.linearDamping); setAngularDamping(bcol.angularDamping); setLinearSleepThreshold(bcol.linearSleepThreshold); setAngularSleepThreshold(bcol.angularSleepThreshold); setCCDMotionThreshold(bcol.ccdMotionThreshold); setCCDSweptSphereRadius(bcol.ccdSweptSphereRadius); setInertia(Vector3(bcol.inertia[0],bcol.inertia[1],bcol.inertia[2])); compute_inertia = !bcol.inertiaProvided; } else if (fourcc==0x4c4f4354) { //TCOL ProxyStreamBuf proxy(file); std::istream stream(&proxy); quex::tcol_lexer qlex(&stream); TColFile tcol; parse_tcol_1_0(name,&qlex,tcol); is_static = tcol.mass == 0.0f; // static masterShape = new btCompoundShape(); if (tcol.usingCompound) { TColCompound &c = tcol.compound; for (size_t i=0 ; i<c.hulls.size() ; ++i) { const TColHull &h = c.hulls[i]; btConvexHullShape *s2 = new btConvexHullShape(); s2->setMargin(h.margin); for (unsigned j=0 ; j<h.vertexes.size() ; ++j) { const Vector3 &v = h.vertexes[j]; s2->addPoint(to_bullet(v)); } masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,h.material)); } for (size_t i=0 ; i<c.boxes.size() ; ++i) { const TColBox &b = c.boxes[i]; /* implement with hulls btConvexHullShape *s2 = new btConvexHullShape(); s2->addPoint(btVector3(-b.dx/2+b.margin, -b.dy/2+b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, -b.dy/2+b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, b.dy/2-b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, b.dy/2-b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, -b.dy/2+b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, -b.dy/2+b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, b.dy/2-b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, b.dy/2-b.margin, b.dz/2-b.margin)); */ btBoxShape *s2 =new btBoxShape(btVector3(b.dx/2,b.dy/2,b.dz/2)); s2->setMargin(b.margin); masterShape->addChildShape(btTransform(btQuaternion(b.qx,b.qy,b.qz,b.qw), btVector3(b.px,b.py,b.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,b.material)); } for (size_t i=0 ; i<c.cylinders.size() ; ++i) { const TColCylinder &cyl = c.cylinders[i]; btCylinderShape *s2 = new btCylinderShapeZ(btVector3(cyl.dx/2,cyl.dy/2,cyl.dz/2)); s2->setMargin(cyl.margin); masterShape->addChildShape( btTransform(btQuaternion(cyl.qx,cyl.qy,cyl.qz,cyl.qw), btVector3(cyl.px,cyl.py,cyl.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,cyl.material)); } for (size_t i=0 ; i<c.cones.size() ; ++i) { const TColCone &cone = c.cones[i]; btConeShapeZ *s2 = new btConeShapeZ(cone.radius,cone.height); s2->setMargin(cone.margin); masterShape->addChildShape( btTransform(btQuaternion(cone.qx,cone.qy,cone.qz,cone.qw), btVector3(cone.px,cone.py,cone.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,cone.material)); } for (size_t i=0 ; i<c.planes.size() ; ++i) { const TColPlane &p = c.planes[i]; btStaticPlaneShape *s2 = new btStaticPlaneShape(btVector3(p.nx,p.ny,p.nz),p.d); masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,p.material)); } for (size_t i=0 ; i<c.spheres.size() ; ++i) { const TColSphere &sp = c.spheres[i]; btSphereShape *s2 = new btSphereShape(sp.radius); masterShape->addChildShape(btTransform(ZQ, btVector3(sp.px,sp.py,sp.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,sp.material)); } } if (tcol.usingTriMesh) { TColTriMesh &t = tcol.triMesh; std::swap(verts, t.vertexes); std::swap(faces, t.faces); faceMaterials.reserve(faces.size()); int counter = 0; float accum_area = 0; for (TColFaces::const_iterator i=faces.begin(), i_=faces.end() ; i!=i_ ; ++i) { //optimisation possible here by changing the TCol struct to be more liek what //bullet wants, and then re-using memory PhysicalMaterial *mat = phys_mats.getMaterial(dir,name,i->material); faceMaterials.push_back(mat); CollisionMesh::ProcObjFace po_face(verts[i->v1], verts[i->v2], verts[i->v3]); procObjFaceDB[mat->id].faces.push_back(po_face); float area = (po_face.AB.cross(po_face.AC)).length(); APP_ASSERT(area>=0); procObjFaceDB[mat->id].areas.push_back(area); procObjFaceDB[mat->id].totalArea += area; if (++counter = 10) { counter = 0; accum_area = 0; procObjFaceDB[mat->id].areas10.push_back(accum_area); } accum_area += area; } btTriangleIndexVertexArray *v = new btTriangleIndexVertexArray( faces.size(), &(faces[0].v1), sizeof(TColFace), verts.size(), &(verts[0].x), sizeof(Vector3)); if (is_static) { btBvhTriangleMeshShape *tm = new btBvhTriangleMeshShape(v,true,true); tm->setMargin(t.margin); btTriangleInfoMap* tri_info_map = new btTriangleInfoMap(); tri_info_map->m_edgeDistanceThreshold = t.edgeDistanceThreshold; btGenerateInternalEdgeInfo(tm,tri_info_map); masterShape->addChildShape(btTransform::getIdentity(), tm); } else { // Skip over dynamic trimesh } } setMass(tcol.mass); setInertia(Vector3(tcol.inertia_x,tcol.inertia_y,tcol.inertia_z)); setLinearDamping(tcol.linearDamping); setAngularDamping(tcol.angularDamping); setLinearSleepThreshold(tcol.linearSleepThreshold); setAngularSleepThreshold(tcol.angularSleepThreshold); setCCDMotionThreshold(tcol.ccdMotionThreshold); setCCDSweptSphereRadius(tcol.ccdSweptSphereRadius); compute_inertia = !tcol.hasInertia; } else { GRIT_EXCEPT("Collision mesh \""+name+"\" seems to be corrupt."); } if (is_static) { setInertia(Vector3(0,0,0)); } else { if (faceMaterials.size() > 0) { CERR << "While loading \"" + name + "\": Dynamic trimesh not supported." << std::endl; } if (compute_inertia) { btVector3 i; masterShape->calculateLocalInertia(mass,i); setInertia(from_bullet(i)); } } }
// public: Phantom::Phantom(QObject *parent) : QObject(parent) , m_proxyPort(1080) , m_returnValue(0) , m_converter(0) , m_netAccessMan(0) { QPalette palette = m_page.palette(); palette.setBrush(QPalette::Base, Qt::transparent); m_page.setPalette(palette); bool autoLoadImages = true; bool pluginsEnabled = false; bool diskCacheEnabled = false; bool ignoreSslErrors = false; // second argument: script name QStringList args = QApplication::arguments(); // Skip the first argument, i.e. the application executable (phantomjs). args.removeFirst(); // Handle all command-line options. QStringListIterator argIterator(args); while (argIterator.hasNext()) { const QString &arg = argIterator.next(); if (arg.startsWith("--upload-file") && argIterator.hasNext()) { const QString &fileInfoString = argIterator.next(); QStringList fileInfo = fileInfoString.split("="); const QString &tag = fileInfo.at(0); const QString &fileName = fileInfo.at(1); m_page.m_allowedFiles[tag] = fileName; continue; } if (arg == "--load-images=yes") { autoLoadImages = true; continue; } if (arg == "--load-images=no") { autoLoadImages = false; continue; } if (arg == "--load-plugins=yes") { pluginsEnabled = true; continue; } if (arg == "--load-plugins=no") { pluginsEnabled = false; continue; } if (arg == "--disk-cache=yes") { diskCacheEnabled = true; continue; } if (arg == "--disk-cache=no") { diskCacheEnabled = false; continue; } if (arg == "--ignore-ssl-errors=yes") { ignoreSslErrors = true; continue; } if (arg == "--ignore-ssl-errors=no") { ignoreSslErrors = false; continue; } if (arg.startsWith("--proxy=")) { m_proxyHost = arg.mid(8).trimmed(); if (m_proxyHost.lastIndexOf(':') > 0) { bool ok = true; int port = m_proxyHost.mid(m_proxyHost.lastIndexOf(':') + 1).toInt(&ok); if (ok) { m_proxyHost = m_proxyHost.left(m_proxyHost.lastIndexOf(':')).trimmed(); m_proxyPort = port; } } continue; } if (arg.startsWith("--")) { qFatal("Unknown option '%s'", qPrintable(arg)); exit(-1); return; } else { m_scriptFile = arg; break; } } if (m_scriptFile.isEmpty()) { Utils::showUsage(); return; } if (m_proxyHost.isEmpty()) { #if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0) QNetworkProxyFactory::setUseSystemConfiguration(true); #endif } else { QNetworkProxy proxy(QNetworkProxy::HttpProxy, m_proxyHost, m_proxyPort); QNetworkProxy::setApplicationProxy(proxy); } // The remaining arguments are available for the script. while (argIterator.hasNext()) { const QString &arg = argIterator.next(); m_args += arg; } // Provide WebPage with a non-standard Network Access Manager m_netAccessMan = new NetworkAccessManager(this, diskCacheEnabled, ignoreSslErrors); m_page.setNetworkAccessManager(m_netAccessMan); connect(m_page.mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), SLOT(inject())); connect(&m_page, SIGNAL(loadFinished(bool)), this, SLOT(finish(bool))); m_page.settings()->setAttribute(QWebSettings::AutoLoadImages, autoLoadImages); m_page.settings()->setAttribute(QWebSettings::PluginsEnabled, pluginsEnabled); m_page.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true); m_page.settings()->setOfflineStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation)); m_page.settings()->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) m_page.settings()->setAttribute(QWebSettings::FrameFlatteningEnabled, true); #endif #if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0) m_page.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true); m_page.settings()->setLocalStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation)); #endif // Ensure we have document.body. m_page.mainFrame()->setHtml("<html><body></body></html>"); m_page.mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff); m_page.mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff); }
void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { if (!panelWidget(widget)) return QProxyStyle::drawControl(element, option, painter, widget); switch (element) { case CE_Splitter: painter->fillRect(option->rect, StyleHelper::borderColor()); break; case CE_TabBarTabShape: // Most styles draw a single dark outline. This looks rather ugly when combined with our // single pixel dark separator so we adjust the first tab to compensate for this if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(option)) { QStyleOptionTabV3 adjustedTab = *tab; if (tab->cornerWidgets == QStyleOptionTab::NoCornerWidgets && ( tab->position == QStyleOptionTab::Beginning || tab->position == QStyleOptionTab::OnlyOneTab)) { if (option->direction == Qt::LeftToRight) adjustedTab.rect = adjustedTab.rect.adjusted(-1, 0, 0, 0); else adjustedTab.rect = adjustedTab.rect.adjusted(0, 0, 1 ,0); } QProxyStyle::drawControl(element, &adjustedTab, painter, widget); return; } break; case CE_MenuBarItem: painter->save(); if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) { QColor highlightOutline = StyleHelper::borderColor().lighter(120); bool act = mbi->state & State_Sunken; bool dis = !(mbi->state & State_Enabled); StyleHelper::menuGradient(painter, option->rect, option->rect); QStyleOptionMenuItem item = *mbi; item.rect = mbi->rect; QPalette pal = mbi->palette; pal.setBrush(QPalette::ButtonText, dis ? Qt::gray : Qt::black); item.palette = pal; QCommonStyle::drawControl(element, &item, painter, widget); QRect r = option->rect; if (act) { // Fill| QColor baseColor = StyleHelper::baseColor(); QLinearGradient grad(option->rect.topLeft(), option->rect.bottomLeft()); grad.setColorAt(0, baseColor.lighter(120)); grad.setColorAt(1, baseColor.lighter(130)); painter->fillRect(option->rect.adjusted(1, 1, -1, 0), grad); // Outline painter->setPen(QPen(highlightOutline, 0)); painter->drawLine(QPoint(r.left(), r.top() + 1), QPoint(r.left(), r.bottom())); painter->drawLine(QPoint(r.right(), r.top() + 1), QPoint(r.right(), r.bottom())); painter->drawLine(QPoint(r.left() + 1, r.top()), QPoint(r.right() - 1, r.top())); highlightOutline.setAlpha(60); painter->setPen(QPen(highlightOutline, 0)); painter->drawPoint(r.topLeft()); painter->drawPoint(r.topRight()); QPalette pal = mbi->palette; uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine; if (!styleHint(SH_UnderlineShortcut, mbi, widget)) alignment |= Qt::TextHideMnemonic; pal.setBrush(QPalette::Text, dis ? Qt::gray : QColor(0, 0, 0, 60)); drawItemText(painter, item.rect.translated(0, 1), alignment, pal, mbi->state & State_Enabled, mbi->text, QPalette::Text); pal.setBrush(QPalette::Text, dis ? Qt::gray : Qt::white); drawItemText(painter, item.rect, alignment, pal, mbi->state & State_Enabled, mbi->text, QPalette::Text); } } painter->restore(); break; case CE_ComboBoxLabel: if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) { if (panelWidget(widget)) { painter->save(); QRect editRect = subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget); QPalette customPal = cb->palette; bool drawIcon = !(widget && widget->property("hideicon").toBool()); if (!cb->currentIcon.isNull() && drawIcon) { QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal : QIcon::Disabled; QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode); QRect iconRect(editRect); iconRect.setWidth(cb->iconSize.width() + 4); iconRect = alignedRect(cb->direction, Qt::AlignLeft | Qt::AlignVCenter, iconRect.size(), editRect); if (cb->editable) painter->fillRect(iconRect, customPal.brush(QPalette::Base)); drawItemPixmap(painter, iconRect, Qt::AlignCenter, pixmap); if (cb->direction == Qt::RightToLeft) editRect.translate(-4 - cb->iconSize.width(), 0); else editRect.translate(cb->iconSize.width() + 4, 0); // Reserve some space for the down-arrow editRect.adjust(0, 0, -13, 0); } QLatin1Char asterisk('*'); int elideWidth = editRect.width(); bool notElideAsterisk = widget && widget->property("notelideasterisk").toBool() && cb->currentText.endsWith(asterisk) && option->fontMetrics.width(cb->currentText) > elideWidth; QString text; if (notElideAsterisk) { elideWidth -= option->fontMetrics.width(asterisk); text = asterisk; } text.prepend(option->fontMetrics.elidedText(cb->currentText, Qt::ElideRight, elideWidth)); if ((option->state & State_Enabled)) { painter->setPen(QColor(0, 0, 0, 70)); painter->drawText(editRect.adjusted(1, 0, -1, 0), Qt::AlignLeft | Qt::AlignVCenter, text); } else { painter->setOpacity(0.8); } painter->setPen(StyleHelper::panelTextColor()); painter->drawText(editRect.adjusted(1, 0, -1, 0), Qt::AlignLeft | Qt::AlignVCenter, text); painter->restore(); } else { QProxyStyle::drawControl(element, option, painter, widget); } } break; case CE_SizeGrip: { painter->save(); QColor dark = Qt::white; dark.setAlphaF(0.1); int x, y, w, h; option->rect.getRect(&x, &y, &w, &h); int sw = qMin(h, w); if (h > w) painter->translate(0, h - w); else painter->translate(w - h, 0); int sx = x; int sy = y; int s = 4; painter->setPen(dark); if (option->direction == Qt::RightToLeft) { sx = x + sw; for (int i = 0; i < 4; ++i) { painter->drawLine(x, sy, sx, sw); sx -= s; sy += s; } } else { for (int i = 0; i < 4; ++i) { painter->drawLine(sx, sw, sw, sy); sx += s; sy += s; } } painter->restore(); } break; case CE_MenuBarEmptyArea: { StyleHelper::menuGradient(painter, option->rect, option->rect); painter->save(); painter->setPen(StyleHelper::borderColor()); painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight()); painter->restore(); } break; case CE_ToolBar: { QRect rect = option->rect; bool horizontal = option->state & State_Horizontal; rect = option->rect; // Map offset for global window gradient QPoint offset = widget->window()->mapToGlobal(option->rect.topLeft()) - widget->mapToGlobal(option->rect.topLeft()); QRect gradientSpan; if (widget) gradientSpan = QRect(offset, widget->window()->size()); bool drawLightColored = lightColored(widget); if (horizontal) StyleHelper::horizontalGradient(painter, gradientSpan, rect, drawLightColored); else StyleHelper::verticalGradient(painter, gradientSpan, rect, drawLightColored); if (!drawLightColored) painter->setPen(StyleHelper::borderColor()); else painter->setPen(QColor(0x888888)); if (horizontal) { // Note: This is a hack to determine if the // toolbar should draw the top or bottom outline // (needed for the find toolbar for instance) QColor lighter(StyleHelper::sidebarHighlight()); if (drawLightColored) lighter = QColor(255, 255, 255, 180); if (widget && widget->property("topBorder").toBool()) { painter->drawLine(rect.topLeft(), rect.topRight()); painter->setPen(lighter); painter->drawLine(rect.topLeft() + QPoint(0, 1), rect.topRight() + QPoint(0, 1)); } else { painter->drawLine(rect.bottomLeft(), rect.bottomRight()); painter->setPen(lighter); painter->drawLine(rect.topLeft(), rect.topRight()); } } else { painter->drawLine(rect.topLeft(), rect.bottomLeft()); painter->drawLine(rect.topRight(), rect.bottomRight()); } } break; #if defined(Q_OS_MAC) case CE_ToolButtonLabel: if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(option)) { QStyleOptionToolButton myTb = *tb; myTb.state &= ~State_AutoRaise; QRect cr = tb->rect; bool needText = false; int alignment = 0; bool down = tb->state & (State_Sunken | State_On); // The down state is special for QToolButtons in a toolbar on the Mac // The text is a bit bolder and gets a drop shadow and the icons are also darkened. // This doesn't really fit into any particular case in QIcon, so we // do the majority of the work ourselves. if (!(tb->features & QStyleOptionToolButton::Arrow)) { Qt::ToolButtonStyle tbstyle = tb->toolButtonStyle; if (tb->icon.isNull() && !tb->text.isEmpty()) tbstyle = Qt::ToolButtonTextOnly; switch (tbstyle) { case Qt::ToolButtonTextOnly: { needText = true; alignment = Qt::AlignCenter; break; } case Qt::ToolButtonIconOnly: case Qt::ToolButtonTextBesideIcon: case Qt::ToolButtonTextUnderIcon: { QRect pr = cr; QIcon::Mode iconMode = (tb->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled; QIcon::State iconState = (tb->state & State_On) ? QIcon::On : QIcon::Off; QPixmap pixmap = tb->icon.pixmap(tb->rect.size().boundedTo(tb->iconSize), iconMode, iconState); // Draw the text if it's needed. if (tb->toolButtonStyle != Qt::ToolButtonIconOnly) { needText = true; if (tb->toolButtonStyle == Qt::ToolButtonTextUnderIcon) { QMainWindow *mw = widget ? qobject_cast<QMainWindow *>(widget->window()) : 0; if (mw && mw->unifiedTitleAndToolBarOnMac()) { pr.setHeight(pixmap.size().height() / pixmap.devicePixelRatio()); cr.adjust(0, pr.bottom() + 1, 0, 1); } else { pr.setHeight(pixmap.size().height() / pixmap.devicePixelRatio() + 6); cr.adjust(0, pr.bottom(), 0, -3); } alignment |= Qt::AlignCenter; } else { pr.setWidth(pixmap.width() / pixmap.devicePixelRatio() + 8); cr.adjust(pr.right(), 0, 0, 0); alignment |= Qt::AlignLeft | Qt::AlignVCenter; } } proxy()->drawItemPixmap(painter, pr, Qt::AlignCenter, pixmap); break; } default: Q_ASSERT(false); break; } if (needText) { QPalette pal = tb->palette; QPalette::ColorRole role = QPalette::WindowText; if (!proxy()->styleHint(SH_UnderlineShortcut, tb, widget)) alignment |= Qt::TextHideMnemonic; if (tbstyle == Qt::ToolButtonTextOnly || (tbstyle != Qt::ToolButtonTextOnly && !down)) { painter->drawText(cr, alignment, tb->text); if (down && tbstyle == Qt::ToolButtonTextOnly) { pal = QApplication::palette("QMenu"); pal.setCurrentColorGroup(tb->palette.currentColorGroup()); role = QPalette::HighlightedText; } } proxy()->drawItemText(painter, cr, alignment, pal, tb->state & State_Enabled, tb->text, role); } } else { QProxyStyle::drawControl(element, option, painter, widget); } } break; #endif default: QProxyStyle::drawControl(element, option, painter, widget); break; } }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(DeferredProxyTest, reporter, ctxInfo) { GrProxyProvider* proxyProvider = ctxInfo.grContext()->priv().proxyProvider(); GrResourceProvider* resourceProvider = ctxInfo.grContext()->priv().resourceProvider(); const GrCaps& caps = *ctxInfo.grContext()->priv().caps(); int attempt = 0; // useful for debugging for (auto origin : { kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin }) { for (auto widthHeight : { 100, 128, 1048576 }) { for (auto config : { kAlpha_8_GrPixelConfig, kRGB_565_GrPixelConfig, kRGBA_8888_GrPixelConfig, kRGBA_1010102_GrPixelConfig, kRGB_ETC1_GrPixelConfig }) { for (auto fit : { SkBackingFit::kExact, SkBackingFit::kApprox }) { for (auto budgeted : { SkBudgeted::kYes, SkBudgeted::kNo }) { for (auto numSamples : {1, 4, 16, 128}) { // We don't have recycling support for compressed textures if (GrPixelConfigIsCompressed(config) && SkBackingFit::kApprox == fit) { continue; } GrSurfaceDesc desc; desc.fFlags = kRenderTarget_GrSurfaceFlag; desc.fWidth = widthHeight; desc.fHeight = widthHeight; desc.fConfig = config; desc.fSampleCnt = numSamples; GrSRGBEncoded srgbEncoded; GrColorType colorType = GrPixelConfigToColorTypeAndEncoding(config, &srgbEncoded); const GrBackendFormat format = caps.getBackendFormatFromGrColorType(colorType, srgbEncoded); { sk_sp<GrTexture> tex; if (SkBackingFit::kApprox == fit) { tex = resourceProvider->createApproxTexture( desc, GrResourceProvider::Flags::kNoPendingIO); } else { tex = resourceProvider->createTexture( desc, budgeted, GrResourceProvider::Flags::kNoPendingIO); } sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(format, desc, origin, fit, budgeted); REPORTER_ASSERT(reporter, SkToBool(tex) == SkToBool(proxy)); if (proxy) { REPORTER_ASSERT(reporter, proxy->asRenderTargetProxy()); // This forces the proxy to compute and cache its // pre-instantiation size guess. Later, when it is actually // instantiated, it checks that the instantiated size is <= to // the pre-computation. If the proxy never computed its // pre-instantiation size then the check is skipped. proxy->gpuMemorySize(); check_surface(reporter, proxy.get(), origin, widthHeight, widthHeight, config, budgeted); int supportedSamples = caps.getRenderTargetSampleCount(numSamples, config); check_rendertarget(reporter, caps, resourceProvider, proxy->asRenderTargetProxy(), supportedSamples, fit, caps.maxWindowRectangles()); } } desc.fFlags = kNone_GrSurfaceFlags; { sk_sp<GrTexture> tex; if (SkBackingFit::kApprox == fit) { tex = resourceProvider->createApproxTexture( desc, GrResourceProvider::Flags::kNoPendingIO); } else { tex = resourceProvider->createTexture( desc, budgeted, GrResourceProvider::Flags::kNoPendingIO); } sk_sp<GrTextureProxy> proxy( proxyProvider->createProxy(format, desc, origin, fit, budgeted)); REPORTER_ASSERT(reporter, SkToBool(tex) == SkToBool(proxy)); if (proxy) { // This forces the proxy to compute and cache its // pre-instantiation size guess. Later, when it is actually // instantiated, it checks that the instantiated size is <= to // the pre-computation. If the proxy never computed its // pre-instantiation size then the check is skipped. proxy->gpuMemorySize(); check_surface(reporter, proxy.get(), origin, widthHeight, widthHeight, config, budgeted); check_texture(reporter, resourceProvider, proxy->asTextureProxy(), fit); } } attempt++; } } } } } } }
int main(int argc, char *argv[]) { QCoreApplication::setApplicationName("Embedded IDE"); QCoreApplication::setOrganizationName("none"); QCoreApplication::setOrganizationDomain("unknown.tk"); QApplication app(argc, argv); QApplication::setWindowIcon(QIcon(":/images/embedded-ide.svg")); QTranslator tr; for(const auto& p: AppConfig::langPaths()) { if (tr.load(QLocale::system().name(), p)) { if (app.installTranslator(&tr)) { qDebug() << "load translations" << QLocale::system().name(); break; } } } auto checkConfig = [&app, &tr](AppConfig *config) { app.setStyleSheet( config->useDarkStyle()? AppConfig::readEntireTextFile(":/qdarkstyle/style.qss"): "" ); auto selectedLang = config->language(); if (!selectedLang.isEmpty()) { for(const auto& p: AppConfig::langPaths()) { if (tr.load(selectedLang, p)) { if (app.installTranslator(&tr)) { qDebug() << "load translations" << QLocale::system().name(); break; } } } } }; QObject::connect(&AppConfig::instance(), &AppConfig::configChanged, [&checkConfig](AppConfig *config) { checkConfig(config); switch (config->networkProxyType()) { case AppConfig::NetworkProxyType::None: QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy); break; case AppConfig::NetworkProxyType::System: QNetworkProxyFactory::setUseSystemConfiguration(true); break; case AppConfig::NetworkProxyType::Custom: QNetworkProxy proxy( QNetworkProxy::HttpProxy, config->networkProxyHost(), static_cast<quint16>(config->networkProxyPort().toInt())); if (config->networkProxyUseCredentials()) { proxy.setUser(config->networkProxyUsername()); proxy.setPassword(config->networkProxyPassword()); } QNetworkProxy::setApplicationProxy(proxy); break; } }); AppConfig::instance().load(); checkConfig(&AppConfig::instance()); QCommandLineParser opt; opt.addHelpOption(); opt.addVersionOption(); opt.addPositionalArgument("filename", "Makefile filename"); opt.addOptions({ { { "e", "exec" }, "Execute stript or file", "execname" }, { { "d", "debug"}, "Enable debug" }, { { "s", "stacktrace" }, "Add stack trace to debug" } }); opt.process(app); if (opt.isSet("exec")) { QString execname = opt.value("exec"); QProcess::startDetached(execname); return 0; } if (opt.isSet("debug")) { QString debugString = "[%{type}] %{appname} (%{file}:%{line}) - %{message}"; if (opt.isSet("stacktrace")) debugString += "\n\t%{backtrace separator=\"\n\t\"}"; qSetMessagePattern(debugString); } else qSetMessagePattern(""); MainWindow w; w.show(); if (!opt.positionalArguments().isEmpty()) { QString path = opt.positionalArguments().first(); QTimer::singleShot(0, [path, &w]() { w.openProject(path); }); } return QApplication::exec(); }
// Detect any proxy configuration settings automatically. static void windows_detect_autoproxy_settings() { if (log_flags.proxy_debug) { msg_printf(NULL, MSG_INFO, "[proxy] automatic proxy check in progress"); } HMODULE hModWinHttp = LoadLibrary("winhttp.dll"); if (!hModWinHttp) { return; } pfnWinHttpOpen pWinHttpOpen = (pfnWinHttpOpen)GetProcAddress(hModWinHttp, "WinHttpOpen"); if (!pWinHttpOpen) { return; } pfnWinHttpCloseHandle pWinHttpCloseHandle = (pfnWinHttpCloseHandle)(GetProcAddress(hModWinHttp, "WinHttpCloseHandle")); if (!pWinHttpCloseHandle) { return; } pfnWinHttpGetProxyForUrl pWinHttpGetProxyForUrl = (pfnWinHttpGetProxyForUrl)(GetProcAddress(hModWinHttp, "WinHttpGetProxyForUrl")); if (!pWinHttpGetProxyForUrl) { return; } HINTERNET hWinHttp = NULL; WINHTTP_AUTOPROXY_OPTIONS autoproxy_options; WINHTTP_PROXY_INFO proxy_info; PARSED_URL purl; std::wstring network_test_url; size_t pos; memset(&autoproxy_options, 0, sizeof(autoproxy_options)); memset(&proxy_info, 0, sizeof(proxy_info)); autoproxy_options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoproxy_options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoproxy_options.fAutoLogonIfChallenged = TRUE; network_test_url = A2W(config.network_test_url).c_str(); hWinHttp = pWinHttpOpen( L"BOINC client", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, NULL ); if (pWinHttpGetProxyForUrl(hWinHttp, network_test_url.c_str(), &autoproxy_options, &proxy_info)) { if (log_flags.proxy_debug) { msg_printf(NULL, MSG_INFO, "[proxy] successfully executed proxy check", hWinHttp); } // Apparently there are some conditions where WinHttpGetProxyForUrl can return // success but where proxy_info.lpszProxy is null. Maybe related to UPNP? // // For the time being check to see if proxy_info.lpszProxy is non-null. // if (proxy_info.lpszProxy) { std::string proxy(W2A(std::wstring(proxy_info.lpszProxy))); std::string new_proxy; if (log_flags.proxy_debug) { msg_printf(NULL, MSG_INFO, "[proxy] proxy list '%s'", proxy.c_str()); } if (!proxy.empty()) { // Trim string if more than one proxy is defined // proxy list is defined as: // ([<scheme>=][<scheme>"://"]<server>[":"<port>]) // Find and erase first delimeter type. pos = proxy.find(';'); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Find and erase second delimeter type. pos = proxy.find(' '); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Parse the remaining url parse_url(proxy.c_str(), purl); // Store the results for future use. if (0 != strcmp(working_proxy_info.autodetect_server_name, purl.host)) { // Reset clients connection error detection path net_status.need_physical_connection = false; working_proxy_info.autodetect_protocol = purl.protocol; strcpy(working_proxy_info.autodetect_server_name, purl.host); working_proxy_info.autodetect_port = purl.port; } if (log_flags.proxy_debug) { msg_printf(NULL, MSG_INFO, "[proxy] automatic proxy detected %s:%d", purl.host, purl.port ); } } } // Clean up if (proxy_info.lpszProxy) GlobalFree(proxy_info.lpszProxy); if (proxy_info.lpszProxyBypass) GlobalFree(proxy_info.lpszProxyBypass); } else { // We can get here if the user is switching from a network that // requires a proxy to one that does not require a proxy. working_proxy_info.autodetect_protocol = 0; strcpy(working_proxy_info.autodetect_server_name, ""); working_proxy_info.autodetect_port = 0; if (log_flags.proxy_debug) { msg_printf(NULL, MSG_INFO, "[proxy] no automatic proxy detected"); } } if (hWinHttp) pWinHttpCloseHandle(hWinHttp); FreeLibrary(hModWinHttp); if (log_flags.proxy_debug) { msg_printf(NULL, MSG_INFO, "[proxy] automatic proxy check finished"); } }
void WAircraftGlyph::paint(WPainter* painter) { data_type& d = *data(); painter->setBrush(WBrush(Ws::NoBrush)); m_cd.aircraftMatrix = painter->worldTransform(); m_cd.labelMatrix_1 = m_cd.aircraftMatrix.inverted(); const WMatrix& mapToView = m_cd.aircraftMatrix; painter->setWorldTransform(WMatrix()); WColor symbolColor = d.m_SymbolColor; WPointF view_aircraft_pos_f = mapToView.map(d.m_pos); static const double R = 10.0; static const double RS = 15.0; //draw a bigger circle around, when aircraft is selected double x = view_aircraft_pos_f.x(); double y = view_aircraft_pos_f.y(); if (d.m_eSymbolType == SYMBOL_COMBINED/*AIRCRAFT_NOR*/) { painter->setPen(WPen(symbolColor)); if (isSelected()) { painter->drawEllipse(WRectF(x - RS, y - RS, RS * 2, RS * 2)); } //tmp painter->drawEllipse(WRectF(x - R, y - R, R * 2, R * 2)); painter->drawLine(WLineF(x - R, y, x + R, y)); painter->drawLine(WLineF(x, y - R, x, y + R)); //DrawAircraft(painter, view_aircraft_pos); } else if (d.m_eSymbolType == SYMBOL_PRIMARY)//一次雷达 { painter->setPen(WPen(symbolColor)); if (isSelected()) { painter->drawEllipse(WRectF(x - RS, y - RS, RS * 2, RS * 2)); } painter->drawLine(WLineF(x - R, y, x + R, y)); painter->drawLine(WLineF(x, y - R, x, y + R)); } else if (d.m_eSymbolType == SYMBOL_SECONDARY)//二次雷达 { painter->setPen(WPen(symbolColor)); if (isSelected()) { painter->drawEllipse(WRectF(x - RS, y - RS, RS * 2, RS * 2)); } painter->drawEllipse(WRectF(x - R, y - R, R * 2, R * 2)); } else if (d.m_eSymbolType == SYMBOL_PLAN)//计划航迹 { painter->setPen(WPen(symbolColor)); if (isSelected()) { painter->drawEllipse(WRectF(x - RS, y - RS, RS * 2, RS * 2)); } painter->drawRect(WRectF(x - R, y - R, R * 2, R * 2)); } else if (d.m_eSymbolType == SYMBOL_COAST)//进入盲区 { painter->setPen(WPen(symbolColor)); if (isSelected()) { painter->drawEllipse(WRectF(x - RS, y - RS, RS * 2, RS * 2)); } WPen pen; pen.setWidth(4); pen.setColor(WColor(255, 255, 255)); painter->setPen(pen); painter->drawLine(WWorldLineF(x - R, y, x - R / 2, y)); painter->drawLine(WWorldLineF(x + R, y, x + R / 2, y)); painter->drawLine(WWorldLineF(x, y - R, x, y - R / 2)); painter->drawLine(WWorldLineF(x, y + R, x, y + R / 2)); pen.setWidth(1); pen.setColor(symbolColor); painter->setPen(pen); } else if (d.m_eSymbolType == SYMBOL_SPI)//处于SPI告警状态 { painter->setPen(WPen(symbolColor)); if (isSelected()) { painter->drawEllipse(WRectF(x - RS, y - RS, RS * 2, RS * 2)); } painter->drawLine(WLineF(x - R, y, x + R, y)); painter->drawLine(WLineF(x, y - R, x, y + R)); WPen pen; pen.setStyle(Ws::DashLine); pen.setColor(WColor(255, 255, 255)); painter->setPen(pen); painter->drawEllipse(WRectF(x - R, y - R, R * 2, R * 2)); pen.setStyle(Ws::SolidLine); pen.setColor(symbolColor); painter->setPen(pen); } else if (d.m_eSymbolType == SYMBOL_VEHICLE)//车辆航迹(实心三角) { painter->setPen(WPen(symbolColor)); painter->setBrush(WBrush(symbolColor, Ws::SolidPattern)); WPointF Tmppoint; std::vector<WPointF> vPoints; Tmppoint.setXY(x, y - 5); vPoints.push_back(Tmppoint); Tmppoint.setXY(x - 5, y + 5); vPoints.push_back(Tmppoint); Tmppoint.setXY(x + 5, y + 5); vPoints.push_back(Tmppoint); painter->drawPolygon(WWorldPolygonF(vPoints)); painter->setBrush(WBrush(Ws::NoBrush)); if (isSelected()) { painter->drawEllipse(WRectF(x - R, y - R, R * 2, R * 2)); } } else if (d.m_eSymbolType == SYMBOL_ADSB) // ADSB暂定符号(参考Indra手册)实心菱形 { painter->setPen(WPen(symbolColor)); painter->setBrush(WBrush(symbolColor, Ws::SolidPattern)); WPointF Tmppoint; std::vector<WPointF> vPoints; Tmppoint.setXY(x, y - 5); vPoints.push_back(Tmppoint); Tmppoint.setXY(x - 5, y); vPoints.push_back(Tmppoint); Tmppoint.setXY(x, y + 5); vPoints.push_back(Tmppoint); Tmppoint.setXY(x + 5, y); vPoints.push_back(Tmppoint); painter->drawPolygon(WWorldPolygonF(vPoints)); painter->setBrush(WBrush(Ws::NoBrush)); if (isSelected()) { painter->drawEllipse(WRectF(x - R, y - R, R * 2, R * 2)); } } else if (d.m_eSymbolType == SYMBOL_PIC_AIRCRAFT || d.m_eSymbolType == SYMBOL_PIC_HELICOPTER) { painter->setPen(WPen(symbolColor)); painter->setBrush(WBrush(symbolColor, Ws::SolidPattern)); painter->setBrush(WBrush(Ws::NoBrush)); painter->setRenderHint(Ws::SmoothPixmapTransform); WPixmap pixmap(d.m_eSymbolType == SYMBOL_PIC_AIRCRAFT ? ":/plane.png" : ":/helicopter.png"); WPixmap newPixmap = pixmap.xrotated(-90 + d.m_nHeading, Ws::SmoothTransformation); painter->drawPixmap(view_aircraft_pos_f-WPointF(newPixmap.width()/2, newPixmap.height()/2), newPixmap); } WLineF line(WPointF(), d.m_boundingRect.center()); if (line.length() > m_sLineMaxLength) { line.setLength(m_sLineMaxLength); WPointF offPoint = line.p2() - d.m_boundingRect.center(); d.m_boundingRect.translate(offPoint); d.m_showRect.translate(offPoint); } WPointF view_label_pos_f = d.m_boundingRect.bottomLeft() + view_aircraft_pos_f;// aircraft pos + label offset pos WPointF offset_f = d.m_showRect.bottomLeft() - d.m_boundingRect.bottomLeft(); WRectF view_label_rect(WRectF(view_label_pos_f, WSizeF(d.m_boundingRect.width(), d.m_boundingRect.height()))); //标牌避让 if (m_sLabelAvoidance) { const WRectF& r = view_label_rect; Mosaic::Instance().Allocate(reinterpret_cast<int>(this), r.left(), r.bottom(), r.right(), r.top()); } // label show rect指标牌边框显示区域,标牌有时候需要显示边框,边框与内容区域可能不一致,如C显示 WRectF label_show_rect(WRectF(view_label_rect.bottomLeft(), WSizeF(d.m_showRect.width(), d.m_showRect.height()))); label_show_rect.translate(offset_f); //show history // 尾迹点访问外部数据,本应该加锁,由于外部默认分配了很大数据存在,且点数据一致增加到默认最大值 // 内部通过下标访问不存在问题 // 如外部数据容器变小,就必须得加锁保护 if (m_sShowHistoryPoint && d.m_vHistory != NULL && d.m_vHistory->size() > 1) { size_t n = d.m_vHistory->size() - 1; size_t count = (m_sHstNum < n) ? m_sHstNum : n; size_t pos = n - 1; for (size_t i = 0; i < count; ++i, --pos) { static const double R = 0.8; double dx = 0.00; double dy = 0.00; mapToView.map((*d.m_vHistory)[pos]->x(), (*d.m_vHistory)[pos]->y(), &dx, &dy); painter->drawEllipse(WRectF(dx - R, dy - R, R * 2, R * 2)); //尾迹点 } } //show preline if (m_sShowPreLine) { painter->drawLine(WLineF(view_aircraft_pos_f, mapToView.map(d.m_PRLPos))); //预计线 } if (d.m_bShowLabel) { //show linkline (内部包含了外一点与一矩形中心点连线只绘制外一点到矩形边框的算法) DrawLabelLine(painter, view_aircraft_pos_f, label_show_rect); WPainterProxy proxy(painter); painter->setRenderHint(Ws::Antialiasing, false); // 绘制矩形的时候去掉反锯齿,效果更好 painter->setRenderHint(Ws::TextAntialiasing, false); if (d.m_bShowBounding) { painter->setPen(d.m_penBounding); // 标牌边框颜色与航迹符号与文本是分开的 painter->drawRect(label_show_rect); } //show label painter->setFont(m_sLabelFont); m_cache_locker.lock(); // 对访问d.m_blocks进行加锁,网络线程在FormatLable的时候会重新组织m_blocks数据,数据需要同步操作 BOOST_FOREACH(const WBlockData& block, m_blocks) { painter->setPen(block.m_penText); WRectF r = block.m_boundingRect.translated(view_label_pos_f); painter->drawText(r, Ws::AlignCenter, block.m_text); }
void WGraphicsRectItem::paint(WPainter* painter) { WPainterProxy proxy(painter); painter->setRenderHint(Ws::Antialiasing, false); painter->setRenderHint(Ws::TextAntialiasing, false); painter->setWorldTransform(getRotateMatrix(), true); //设置旋转矩阵 painter->setBrush(brush()); painter->setPen(pen()); painter->drawRect(data()->rect); //绘制矩形 if (isSelected()) //矩形被选中,绘制所有的控制点 { painter->drawLine(WWorldLineF(_rotate_pt, WWorldPointF(_rotate_pt.x(), data()->rect.top()))); painter->setPen(CP_PEN); painter->setBrush(CP_BRUSH); for (unsigned i=0; i<array_size(_cp); ++i) { if (i & 1) { painter->drawRect(WWorldRectF(_cp[i].x() - CP_RADIUS, _cp[i].y() - CP_RADIUS, CP_RADIUS * 2, CP_RADIUS * 2)); } else { painter->drawEllipse(WWorldRectF(_cp[i].x() - CP_RADIUS, _cp[i].y() - CP_RADIUS, CP_RADIUS * 2, CP_RADIUS * 2)); } } painter->setBrush(ROTATE_BRUSH); painter->drawEllipse(WWorldRectF(_rotate_pt.x() - CP_RADIUS, _rotate_pt.y() - CP_RADIUS, CP_RADIUS * 2, CP_RADIUS * 2)); } if (_dragging) //矩形在拖动,绘制正在拖动的矩形 { WWorldPointF pos = scene()->attachedPoint(scene()->mousePos()); WPen dragPen = data()->pen; WBrush dragBrush = data()->brush; dragPen.setColor(dragPen.color().lighter(2.0)); dragBrush.setColor(dragBrush.color().lighter(2.0)); painter->setPen(dragPen); painter->setBrush(dragBrush); if (_select_flag != SF_ROTATE) { if (_select_flag != SF_CONTENT || isMovable()) { WWorldPointF offset = pos - scene()->dragStartPos(); const int (&f)[4] = ADJUST_TABLE[bit(_select_flag)]; painter->drawRect(data()->rect.adjusted(offset.x() * f[0], offset.y() * f[1], offset.x() * f[2], offset.y() * f[3])); } } else { painter->setWorldTransform(getRotateMatrix_1(), true); WWorldPointF c = data()->rect.center(); double ag = WWorldLineF(c, pos).angle() - 90; painter->setWorldTransform(WMatrix().translate(-c.x(), -c.y()) * WMatrix().rotate(ag + data()->angle) * WMatrix().translate(c.x(), c.y())); painter->drawRect(data()->rect); } } }
void NetworkBinding::_SetHTTPSProxy(const ValueList& args, KValueRef result) { args.VerifyException("setHTTPSProxy", "s|0 ?s s s"); SharedProxy proxy(ArgumentsToProxy(args, "https")); ProxyConfig::SetHTTPSProxyOverride(proxy); }
void NetworkAccessManager::SetProxy(QString proxySet){ #ifndef QT_NO_NETWORKPROXY QStringList set = proxySet.split(QStringLiteral(" ")); set.takeFirst(); if(set.length() < 1) return; QString type = QString(); QString host = QString(); QString user = QString(); QString pass = QString(); int port = 1080; QStringList addrplus; QStringList hostplus; QStringList userplus; if(set.length() == 2){ type = set[0]; addrplus = set[1].split(QStringLiteral("@")); } else { type = QStringLiteral("default"); addrplus = set[0].split(QStringLiteral("@")); } if(addrplus.length() == 2){ userplus = addrplus[0].split(QStringLiteral(":")); hostplus = addrplus[1].split(QStringLiteral(":")); if(userplus.length() == 2){ user = userplus[0]; pass = userplus[1]; } else { user = userplus[0]; } } else { hostplus = addrplus[0].split(QStringLiteral(":")); } if(hostplus.length() == 2){ host = hostplus[0]; port = hostplus[1].toInt(); } else { host = hostplus[0]; } if(!host.isEmpty() && proxy().hostName() != host){ QNetworkProxy proxy; if (Application::ExactMatch(QStringLiteral("[dD]efault(?:[pP]roxy)?"), type)) proxy.setType(QNetworkProxy::DefaultProxy); else if(Application::ExactMatch(QStringLiteral("[sS]ocks5?(?:[pP]roxy)?"), type)) proxy.setType(QNetworkProxy::Socks5Proxy); else if(Application::ExactMatch(QStringLiteral("[hH]ttp(?:[pP]roxy)?"), type)) proxy.setType(QNetworkProxy::HttpProxy); else if(Application::ExactMatch(QStringLiteral("[hH]ttp[cC]aching(?:[pP]roxy)?"), type)) proxy.setType(QNetworkProxy::HttpCachingProxy); else if(Application::ExactMatch(QStringLiteral("[fF]tp[cC]aching(?:[pP]roxy)?"), type)) proxy.setType(QNetworkProxy::FtpCachingProxy); else proxy.setType(QNetworkProxy::DefaultProxy); if(!host.isEmpty()) proxy.setHostName(host); if(!user.isEmpty()) proxy.setUser(user); if(!pass.isEmpty()) proxy.setPassword(pass); proxy.setPort(port); setProxy(proxy); } #else Q_UNUSED(proxySet); #endif }