code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
Rule: {
identifier: an unique identifier
title: description
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
userAgent: the useragent value. See var "agents" for options.
script: script to inject. Separated by spaces
}
Order: {
status: enabled / disabled / custom
position: default / custom
identifier: identifier of rule
}
Issue: {
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
description: The description of this issue
issueId: Issue ID on issue tracking page
url: optional, support page for issue tracking.
Use code.google.com if omitted.
}
ServerSide:
ActiveXConfig: {
version: version
rules: object of user-defined rules, propertied by identifiers
defaultRules: ojbect of default rules
scripts: mapping of workaround scripts, by identifiers. metadatas
localScripts: metadatas of local scripts.
order: the order of rules
cache: to accerlerate processing
issues: The bugs/unsuppoted sites that we have accepted.
misc:{
lastUpdate: last timestamp of updating
logEnabled: log
tracking: Allow GaS tracking.
verbose: verbose level of logging
}
}
PageSide:
ActiveXConfig: {
pageSide: Flag of pageSide.
pageScript: Helper script to execute on context of page
extScript: Helper script to execute on context of extension
pageRule: If page is matched.
clsidRules: If page is not matched or disabled. valid CLSID rules
logEnabled: log
verbose: verbose level of logging
}
*/
// Update per 5 hours.
var DEFAULT_INTERVAL = 1000 * 3600 * 5;
function ActiveXConfig(input)
{
var settings;
if (input === undefined) {
var defaultSetting = {
version: 3,
rules: {},
defaultRules: {},
scripts: {},
localScripts: {},
order: [],
notify: [],
issues: [],
blocked: [],
misc: {
lastUpdate: 0,
logEnabled: false,
tracking: true,
verbose: 3
}
};
input = defaultSetting;
}
settings = ActiveXConfig.convertVersion(input);
settings.removeInvalidItems();
settings.update();
return settings;
}
var settingKey = 'setting';
var scriptPrefix = 'script_';
clsidPattern = /[^0-9A-F][0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}[^0-9A-F]/;
var agents = {
ie9: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)",
ie8: "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0)",
ie7: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64;)",
ff7win: "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",
ip5: "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3",
ipad5: "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3"
};
function stringHash(str) {
var hash = 0;
if (!str)
return hash;
for (var i = 0; i < str.length; i++) {
ch = str.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function getUserAgent(key) {
// This script is always run under sandbox, so useragent should be always
// correct.
if (!key || !(key in agents)) {
return "";
}
var current = navigator.userAgent;
var wow64 = current.indexOf('WOW64') >= 0;
var value = agents[key];
if (!wow64) {
value = value.replace(' WOW64;', '');
}
return value;
}
ActiveXConfig.convertVersion = function(setting) {
if (setting.version == 3) {
if (!setting.blocked) {
setting.blocked = [];
}
setting.__proto__ = ActiveXConfig.prototype;
return setting;
} else if (setting.version == 2) {
function parsePattern(pattern) {
pattern = pattern.trim();
var title = pattern.match(/###(.*)/);
if (title) {
return {
pattern: pattern.match(/(.*)###/)[1].trim(),
title: title[1].trim()
};
} else {
return {
pattern: pattern,
title: "Rule"
};
}
}
var ret = new ActiveXConfig();
if (setting.logEnabled) {
ret.misc.logEnabled = true;
}
var urls = setting.url_plain.split('\n');
for (var i = 0; i < urls.length; ++i) {
var rule = ret.createRule();
var pattern = parsePattern(urls[i]);
rule.title = pattern.title;
var url = pattern.pattern;
if (url.substr(0, 2) == 'r/') {
rule.type = 'regex';
rule.value = url.substr(2);
} else {
rule.type == 'wild';
rule.value = url;
}
ret.addCustomRule(rule, 'convert');
}
var clsids = setting.trust_clsids.split('\n');
for (var i = 0; i < clsids.length; ++i) {
var rule = ret.createRule();
rule.type = 'clsid';
var pattern = parsePattern(clsids[i]);
rule.title = pattern.title;
rule.value = pattern.pattern;
ret.addCustomRule(rule, 'convert');
}
firstUpgrade = true;
return ret;
}
};
ActiveXConfig.prototype = {
// Only used for user-scripts
shouldEnable: function(object) {
if (this.pageRule) {
return this.pageRule;
}
var clsidRule = this.getFirstMatchedRule(object, this.clsidRules);
if (clsidRule) {
return clsidRule;
} else {
return null;
}
},
createRule: function() {
return {
title: "Rule",
type: "wild",
value: "",
userAgent: "",
scriptItems: "",
}
},
removeInvalidItems : function() {
if (this.pageSide) {
return;
}
function checkIdentifierMatches(item, prop) {
if (typeof item[prop] != "object") {
console.log('reset ', prop);
item[prop] = {};
}
for (var i in item[prop]) {
var ok = true;
if (typeof item[prop][i] != "object") {
ok = false;
}
if (ok && item[prop][i].identifier != i) {
ok = false;
}
if (!ok) {
console.log('remove corrupted item ', i, ' in ', prop);
delete item[prop][i];
}
}
}
checkIdentifierMatches(this, "rules");
checkIdentifierMatches(this, "defaultRules");
checkIdentifierMatches(this, "localScripts");
checkIdentifierMatches(this, "scripts");
checkIdentifierMatches(this, "issues");
var newOrder = [];
for (var i = 0; i < this.order.length; ++i) {
if (this.getItem(this.order[i])) {
newOrder.push(this.order[i]);
} else {
console.log('remove order item ', this.order[i]);
}
}
this.order = newOrder;
},
addCustomRule: function(newItem, auto) {
if (!this.validateRule(newItem)) {
return;
}
var identifier = this.createIdentifier();
newItem.identifier = identifier;
this.rules[identifier] = newItem;
this.order.push({
status: 'custom',
position: 'custom',
identifier: identifier
});
this.update();
trackAddCustomRule(newItem, auto);
},
updateDefaultRules: function(newRules) {
var deleteAll = false, ruleToDelete = {};
if (typeof this.defaultRules != 'object') {
// There might be some errors!
// Clear all defaultRules
console.log('Corrupted default rules, reload all');
deleteAll = true;
this.defaultRules = {};
} else {
for (var i in this.defaultRules) {
if (!(i in newRules)) {
console.log('Remove rule ' + i);
ruleToDelete[i] = true;
delete this.defaultRules[i];
}
}
}
var newOrder = [];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].position == 'custom' ||
(!deleteAll && !ruleToDelete[this.order[i].identifier])) {
newOrder.push(this.order[i]);
}
}
this.order = newOrder;
var position = 0;
for (var i in newRules) {
if (!(i in this.defaultRules)) {
this.addDefaultRule(newRules[i], position);
position++;
}
this.defaultRules[i] = newRules[i];
}
},
updateConfig: function(session) {
session.startUpdate();
console.log('Start updating');
var updated = {
issues: false,
setting: false,
scripts: false
};
var setting = this;
session.updateFile({
url: 'setting.json',
dataType: "json",
success: function(nv, status, xhr) {
console.log('Update default rules');
updated.setting = true;
setting.updateDefaultRules(nv);
if (updated.setting && updated.scripts) {
setting.updateAllScripts(session);
}
setting.update();
}
});
session.updateFile({
url: 'scripts.json',
dataType: "json",
success: function(nv, status, xhr) {
updated.scripts = true;
console.log('Update scripts');
setting.scripts = nv;
if (updated.setting && updated.scripts) {
setting.updateAllScripts(session);
}
setting.update();
}
});
session.updateFile({
url: 'issues.json',
dataType: "json",
success: function(nv, status, xhr) {
console.log('Update issues');
setting.issues = nv;
setting.update();
}
});
},
getPageConfig: function(href) {
var ret = {};
ret.pageSide = true;
ret.version = this.version;
ret.verbose = this.misc.verbose;
ret.logEnabled = this.misc.logEnabled;
ret.pageRule = this.getFirstMatchedRule({href:href});
if (!ret.pageRule) {
ret.clsidRules = this.cache.clsidRules;
} else {
var script = this.getScripts(ret.pageRule.script);
ret.pageScript = script.page;
ret.extScript = script.extension;
}
return ret;
},
getFirstMatchedRule: function(object, rules) {
var useCache = false;
if (!rules) {
rules = this.cache.validRules;
useCache = true;
}
if (Array.isArray(rules)) {
for (var i = 0; i < rules.length; ++i) {
if (this.isRuleMatched(rules[i], object, useCache ? i : -1)) {
return rules[i];
}
}
} else {
for (var i in rules) {
if (this.isRuleMatched(rules[i], object)) {
return rules[i];
}
}
}
return null;
},
getMatchedIssue: function(filter) {
return this.getFirstMatchedRule(filter, this.issues);
},
activeRule: function(rule) {
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == rule.identifier) {
if (this.order[i].status == 'disabled') {
this.order[i].status = 'enabled';
trackAutoEnable(rule.identifier);
}
break;
}
}
this.update();
},
validateRule: function(rule) {
var ret = true;
try {
if (rule.type == 'wild') {
ret &= this.convertUrlWildCharToRegex(rule.value) != null;
} else if (rule.type == 'regex') {
ret &= rule.value != '';
var r = new RegExp(rule.value, 'i');
} else if (rule.type == 'clsid') {
var v = rule.value.toUpperCase();
if (!clsidPattern.test(v) || v.length > 55)
ret = false;
}
} catch (e) {
ret = false;
}
return ret;
},
isRuleMatched: function(rule, object, id) {
if (rule.type == "wild" || rule.type == "regex" ) {
var regex;
if (id >= 0) {
regex = this.cache.regex[id];
} else if (rule.type == 'wild') {
regex = this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
regex = new RegExp('^' + rule.value + '$', 'i');
}
if (object.href && regex.test(object.href)) {
return true;
}
} else if (rule.type == "clsid") {
if (object.clsid) {
var v1 = clsidPattern.exec(rule.value.toUpperCase());
var v2 = clsidPattern.exec(object.clsid.toUpperCase());
if (v1 && v2 && v1[0] == v2[0]) {
return true;
}
}
}
return false;
},
getScripts: function(script) {
var ret = {
page: "",
extension: ""
};
if (!script) {
return ret;
}
var items = script.split(' ');
for (var i = 0; i < items.length; ++i) {
if (!items[i] || !this.scripts[items[i]]) {
continue;
}
var name = items[i];
var val = '// ';
val += items[i] + '\n';
val += this.getScriptContent(name);
val += '\n\n';
ret[this.scripts[name].context] += val;
}
return ret;
},
getScriptContent: function(scriptid) {
this.updateScript(scriptid, false);
var local = this.localScripts[scriptid];
if (!local) {
// The script not found.
return "";
}
var id = scriptPrefix + scriptid;
return localStorage[id];
},
updateAllScripts: function(session) {
console.log('updateAllScripts');
var scripts = {};
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].status == 'disabled') {
continue;
}
var rule = this.getItem(this.order[i]);
var script = rule.script;
if (!script) {
continue;
}
var items = script.split(' ');
for (var j = 0; j < items.length; ++j) {
scripts[items[j]] = true;
}
}
for (var i in scripts) {
this.updateScript(i, true, session);
}
},
updateScript: function(id, async, session) {
var remote = this.scripts[id];
var local = this.localScripts[id];
if (!remote || remote.updating) {
return;
}
if (local && local.checksum == remote.checksum) {
return;
}
remote.updating = true;
var setting = this;
var config = {
url: remote.url + "?hash=" + remote.checksum,
async: async,
complete: function() {
delete remote.updating;
},
error: function() {
console.log('Update script ' + remote.identifier + ' failed');
},
context: this,
success: function(nv, status, xhr) {
delete remote.updating;
var hash = stringHash(nv);
if (hash == remote.checksum) {
localStorage[scriptPrefix + id] = nv;
setting.localScripts[id] = remote;
setting.save();
console.log('script updated ', id);
} else {
var message = 'Hashcode mismatch!!';
message += ' script: ' + remote.identifier;
messsge += ' actual: ' + hash;
message += ' expected: ' + remote.checksum;
console.log(message);
}
},
// Don't evaluate this.
dataType: "text"
};
if (!UpdateSession && !session) {
// Should run update from background
throw "Not valid session";
}
if (session) {
session.updateFile(config);
} else {
UpdateSession.updateFile(config);
}
},
convertUrlWildCharToRegex: function(wild) {
try {
function escapeRegex(str, star) {
if (!star) star = '*';
var escapeChars = /([\.\\\/\?\{\}\+\[\]])/g;
return str.replace(escapeChars, "\\$1").replace('*', star);
}
wild = wild.toLowerCase();
if (wild == "<all_urls>") {
wild = "*://*/*";
}
var pattern = /^(.*?):\/\/(\*?[^\/\*]*)\/(.*)$/i;
// pattern: [all, scheme, host, page]
var parts = pattern.exec(wild);
if (parts == null) {
return null;
}
var scheme = parts[1];
var host = parts[2];
var page = parts[3];
var regex = '^' + escapeRegex(scheme, '[^:]*') + ':\\/\\/';
regex += escapeRegex(host, '[^\\/]*') + '/';
regex += escapeRegex(page, '.*');
return new RegExp(regex, 'i');
} catch (e) {
return null;
}
},
update: function() {
if (this.pageSide) {
return;
}
this.updateCache();
if (this.cache.listener) {
this.cache.listener.trigger('update');
}
this.save();
},
// Please remember to call update() after all works are done.
addDefaultRule: function(rule, position) {
console.log("Add new default rule: ", rule);
var custom = null;
if (rule.type == 'clsid') {
for (var i in this.rules) {
var info = {href: "not-a-URL-/", clsid: rule.value};
if (this.isRuleMatched(this.rules[i], info, -1)) {
custom = this.rules[i];
break;
}
}
} else if (rule.keyword && rule.testUrl) {
// Try to find matching custom rule
for (var i in this.rules) {
if (this.isRuleMatched(this.rules[i], {href: rule.testUrl}, -1)) {
if (this.rules[i].value.toLowerCase().indexOf(rule.keyword) != -1) {
custom = this.rules[i];
break;
}
}
}
}
var newStatus = 'disabled';
if (custom) {
console.log('Convert custom rule', custom, ' to default', rule);
// Found a custom rule which is similiar to this default rule.
newStatus = 'enabled';
// Remove old one
delete this.rules[custom.identifier];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == custom.identifier) {
this.order.splice(i, 1);
break;
}
}
}
this.order.splice(position, 0, {
position: 'default',
status: newStatus,
identifier: rule.identifier
});
this.defaultRules[rule.identifier] = rule;
},
updateCache: function() {
if (this.pageSide) {
return;
}
this.cache = {
validRules: [],
regex: [],
clsidRules: [],
userAgentRules: [],
listener: (this.cache || {}).listener
};
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].status == 'custom' || this.order[i].status == 'enabled') {
var rule = this.getItem(this.order[i]);
var cacheId = this.cache.validRules.push(rule) - 1;
if (rule.type == 'clsid') {
this.cache.clsidRules.push(rule);
} else if (rule.type == 'wild') {
this.cache.regex[cacheId] =
this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
this.cache.regex[cacheId] = new RegExp('^' + rule.value + '$', 'i');
}
if (rule.userAgent != '') {
this.cache.userAgentRules.push(rule);
}
}
}
},
save: function() {
if (location.protocol == "chrome-extension:") {
// Don't include cache in localStorage.
var cache = this.cache;
delete this.cache;
localStorage[settingKey] = JSON.stringify(this);
this.cache = cache;
}
},
createIdentifier: function() {
var base = 'custom_' + Date.now() + "_" + this.order.length + "_";
var ret;
do {
ret = base + Math.round(Math.random() * 65536);
} while (this.getItem(ret));
return ret;
},
getItem: function(item) {
var identifier = item;
if (typeof identifier != 'string') {
identifier = item.identifier;
}
if (identifier in this.rules) {
return this.rules[identifier];
} else {
return this.defaultRules[identifier];
}
}
};
function loadLocalSetting() {
var setting = undefined;
if (localStorage[settingKey]) {
try{
setting = JSON.parse(localStorage[settingKey]);
} catch (e){
setting = undefined;
}
}
if (!setting) {
firstRun = true;
}
return new ActiveXConfig(setting);
}
function clearSetting() {
localStorage.removeItem(settingKey);
setting = loadLocalSetting();
}
| zzhongster-npactivex | chrome/configure.js | JavaScript | mpl11 | 20,700 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
if (isNaN(tabId)) {
alert('Invalid tab id');
}
var backgroundPage = chrome.extension.getBackgroundPage();
var tabInfo = backgroundPage.tabStatus[tabId];
var setting = backgroundPage.setting;
if (!tabInfo) {
alert('Cannot get tab tabInfo');
}
$(document).ready(function() {
$('.status').hide();
$('#submitissue').hide();
if (tabInfo.urldetect) {
$('#status_urldetect').show();
} else if (!tabInfo.count) {
// Shouldn't have this popup
} else if (tabInfo.error) {
$('#status_error').show();
} else if (tabInfo.count != tabInfo.actived) {
$('#status_disabled').show();
} else {
$('#status_ok').show();
$('#submitissue').show();
}
});
$(document).ready(function() {
$('#issue_view').hide();
if (tabInfo.error != 0) {
var errorid = tabInfo.issueId;
var issue = setting.issues[errorid];
$('#issue_content').text(issue.description);
var url = issue.url;
if (!url) {
var issueUrl = "http://code.google.com/p/np-activex/issues/detail?id=";
url = issueUrl + issue.issueId;
}
$('#issue_track').click(function() {
chrome.tabs.create({url:url});
window.close();
});
$('#issue_view').show();
}
});
function refresh() {
alert($$('refresh_needed'));
window.close();
}
function showEnableBtns() {
var list = $('#enable_btns');
list.hide();
if (tabInfo.urldetect || tabInfo.count > tabInfo.actived) {
list.show();
var info = {actived: true};
for (var i = 0; i < tabInfo.frames && info.actived; ++i) {
for (var j = 0; j < tabInfo.objs[i].length && info.actived; ++j) {
info = tabInfo.objs[i][j];
}
}
if (info.actived) {
return;
}
var rule = setting.getFirstMatchedRule(info, setting.defaultRules);
if (rule) {
var button = $('<button>').addClass('defaultRule');
button.text($$('enable_default_rule', rule.title));
button.click(function() {
setting.activeRule(rule);
refresh();
});
list.append(button);
} else {
var site = info.href.replace(/[^:]*:\/\/([^\/]*).*/, '$1');
var sitepattern = info.href.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*');
var btn1 = $('<button>').addClass('customRule').
text($$('add_rule_site', site)).click(function() {
var rule = setting.createRule();
rule.type = 'wild';
rule.value = sitepattern;
setting.addCustomRule(rule, 'popup');
refresh();
});
var clsid = info.clsid;
var btn2 = $('<button>').addClass('customRule').
text($$('add_rule_clsid')).click(function() {
var rule = setting.createRule();
rule.type = 'clsid';
rule.value = clsid;
setting.addCustomRule(rule, 'popup');
refresh();
});
list.append(btn1).append(btn2);
}
}
}
$(document).ready(function() {
$('#submitissue').click(function() {
tabInfo.tracking = true;
alert($$('issue_submitting_desp'));
window.close();
});
});
$(document).ready(showEnableBtns);
$(window).load(function() {
$('#share').load('share.html');
});
| zzhongster-npactivex | chrome/popup.js | JavaScript | mpl11 | 3,467 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta>
<link rel="stylesheet" type="text/css" href="/popup.css" />
<script src="/jquery.js"></script>
<script src="/popup.js"></script>
<script src="/i18n.js"></script>
<script src="/gas.js"></script>
</head>
<body>
<div class="main">
<div>
<div id="status_ok" class="status">
<span i18n="status_ok"></span>
<button id="submitissue" i18n="submitissue"></button>
</div>
<div id="status_urldetect" class="status" i18n="status_urldetect"></div>
<div id="status_disabled" class="status" i18n="status_disabled"></div>
<div id="status_error" class="status" i18n="status_error"></div>
</div>
<div id="enable_btns">
</div>
<div id="issue_view">
<div i18n="issue_desp">
</div>
<div id="issue_content">
</div>
<div>
<a id="issue_track" i18n="issue_track" href="#"></a>
</div>
</div>
<div id="share">
</div>
</div>
</body>
</html>
| zzhongster-npactivex | chrome/popup.html | HTML | mpl11 | 1,143 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var controlLogFName="__npactivex_log";
var controlLogEvent="__npactivex_log_event__";
var config = null;
var port = null;
var logs = [];
var scriptConfig = {
none2block: false,
formid: false,
documentid: false
};
function onControlLog(event) {
var message = event.data;
log(message);
}
window.addEventListener(controlLogEvent, onControlLog, false);
function connect() {
if (port) {
return;
}
port = chrome.extension.connect();
for (var i = 0; i < logs.length; ++i) {
port.postMessage({command: 'Log', message: logs[i]});
}
if (port && config) {
logs = undefined;
}
}
function log(message) {
var time = (new Date()).toLocaleTimeString();
message = time + ' ' + message;
if (config && config.logEnabled) {
console.log(message);
}
if (port) {
port.postMessage({command: 'Log', message: message});
}
if (!config || !port) {
logs.push(message);
}
}
log('PageURL: ' + location.href);
var pendingObjects = [];
function init(response) {
config = new ActiveXConfig(response);
if (config.logEnabled) {
for (var i = 0; i < logs.length; ++i) {
console.log(logs[i]);
}
}
eval(config.extScript);
executeScript(config.pageScript);
setUserAgent();
log('Page rule:' + JSON.stringify(config.pageRule));
for (var i = 0; i < pendingObjects.length; ++i) {
pendingObjects[i].activex_process = false;
process(pendingObjects[i]);
cacheConfig();
}
delete pendingObjects;
}
function cacheConfig() {
sessionStorage.activex_config_cache = JSON.stringify(config);
}
function loadConfig(response) {
if (config) {
config = new ActiveXConfig(response);
var cache = sessionStorage.activex_config_cache;
if (cache) {
cacheConfig();
}
} else {
init(response);
}
if (config.pageRule) {
cacheConfig();
}
}
function loadSessionConfig() {
var cache = sessionStorage.activex_config_cache;
if (cache) {
log('Loading config from session cache');
init(JSON.parse(cache));
}
}
loadSessionConfig();
var notifyBar = null;
var pageDOMLoaded = false;
var needNotifyBar = false;
function showNotifyBar(request) {
if (notifyBar) {
return;
}
if (!pageDOMLoaded) {
needNotifyBar = true;
return;
}
notifyBar = {};
log('Create notification bar');
var barurl = chrome.extension.getURL('notifybar.html');
if (document.body.tagName == 'BODY') {
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.src = barurl;
iframe.height = "35px";
iframe.width = "100%";
iframe.style.top = "0px";
iframe.style.left = "0px";
iframe.style.zIndex = '2000';
iframe.style.position = 'fixed';
notifyBar.iframe = iframe;
document.body.insertBefore(iframe, document.body.firstChild);
var placeHolder = document.createElement('div');
placeHolder.style.height = iframe.height;
placeHolder.style.zIndex = '1999';
placeHolder.style.borderWidth = '0px';
placeHolder.style.borderStyle = 'solid';
placeHolder.style.borderBottomWidth = '1px';
document.body.insertBefore(placeHolder, document.body.firstChild);
notifyBar.placeHolder = placeHolder;
} else if (document.body.tagName == 'FRAMESET') {
// We can't do this..
return;
}
}
function dismissNotifyBar() {
if (!notifyBar || !notifyBar.iframe) {
return;
}
notifyBar.iframe.parentNode.removeChild(notifyBar.iframe);
notifyBar.placeHolder.parentNode.removeChild(notifyBar.placeHolder);
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (self == top && request.command == 'NotifyUser') {
showNotifyBar(request);
sendResponse({});
} else if (self == top && request.command == 'DismissNotificationPage') {
dismissNotifyBar();
sendResponse({});
}
});
chrome.extension.sendRequest(
{command:"Configuration", href:location.href, top: self == top}, loadConfig);
window.addEventListener("beforeload", onBeforeLoading, true);
//window.addEventListener('error', onError, true);
| zzhongster-npactivex | chrome/inject_start.js | JavaScript | mpl11 | 4,393 |
// Copyright (c) 2010 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var $$ = chrome.i18n.getMessage;
function loadI18n() {
var spans = document.querySelectorAll('[i18n]');
for (var i = 0; i < spans.length; ++i) {
var obj = spans[i];
v = $$(obj.getAttribute("i18n"));
if (v == "")
v = obj.getAttribute('i18n');
if (obj.tagName == 'INPUT') {
obj.value = v;
} else {
obj.innerText = v;
}
}
document.removeEventListener("DOMContentLoaded", loadI18n, false);
}
document.addEventListener("DOMContentLoaded", loadI18n, false);
| zzhongster-npactivex | chrome/i18n.js | JavaScript | mpl11 | 704 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var backgroundPage = chrome.extension.getBackgroundPage();
var defaultTabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
function insertTabInfo(tab) {
if (isNaN(defaultTabId)) {
defaultTabId = tab.id;
}
if (uls[tab.id]) {
return;
}
var ul = $('<ul>').appendTo($('#logs_items'));
uls[tab.id] = ul;
var title = tab.title;
if (!title) {
title = "Tab " + tab.id;
}
$('<a>').attr('href', '#')
.attr('tabid', tab.id)
.text(title)
.click(function(e) {
loadTabInfo(parseInt($(e.target).attr('tabid')));
}).appendTo(ul);
}
var uls = {};
$(document).ready(function() {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; ++i) {
var protocol = tabs[i].url.replace(/(^[^:]*).*/, '$1');
if (protocol != 'http' && protocol != 'https' && protocol != 'file') {
continue;
}
insertTabInfo(tabs[i]);
}
for (var i in backgroundPage.tabStatus) {
insertTabInfo({id: i});
}
$('#tracking').change(function() {
var tabStatus = backgroundPage.tabStatus[currentTab];
if (tabStatus) {
tabStatus.tracking = tracking.checked;
}
});
loadTabInfo(defaultTabId);
});
});
$(document).ready(function() {
$("#beforeSubmit").click(function() {
var link = $("#submitLink");
if (beforeSubmit.checked) {
link.show();
} else {
link.hide();
}
});
});
var currentTab = -1;
function loadTabInfo(tabId) {
if (isNaN(tabId)) {
return;
}
if (tabId != currentTab) {
if (currentTab != -1) {
uls[currentTab].removeClass('selected');
}
currentTab = tabId;
uls[tabId].addClass('selected');
var s = backgroundPage.generateLogFile(tabId);
$("#text").val(s);
tracking.checked = backgroundPage.tabStatus[tabId].tracking;
}
}
| zzhongster-npactivex | chrome/log.js | JavaScript | mpl11 | 2,104 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta>
<style>
.line {
clear: both;
margin: 4px 0px;
}
.item {
margin: 4px 3px;
float: left;
}
</style>
<script>
var link = "https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn"
var text2 = '给使用Chrome的亲们:只要安装了这个扩展,就可以直接在Chrome里使用各种网银、播放器等ActiveX控件了。而且不用切换内核,非常方便。';
var text = text2 + "下载地址:";
var pic = 'http://ww3.sinaimg.cn/bmiddle/8c75b426jw1dqz2l1qfubj.jpg';
</script>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/all.js#xfbml=1";
js.async = true;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="line">
<div class="fb-like" data-href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn" data-send="true" data-width="450" data-show-faces="false"></div>
</div>
<div class="line">
<!-- Place this tag where you want the +1 button to render -->
<g:plusone annotation="inline" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn" expandTo="top"></g:plusone>
<!-- Place this render call where appropriate -->
<script type="text/javascript">
window.___gcfg = {lang: navigator.language};
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</div>
<div class="line">
<div class="item">
<div id="weiboshare">
</div>
<script type="text/javascript" charset="utf-8">
(function(){
var _w = 75 , _h = 24;
var param = {
url:link,
type:'2',
count:'1', /**是否显示分享数,1显示(可选)*/
appkey:'798098327', /**您申请的应用appkey,显示分享来源(可选)*/
title:text,
pic:pic, /**分享图片的路径(可选)*/
ralateUid:'2356524070', /**关联用户的UID,分享微博会@该用户(可选)*/
language:'zh_cn', /**设置语言,zh_cn|zh_tw(可选)*/
rnd:new Date().valueOf()
}
var temp = [];
for( var p in param ){
temp.push(p + '=' + encodeURIComponent( param[p] || '' ) )
}
weiboshare.innerHTML = ('<iframe allowTransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?' + temp.join('&') + '" width="'+ _w+'" height="'+_h+'"></iframe>')
})()
</script>
</div>
<div class="item">
<script async="true" type="text/javascript" src="http://widget.renren.com/js/rrshare.js"></script>
<a name="xn_share" onclick="shareClick()" type="icon_medium" href="javascript:;"></a>
<script type="text/javascript">
function shareClick() {
var rrShareParam = {
resourceUrl : link, //分享的资源Url
pic : pic, //分享的主题图片Url
title : 'ActiveX for Chrome', //分享的标题
description : text2 //分享的详细描述
};
rrShareOnclick(rrShareParam);
}
</script>
</div>
<div class="item">
<a href="javascript:void(0)" onclick="postToWb();return false;" class="tmblog"><img src="http://mat1.gtimg.com/app/opent/images/websites/share/weiboicon24.png" border="0" alt="转播到腾讯微博" ></a><script type="text/javascript">
function postToWb(){
var _url = encodeURIComponent(link);
var _assname = encodeURI("");//你注册的帐号,不是昵称
var _appkey = encodeURI("801125118");//你从腾讯获得的appkey
var _pic = encodeURI(pic);//(例如:var _pic='图片url1|图片url2|图片url3....)
var _t = '';//标题和描述信息
var metainfo = document.getElementsByTagName("meta");
for(var metai = 0;metai < metainfo.length;metai++){
if((new RegExp('description','gi')).test(metainfo[metai].getAttribute("name"))){
_t = metainfo[metai].attributes["content"].value;
}
}
_t = text;
if(_t.length > 120){
_t= _t.substr(0,117)+'...';
}
_t = encodeURI(_t);
var _u = 'http://share.v.t.qq.com/index.php?c=share&a=index&url='+_url+'&appkey='+_appkey+'&pic='+_pic+'&assname='+_assname+'&title='+_t;
window.open( _u,'', 'width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' );
}
</script>
</div>
<div class="item">
<iframe allowTransparency='true' id='like_view' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' hspace='0' vspace='0' style='height:24px;width:65px;' src='http://www.kaixin001.com/like/like.php?url=https%3A%2F%2Fchrome.google.com%2Fwebstore%2Fdetail%2Flgllffgicojgllpmdbemgglaponefajn&show_faces=false'></iframe>
</div>
<div class="item">
<a href="javascript:void(function(){var d=document,e=encodeURIComponent,s1=window.getSelection,s2=d.getSelection,s3=d.selection,s=s1?s1():s2?s2():s3?s3.createRange().text:'',r='http://www.douban.com/recommend/?url='+e(link)+'&title='+e('ActiveX for Chrome')+'&sel='+e(s)+'&v=1',x=function(){if(!window.open(r,'douban','toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330'))location.href=r+'&r=1'};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})()"><img style="margin:auto" src="http://img2.douban.com/pics/fw2douban_s.png" alt="推荐到豆瓣" /></a>
</div>
</div>
</body>
</html>
| zzhongster-npactivex | chrome/share.html | HTML | mpl11 | 5,785 |
<script src="jquery.js" > </script>
<script src="i18n.js" > </script>
<script src="common.js" > </script>
<script src="configure.js"> </script>
<script src="web.js"> </script>
<script src="configUpdate.js"> </script>
<script src="gas.js"> </script>
<script>
var setting = loadLocalSetting();
var updateSession = new UpdateSession();
setting.cache.listener = updateSession;
updateSession.bind('success', function() {
setting.misc.lastUpdate = Date.now();
});
updateSession.bind('complete', function() {
setting.update();
console.log('Update completed');
});
startListener();
registerRequestListener();
// If you want to build your own copy with a different id, please keep the
// tracking enabled.
var default_id = "lgllffgicojgllpmdbemgglaponefajn";
var debug = chrome.i18n.getMessage("@@extension_id") != default_id;
if (debug && firstRun) {
if (confirm("Debugging mode. Disable tracking?")) {
setting.misc.tracking = false;
}
}
window.setTimeout(function() {
UpdateSession.setUpdateInterval(function() {
setting.updateConfig(updateSession);
}, updateSession, DEFAULT_INTERVAL);
if (firstRun || firstUpgrade) {
open('donate.html');
}
}, 1000);
</script>
| zzhongster-npactivex | chrome/background.html | HTML | mpl11 | 1,291 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var config;
function loadConfig(_resp) {
config = _resp;
$(document).ready(init);
}
function openPopup() {
var url = chrome.extension.getURL('popup.html?tabid=' + config.tabId);
var windowConfig = 'height=380,width=560,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no';
window.open(url, 'popup', windowConfig);
dismiss();
}
function blockSite() {
chrome.extension.sendRequest(
{command: "BlockSite", site: config.sitePattern});
dismiss();
}
function dismiss() {
chrome.extension.sendRequest({command: "DismissNotification"});
}
function init() {
$('#enable').click(openPopup);
$('#close').click(dismiss);
$('#block').click(blockSite);
$('#close').text(config.closeMsg);
$('#enable').text(config.enableMsg);
$('#info').text(config.message);
$('#block').text(config.blockMsg);
}
chrome.extension.sendRequest({command: "GetNotification"}, loadConfig);
| zzhongster-npactivex | chrome/notifybar.js | JavaScript | mpl11 | 1,133 |
body {
background: -webkit-gradient(
linear, left top, left bottom, from(#feefae), to(#fee692));
margin: 0;
margin-top: 1px;
margin-left: 5px;
border-bottom-width: 1px;
overflow: hidden;
}
span {
word-break:keep-all;
white-space:nowrap;
overflow: hidden;
}
button {
background: -webkit-gradient(
linear, left top, left bottom, from(#fffbe9), to(#fcedb2));
height: 28px;
margin: 2px 3px;
border-radius: 3px;
border-width: 1px;
border-color: #978d60;
}
button:hover {
border-color: #4b4630;
}
| zzhongster-npactivex | chrome/notifybar.css | CSS | mpl11 | 560 |
<html>
<head>
<style>
body {
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#CCF), color-stop(0.4, white), to(white)) no-repeat
}
#paymentoptions > * {
float: left;
}
#main {
margin: auto;
width: 600px;
}
#main > * {
clear: both;
margin: 30px;
}
#header {
text-align: center;
font-size: 30px;
}
#hint {
font-size: 20px;
border-color: red;
border-width: 2px;
border-style: dashed;
padding: 10px;
}
</style>
<script src="jquery.js"></script>
<script src="i18n.js"></script>
<script src="gas.js"></script>
<title i18n="donate"></title>
</head>
<body>
<div id="main">
<div id="header">ActiveX for Chrome -- <span i18n="donate"></span></div>
<div i18n="donate_label"></div>
<div><a target="_blank" href="http://code.google.com/p/np-activex/wiki/Donations" i18n="donate_record"></a></div>
<div id="paymentoptions">
<form name="_xclick" target="_blank" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="qiuc12@gmail.com">
<input type="hidden" name="item_name" value="ActiveX for Chrome">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="">
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
<a target="_blank" href="https://me.alipay.com/eagleonhill">
<img src="http://alipay-donate.appspot.com/images/donate.jpg" border="0" alt="alipay支付宝"></img>
</a>
</div>
<div></div>
<div i18n="donate_share">
</div>
<div id="share"></div>
<div></div>
<div id="hint" style="display:none">
<a id="hintonfirst" href="options.html" i18n="donate_gotooptions"></a>
</div>
<script>
if (chrome.extension.getBackgroundPage().firstRun) {
document.getElementById('hint').style.display = '';
chrome.extension.getBackgroundPage().firstRun = false;
}
$(document).ready(function() {
$('#share').load('share.html');
});
</script>
</div>
</body>
</html>
| zzhongster-npactivex | chrome/donate.html | HTML | mpl11 | 2,559 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
// Permission for experimental not given.
var handler = chrome.webRequest;
function onBeforeSendHeaders(details) {
var rule = setting.getFirstMatchedRule(
{href: details.url}, setting.cache.userAgent);
if (!rule || !(rule.userAgent in agents)) {
return {};
}
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (details.requestHeaders[i].name == 'User-Agent') {
details.requestHeaders[i].value = agents[rule.userAgent];
break;
}
}
return {requestHeaders: details.requestHeaders};
}
function registerRequestListener() {
if (!handler) {
return;
}
var filters = {
urls: ["<all_urls>"],
types: ["main_frame", "sub_frame", "xmlhttprequest"]
};
try{
handler.onBeforeSendHeaders.addListener(
onBeforeSendHeaders, filters, ["requestHeaders", "blocking"]);
} catch (e) {
console.log('Your browser doesn\'t support webRequest');
}
}
| zzhongster-npactivex | chrome/web.js | JavaScript | mpl11 | 1,133 |
<html>
<head>
<title i18n="view_log"></title>
<script src="jquery.js"></script>
<script src="gas.js"></script>
<script src="i18n.js"></script>
<script src="log.js"></script>
<style>
#text {
width: 800px;
height: 500px;
}
div {
margin: 10px 0px;
}
body > div {
float:left;
}
#logs_items {
margin-top: 40px;
margin-right: 20px;
overflow-x: hidden;
overflow-y: scroll;
width: 300px;
height: 500px;
white-space: nowrap;
border-width: 1px;
border-style: solid;
}
ul.selected {
background-color: aqua;
}
</style>
</head>
<body>
<div id="left">
<div id="logs_items">
</div>
</div>
<div id="logs_show">
<div i18n="log">
</div>
<textarea id="text" wrap="off">
</textarea>
<div>
<input id="tracking" type="checkbox"></input>
<label for="tracking" i18n="log_tracking"></label>
</div>
<div>
<input id="beforeSubmit" type="checkbox"></input>
<label for="beforeSubmit" i18n="issue_submit_desp"></label>
<a id="submitLink" i18n="issue_submit_goto" style="margin-left:50px;display:none" href="http://code.google.com/p/np-activex/issues/entry?template=Defect%20report%20from%20log" target="_blank"></a>
</div>
</div>
</body>
</html>
| zzhongster-npactivex | chrome/log.html | HTML | mpl11 | 1,496 |
body {
background-color: #ffd;
}
body > div {
margin: 10px;
max-width: 1000px;
}
#tbSetting {
width: 1000px;
height: 500px;
}
.itemline.newline:not(.editing) {
display:none;
}
div[property=status] {
width: 75px
}
div[property=title] {
width: 200px
}
div[property=type] {
width: 60px
}
div[property=value] {
width: 320px
}
div[property=userAgent] {
width: 80px
}
div[property=script] {
width: 350px
}
[property=status] button {
width: 70px;
}
#ruleCmds button {
width: 100px;
margin: 4px 8px 3px 8px;
}
#tbServer, #tbServerStatus {
float: left;
}
#tbServer {
width: 600px;
}
#share {
float:left;
padding: 5px 0 0 40px;
height: 100px;
}
#footer * {
margin: 0 10px;
}
| zzhongster-npactivex | chrome/options.css | CSS | mpl11 | 780 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html("");
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text)
this.input.append(o);
}
}
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
| zzhongster-npactivex | chrome/listtypes.js | JavaScript | mpl11 | 3,295 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var USE_RECORD_GAP = 3 * 60 * 1000; // 3 minutes
var _gaq = window._gaq || [];
_gaq.push(['_setAccount', 'UA-28870762-4']);
_gaq.push(['_trackPageview', location.href.replace(/\?.*$/, "")]);
function initGAS() {
var setting = chrome.extension.getBackgroundPage().setting;
if (setting.misc.tracking) {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
} else {
// dummy it. Non-debug && non-track
_gaq.push = function() {};
}
}
window.addEventListener('load', initGAS, false);
var useHistory = {};
var issueHistory = {};
function trackCheckSpan(history, item) {
var last = history[item];
if (last && Date.now() - last < USE_RECORD_GAP) {
return false;
}
history[item] = Date.now();
return true;
}
function trackIssue(issue) {
if (!trackCheckSpan(issueHistory, issue.identifier)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'error', '' + issue.identifier]);
}
function trackVersion(version) {
_gaq.push(['_trackEvent', 'option', 'version', version]);
}
function serializeRule(rule) {
return rule.type[0] + ' ' + rule.value;
}
function trackUse(identifier) {
if (!trackCheckSpan(useHistory, identifier)) {
return;
}
if (identifier.substr(0, 7) == 'custom_') {
var rule = setting.getItem(identifier);
_gaq.push(['_trackEvent', 'usage', 'use-custom', serializeRule(rule)]);
} else {
_gaq.push(['_trackEvent', 'usage', 'use', identifier]);
}
}
var urlHistory = {}
function trackNotUse(url) {
if (!trackCheckSpan(urlHistory, url)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'notuse', url]);
}
function trackDisable(identifier) {
_gaq.push(['_trackEvent', 'option', 'disable', identifier]);
}
function trackAutoEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'autoenable', identifier]);
}
function trackEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'enable', identifier]);
}
function trackAddCustomRule(rule, auto) {
var cmd = 'add';
if (auto) {
cmd = 'add-' + auto;
}
_gaq.push(['_trackEvent', 'option', cmd, serializeRule(rule)]);
}
function trackManualUpdate() {
_gaq.push(['_trackEvent', 'update', 'manual']);
}
function trackUpdateFile(url) {
_gaq.push(['_trackEvent', 'update', 'file', url]);
}
| zzhongster-npactivex | chrome/gas.js | JavaScript | mpl11 | 2,714 |
body {
background-color: #ffd;
}
.main {
width: 500px;
height: 340px;
padding: 10px;
}
.status {
font-size: 18px;
margin: 0 20px;
}
#issue_view {
margin: 15px 10px;
}
#issue_view > div {
margin: 7px 0px;
}
#share {
position: absolute;
top: 250px;
left: 30px;
height: 90px;
}
button {
width: 350px;
height: 30px;
margin: 4px;
}
button.defaultRule {
background-color: #0A0;
}
button.customRule {
background-color: #aaf;
}
| zzhongster-npactivex | chrome/popup.css | CSS | mpl11 | 507 |
<html>
<head>
<link rel="stylesheet" type="text/css" href="/list.css" />
<link rel="stylesheet" type="text/css" href="/options.css" />
<script src="/jquery.js"></script>
<script src="/configure.js"></script>
<script src="/i18n.js"></script>
<script src="/list.js"></script>
<script src="/listtypes.js"></script>
<script src="/options.js"></script>
<script src="/gas.js"></script>
<title i18n="option_title"></title>
</head>
<body>
<div class="description">
<span i18n="option_help"></span>
<a class="help" i18n="help" target="_blank"></a>
<a href="donate.html" target="_blank" i18n="donate"></a>
</div>
<div id="tbSetting">
</div>
<div>
<div style="float:left">
<div id="ruleCmds">
<button id="addRule" i18n="add"></button>
<button id="deleteRule" i18n="delete"></button>
<button id="moveUp" i18n="moveUp"></button>
<button id="moveDown" i18n="moveDown"></button>
</div>
<div id="serverStatus" style="margin-top: 10px">
<span i18n="lastupdatetime"></span>
<span width="400" id="lastUpdate"></span>
<button id="doUpdate" i18n="doUpdate"></button>
</div>
<div>
<input id="log_enable" type="checkbox">
<span i18n="log_enable">
</span>
</input>
<input id="tracking" type="checkbox">
<span i18n="tracking">
</span>
</input>
</div>
</div>
<div id="share">
</div>
</div>
<div id="footer" style="clear:both">
<span i18n="copyright">
</span>
<a href="donate.html" target="_blank" i18n="donate"></a>
<a class="help" i18n="help" target="_blank"></a>
<a href="log.html" i18n="view_log" target="_blank"></a>
<span id="follow">
</span>
</div>
</body>
</html>
| zzhongster-npactivex | chrome/options.html | HTML | mpl11 | 1,966 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var background = chrome.extension.getBackgroundPage();
var setting = background.setting;
var updateSession = background.updateSession;
function toggleRule(e) {
var line = e.data.line;
var index = line.attr('row');
var item = setting.order[index];
if (item.position == 'default') {
if (item.status == 'enabled') {
item.status = 'disabled';
trackDisable(item.identifier);
} else if (item.status == 'disabled') {
item.status = 'enabled';
trackEnable(item.identifier);
}
}
line.blur();
e.data.list.finishEdit(line);
e.data.list.updateLine(line);
save();
}
var settingProps = [ {
header: "",
property: "status",
type: 'button',
caption: "",
events: {
command: toggleRule,
update: setStatus,
createNew: setStatusNew
}
}, {
header: $$("title"),
property: "title",
type: "input"
}, {
header: $$("mode"),
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: $$("WildChar")},
{value: "regex", text: $$("RegEx")},
{value: "clsid", text: $$("CLSID")}
]
}, {
header: $$("pattern"),
property: "value",
type: "input"
}, {
header: $$("user_agent"),
property: "userAgent",
type: "select",
option: "static",
options: [
{value: "", text: "Chrome"},
{value: "ie9", text: "MSIE9"},
{value: "ie8", text: "MSIE8"},
{value: "ie7", text: "MSIE7"},
{value: "ff7win", text: "Firefox 7"},
{value: "ip5", text: "iPhone"},
{value: "ipad5", text: "iPad"}
]
}, {
header: $$("helper_script"),
property: "script",
type: "input"
}
];
var table;
var dirty = false;
function save() {
dirty = true;
}
function doSave() {
if (dirty) {
dirty = false;
setting.update();
}
}
function setReadonly(e) {
var line = e.data.line;
var id = line.attr('row');
if (id < 0) {
return;
}
var order = setting.order[id];
var divs = $('.listvalue', line);
if (order.position != 'custom') {
divs.addClass('readonly');
} else {
divs.removeClass('readonly');
}
}
$(window).blur(doSave);
function refresh() {
table.refresh();
}
// Main setting
$(document).ready(function() {
table = new List({
props: settingProps,
main: $('#tbSetting'),
lineEvents: {
update: setReadonly
},
getItems: function() {
return setting.order;
},
getItemProp: function(i, prop) {
if (prop in setting.order[i]) {
return setting.order[i][prop];
}
return setting.getItem(setting.order[i])[prop];
},
setItemProp: function(i, prop, value) {
if (prop in setting.order[i]) {
setting.order[i][prop] = value;
} else {
setting.getItem(setting.order[i])[prop] = value;
}
},
defaultValue: setting.createRule(),
count: function() {
return setting.order.length;
},
insert: function(id, newItem) {
setting.addCustomRule(newItem);
this.move(setting.order.length - 1, id);
},
remove: function(id) {
if (setting.order[id].position != 'custom') {
return true;
}
var identifier = setting.order[id].identifier;
delete setting.rules[identifier];
setting.order.splice(id, 1);
},
validate: function(id, rule) {
return setting.validateRule(rule);
}
});
$(table).bind('updated', save);
$('#addRule').bind('click', function() {
table.editNewLine();
});
$(table).bind('select', function() {
var line = table.selectedLine;
if (line < 0) {
$('#moveUp').attr('disabled', 'disabled');
$('#moveDown').attr('disabled', 'disabled');
$('#deleteRule').attr('disabled', 'disabled');
} else {
if (line != 0) {
$('#moveUp').removeAttr('disabled');
} else {
$('#moveUp').attr('disabled', 'disabled');
}
if (line != setting.order.length - 1) {
$('#moveDown').removeAttr('disabled');
} else {
$('#moveDown').attr('disabled', 'disabled');
}
if (setting.order[line].position != 'custom') {
$('#deleteRule').attr('disabled', 'disabled');
} else {
$('#deleteRule').removeAttr('disabled');
}
}
});
$('#moveUp').click(function() {
var line = table.selectedLine;
table.move(line, line - 1, true);
});
$('#moveDown').click(function() {
var line = table.selectedLine;
table.move(line, line + 1, true);
});
$('#deleteRule').click(function() {
var line = table.selectedLine;
table.remove(line);
});
table.init();
updateSession.bind('update', refresh);
updateSession.bind('updating', showUpdatingState);
updateSession.bind('progress', showUpdatingState);
updateSession.bind('complete', showUpdatingState);
});
window.onbeforeunload = function() {
updateSession.unbind('update', refresh);
updateSession.unbind('updating', showUpdatingState);
updateSession.unbind('progress', showUpdatingState);
updateSession.unbind('complete', showUpdatingState);
}
function setStatusNew(e) {
with (e.data) {
s = 'Custom';
color = '#33f';
$('button', line).text(s).css('background-color', color);
}
}
function setStatus(e) {
with (e.data) {
var id = line.attr('row');
var order = setting.order[id];
var rule = setting.getItem(order);
var s, color;
if (order.status == 'enabled') {
s = $$('Enabled');
color = '#0A0';
} else if (order.status == 'disabled') {
s = $$('Disabled');
color = 'indianred';
} else {
s = $$('Custom');
color = '#33f';
}
$('button', line).text(s).css('background-color', color);
}
}
function showTime(time) {
var never = 'Never'
if (time == 0) {
return never;
}
var delta = Date.now() - time;
if (delta < 0) {
return never;
}
function getDelta(delta) {
var sec = delta / 1000;
if (sec < 60) {
return [sec, 'second'];
}
var minute = sec / 60;
if (minute < 60) {
return [minute, 'minute'];
}
var hour = minute / 60;
if (hour < 60) {
return [hour, 'hour'];
}
var day = hour / 24;
return [day, 'day'];
}
var disp = getDelta(delta);
var v1 = Math.floor(disp[0]);
return v1 + ' ' + disp[1] + (v1 != 1 ? 's' : '') + " ago";
}
function showUpdatingState(e) {
if (updateSession.status == 'stop') {
$('#lastUpdate').text(showTime(setting.misc.lastUpdate));
} else {
$('#lastUpdate').text($$("update_progress") + updateSession.finish + '/' + updateSession.total);
}
}
$(document).ready(function() {
showUpdatingState({});
$('#doUpdate').click(function() {
setting.updateConfig(updateSession);
trackManualUpdate();
});
$('#log_enable').change(function(e) {
setting.misc.logEnabled = e.target.checked;
save();
})[0].checked = setting.misc.logEnabled;
$('#tracking').change(function(e) {
setting.misc.tracking = e.target.checked;
save();
})[0].checked = setting.misc.tracking;
});
$(document).ready(function() {
var help = 'http://code.google.com/p/np-activex/wiki/ExtensionHelp?wl=';
help = help + $$('wikicode');
$('.help').each(function() {
this.href = help;
});
});
$(window).load(function() {
$('#share').load('share.html');
if (background.firstUpgrade) {
background.firstUpgrade = false;
alert($$("upgrade_show"));
}
$('#follow').html('<iframe width="136" height="24" frameborder="0" allowtransparency="true" marginwidth="0" marginheight="0" scrolling="no" border="0" src="http://widget.weibo.com/relationship/followbutton.php?language=zh_cn&width=136&height=24&uid=2356524070&style=2&btn=red&dpc=1"></iframe>');
});
| zzhongster-npactivex | chrome/options.js | JavaScript | mpl11 | 8,110 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var FLASH_CLSID = '{d27cdb6e-ae6d-11cf-96b8-444553540000}';
var typeId = "application/x-itst-activex";
function executeScript(script) {
var scriptobj = document.createElement("script");
scriptobj.innerHTML = script;
var element = document.head || document.body ||
document.documentElement || document;
element.insertBefore(scriptobj, element.firstChild);
element.removeChild(scriptobj);
}
function checkParents(obj) {
var parent = obj;
var level = 0;
while (parent && parent.nodeType == 1) {
if (getComputedStyle(parent).display == 'none') {
var desp = obj.id + ' at level ' + level;
if (scriptConfig.none2block) {
parent.style.display = 'block';
parent.style.height = '0px';
parent.style.width = '0px';
log('Remove display:none for ' + desp);
} else {
log('Warning: Detected display:none for ' + desp);
}
}
parent = parent.parentNode;
++level;
}
}
function getLinkDest(url) {
if (typeof url != 'string') {
return url;
}
url = url.trim();
if (/^https?:\/\/.*/.exec(url)) {
return url;
}
if (url[0] == '/') {
if (url[1] == '/') {
return location.protocol + url;
} else {
return location.origin + url;
}
}
return location.href.replace(/\/[^\/]*$/, '/' + url);
}
var hostElement = null;
function enableobj(obj) {
// We can't use classid directly because it confuses the browser.
obj.setAttribute("clsid", getClsid(obj));
obj.removeAttribute("classid");
checkParents(obj);
var newObj = obj.cloneNode(true);
newObj.type = typeId;
// Remove all script nodes. They're executed.
var scripts = newObj.getElementsByTagName('script');
for (var i = 0; i < scripts.length; ++i) {
scripts[i].parentNode.removeChild(scripts[i]);
}
// Set codebase to full path.
var codebase = newObj.getAttribute('codebase');
if (codebase && codebase != '') {
newObj.setAttribute('codebase', getLinkDest(codebase));
}
newObj.activex_process = true;
obj.parentNode.insertBefore(newObj, obj);
obj.parentNode.removeChild(obj);
obj = newObj;
if (obj.id) {
var command = '';
if (obj.form && scriptConfig.formid) {
var form = obj.form.name;
command += "document.all." + form + "." + obj.id;
command + " = document.all." + obj.id + ';\n';
log('Set form[obj.id]: form: ' + form + ', object: ' + obj.id)
}
// Allow access by document.obj.id
if (obj.id && scriptConfig.documentid) {
command += "delete document." + obj.id + ";\n";
command += "document." + obj.id + '=' + obj.id + ';\n';
}
if (command) {
executeScript(command);
}
}
log("Enabled object, id: " + obj.id + " clsid: " + getClsid(obj));
return obj;
}
function getClsid(obj) {
if (obj.hasAttribute("clsid"))
return obj.getAttribute("clsid");
var clsid = obj.getAttribute("classid");
var compos = clsid.indexOf(":");
if (clsid.substring(0, compos).toLowerCase() != "clsid")
return;
clsid = clsid.substring(compos + 1);
return "{" + clsid + "}";
}
function notify(data) {
connect();
data.command = 'DetectControl';
port.postMessage(data);
}
function process(obj) {
if (obj.activex_process)
return;
if (onBeforeLoading.caller == enableobj ||
onBeforeLoading.caller == process ||
onBeforeLoading.caller == checkParents) {
log("Nested onBeforeLoading " + obj.id);
return;
}
if (obj.type == typeId) {
if (!config || !config.pageRule) {
// hack??? Deactive this object.
log("Deactive unexpected object " + obj.outerHTML);
return true;
}
log("Found objects created by client scripts");
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: config.pageRule.identifier
});
obj.activex_process = true;
return;
}
if (obj.type != "" || !obj.hasAttribute("classid"))
return;
if (getClsid(obj).toLowerCase() == FLASH_CLSID) {
return;
}
if (config == null) {
// Delay the process of this object.
// Hope config will be load soon.
log('Pending object ', obj.id);
pendingObjects.push(obj);
return;
}
obj.activex_process = true;
connect();
var clsid = getClsid(obj);
var rule = config.shouldEnable({href: location.href, clsid:clsid});
if (rule) {
obj = enableobj(obj);
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: rule.identifier
});
} else {
notify({href: location.href, clsid: clsid, actived: false});
}
}
function replaceDocument() {
var s = document.querySelectorAll('object[classid]');
log("found " + s.length + " object(s) on page");
for (var i = 0; i < s.length; ++i) {
process(s[i]);
}
};
function onBeforeLoading(event) {
var obj = event.target;
if (obj.nodeName == "OBJECT") {
log("BeforeLoading " + obj.id);
if (process(obj)) {
event.preventDefault();
}
}
}
function onError(event) {
var message = 'Error: ';
message += event.message;
message += ' at ';
message += event.filename;
message += ':';
message += event.lineno;
log(message);
return false;
}
function setUserAgent() {
if (!config.pageRule) {
return;
}
var agent = getUserAgent(config.pageRule.userAgent);
if (agent && agent != '') {
log("Set userAgent: " + config.pageRule.userAgent);
var js = "(function(agent) {";
js += "delete navigator.userAgent;";
js += "navigator.userAgent = agent;";
js += "delete navigator.appVersion;";
js += "navigator.appVersion = agent.substr(agent.indexOf('/') + 1);";
js += "if (agent.indexOf('MSIE') >= 0) {";
js += "delete navigator.appName;";
js += 'navigator.appName = "Microsoft Internet Explorer";}})("';
js += agent;
js += '")';
executeScript(js);
}
}
| zzhongster-npactivex | chrome/inject_actions.js | JavaScript | mpl11 | 6,249 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
// Updater events:
// error
// updating
// complete
// success
// itemupdated
// progress
// properties:
// status
// lastUpdate
// Can be used for debugging.
var defaultServer = "http://settings.np-activex.googlecode.com/hg/";
var server=localStorage.updateServer || defaultServer;
function ObjectWithEvent() {
this._events = {};
};
ObjectWithEvent.prototype = {
bind: function(name, func) {
if (!Array.isArray(this._events[name])) {
this._events[name] = [];
}
this._events[name].push(func);
},
unbind: function(name, func) {
if (!Array.isArray(this._events[name])) {
return;
}
for (var i = 0; i < this._events[name].length; ++i) {
if (this._events[name][i] == func) {
this._events[name].splice(i, 1);
break;
}
}
},
trigger: function(name, argument) {
if (this._events[name]) {
var handlers = this._events[name];
for (var i = 0; i < handlers.length; ++i) {
handlers[i].apply(this, argument);
}
}
}
};
function UpdateSession() {
ObjectWithEvent.call(this);
this.jqXHRs = [];
this.reset();
}
UpdateSession.prototype = {
__proto__: ObjectWithEvent.prototype,
updateProgress: function() {
with(this) {
if (finished == total) {
if (error == 0) {
this.trigger('success');
}
this.trigger('complete');
// Clear the requests.
this.jqXHRs = [];
} else {
this.trigger('progress');
}
}
},
updateFile: function(request) {
++this.total;
var session = this;
var jqXHR = UpdateSession.updateFile(request)
.fail(function(xhr, msg, thrown) {
++session.error;
session.trigger('error', [xhr, msg, thrown]);
session.updateProgress();
}).always(function() {
++session.finished;
session.updateProgress();
});
this.jqXHRs.push(jqXHR);
},
reset: function() {
this.finished = this.total = this.error = 0;
if (this.updateToken) {
clearTimeout(this.updateToken);
this.updateToken = undefined;
}
for (var i = 0; i < this.jqXHRs.length; ++i) {
this.jqXHRs[i].abort();
}
this.jqXHRs = [];
},
startUpdate: function() {
this.reset();
this.trigger('updating');
}
};
UpdateSession.prototype.__defineGetter__('status', function() {
if (this.finished == this.total) {
return "stop";
} else {
return "updating";
}
});
UpdateSession.setUpdateInterval= function(callback, session, interval) {
session.bind('complete', function() {
session.updateToken = setTimeout(callback, interval);
});
callback();
};
UpdateSession.updateFile = function(request) {
if (request.url.match(/^.*:\/\//) == null) {
request.url = server + request.url;
}
trackUpdateFile(request.url);
return $.ajax(request);
};
| zzhongster-npactivex | chrome/configUpdate.js | JavaScript | mpl11 | 3,163 |
<html>
<head>
<script src="jquery.js"></script>
<script src="notifybar.js"> </script>
<script src="i18n.js"> </script>
<link rel="stylesheet" type="text/css" href="notifybar.css" />
</head>
<body>
<span>
<span id="info">ActiveX controls can be used on this site</span>
<button id="enable">Enable them now!</button>
<button id="block" style="font-size:0.8em">Don't notify me for this site</button>
<button id="close">Close</button>
</span>
</body>
</html>
| zzhongster-npactivex | chrome/notifybar.html | HTML | mpl11 | 527 |
.list {
width: 800px;
height: 400px;
font-family: Arial, sans-serif;
overflow-x: hidden;
border: 3px solid #0D5995;
background-color: #0D5995;
padding: 1px;
padding-top: 10px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
.listscroll {
overflow-x: scroll;
overflow-y: scroll;
background-color: white;
}
.listitems {
display: inline-block;
}
.listvalue, .header {
display: inline-block;
width: 80px;
margin: 0px 6px;
}
.headers {
background-color: transparent;
position: relative;
white-space: nowrap;
display: inline-block;
color:white;
padding: 5px 0px;
}
.header{
white-space: normal;
}
.itemline {
height: 32px;
}
.itemline:nth-child(odd) {
background-color: white;
}
.itemline:nth-child(even) {
background-color: whitesmoke;
}
.itemline.selected {
background-color: #aaa;
}
.itemline:hover {
background-color: #bbcee9
}
.itemline.error,
.itemline.error:hover {
background-color: salmon;
}
.itemline > div {
white-space: nowrap;
padding: 4px 0px 0 0;
}
.itemline.editing > div{
padding: 3px 0px 0 0;
}
.valdisp, .valinput {
background-color: transparent;
width: 100%;
display: block;
}
.listvalue {
overflow-x: hidden;
}
.itemline.editing .listvalue:not(.readonly) .valdisp {
display: none;
}
.valdisp {
font-size: 13px;
}
.itemline:not(.editing) .valinput,
.listvalue.readonly .valinput {
display: none;
}
.itemline :focus {
outline: none;
}
.valinput {
border:1px solid #aaa;
background-color: white;
padding: 3px;
margin: 0;
}
.itemline .valinput:focus {
outline-color: rgba(0, 128, 256, 0.5);
outline: 5px auto rgba(0, 128, 256, 0.5);
}
| zzhongster-npactivex | chrome/list.css | CSS | mpl11 | 1,865 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
};
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1,
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay : function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with(list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if(!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with(this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == "number") {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
| zzhongster-npactivex | chrome/list.js | JavaScript | mpl11 | 11,700 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "HTMLDocumentContainer.h"
#include "npactivex.h"
#include <MsHTML.h>
const GUID HTMLDocumentContainer::IID_TopLevelBrowser = {0x4C96BE40, 0x915C, 0x11CF, {0x99, 0xD3, 0x00, 0xAA, 0x00, 0x4A, 0xE8, 0x37}};
HTMLDocumentContainer::HTMLDocumentContainer() : dispatcher(NULL)
{
}
void HTMLDocumentContainer::Init(NPP instance, ITypeLib *htmlLib) {
NPObjectProxy npWindow;
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &npWindow);
NPVariantProxy documentVariant;
if (NPNFuncs.getproperty(instance, npWindow, NPNFuncs.getstringidentifier("document"), &documentVariant)
&& NPVARIANT_IS_OBJECT(documentVariant)) {
NPObject *npDocument = NPVARIANT_TO_OBJECT(documentVariant);
dispatcher = new FakeDispatcher(instance, htmlLib, npDocument);
}
npp = instance;
}
HRESULT HTMLDocumentContainer::get_LocationURL(BSTR *str) {
NPObjectProxy npWindow;
NPNFuncs.getvalue(npp, NPNVWindowNPObject, &npWindow);
NPVariantProxy LocationVariant;
if (!NPNFuncs.getproperty(npp, npWindow, NPNFuncs.getstringidentifier("location"), &LocationVariant)
|| !NPVARIANT_IS_OBJECT(LocationVariant)) {
return E_FAIL;
}
NPObject *npLocation = NPVARIANT_TO_OBJECT(LocationVariant);
NPVariantProxy npStr;
if (!NPNFuncs.getproperty(npp, npLocation, NPNFuncs.getstringidentifier("href"), &npStr))
return E_FAIL;
CComBSTR bstr(npStr.value.stringValue.UTF8Length, npStr.value.stringValue.UTF8Characters);
*str = bstr.Detach();
return S_OK;
}
HRESULT STDMETHODCALLTYPE HTMLDocumentContainer::get_Document(
__RPC__deref_out_opt IDispatch **ppDisp) {
if (dispatcher)
return dispatcher->QueryInterface(DIID_DispHTMLDocument, (LPVOID*)ppDisp);
return E_FAIL;
}
HTMLDocumentContainer::~HTMLDocumentContainer(void)
{
}
| zzhongster-npactivex | ffactivex/HTMLDocumentContainer.cpp | C++ | mpl11 | 3,293 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <algorithm>
#include <string>
#include "GenericNPObject.h"
static NPObject*
AllocateGenericNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, false);
}
static NPObject*
AllocateMethodNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, true);
}
static void
DeallocateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
GenericNPObject *m = (GenericNPObject *)obj;
delete m;
}
static void
InvalidateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
((GenericNPObject *)obj)->Invalidate();
}
NPClass GenericNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateGenericNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
NPClass MethodNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateMethodNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
// Some standard JavaScript methods
bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) {
GenericNPObject *map = (GenericNPObject *)object;
if (!map || map->invalid) return false;
// no args expected or cared for...
std::string out;
std::vector<NPVariant>::iterator it;
for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) {
if (NPVARIANT_IS_VOID(*it)) {
out += ",";
}
else if (NPVARIANT_IS_NULL(*it)) {
out += ",";
}
else if (NPVARIANT_IS_BOOLEAN(*it)) {
if ((*it).value.boolValue) {
out += "true,";
}
else {
out += "false,";
}
}
else if (NPVARIANT_IS_INT32(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%d,", (*it).value.intValue);
out += tmp;
}
else if (NPVARIANT_IS_DOUBLE(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%f,", (*it).value.doubleValue);
out += tmp;
}
else if (NPVARIANT_IS_STRING(*it)) {
out += std::string((*it).value.stringValue.UTF8Characters,
(*it).value.stringValue.UTF8Characters + (*it).value.stringValue.UTF8Length);
out += ",";
}
else if (NPVARIANT_IS_OBJECT(*it)) {
out += "[object],";
}
}
// calculate how much space we need
std::string::size_type size = out.length();
char *s = (char *)NPNFuncs.memalloc(size * sizeof(char));
if (NULL == s) {
return false;
}
memcpy(s, out.c_str(), size);
s[size - 1] = 0; // overwrite the last ","
STRINGZ_TO_NPVARIANT(s, (*result));
return true;
}
// Some helpers
static void free_numeric_element(NPVariant elem) {
NPNFuncs.releasevariantvalue(&elem);
}
static void free_alpha_element(std::pair<const char *, NPVariant> elem) {
NPNFuncs.releasevariantvalue(&(elem.second));
}
// And now the GenericNPObject implementation
GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj):
invalid(false), defInvoker(NULL), defInvokerObject(NULL) {
NPVariant val;
INT32_TO_NPVARIANT(0, val);
immutables["length"] = val;
if (!isMethodObj) {
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &MethodNPObjectClass);
if (NULL == obj) {
throw NULL;
}
((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this);
OBJECT_TO_NPVARIANT(obj, val);
immutables["toString"] = val;
}
}
GenericNPObject::~GenericNPObject() {
for_each(immutables.begin(), immutables.end(), free_alpha_element);
for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element);
for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element);
}
bool GenericNPObject::HasMethod(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL != immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
}
return false;
}
bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(immutables[key])
&& immutables[key].value.objectValue->_class->invokeDefault) {
return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result);
}
}
else if (alpha_mapper.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(alpha_mapper[key])
&& alpha_mapper[key].value.objectValue->_class->invokeDefault) {
return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result);
}
}
}
return true;
}
bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (defInvoker) {
defInvoker(defInvokerObject, args, argCount, result);
}
return true;
}
// This method is also called before the JS engine attempts to add a new
// property, most likely it's trying to check that the key is supported.
// It only returns false if the string name was not found, or does not
// hold a callable object
bool GenericNPObject::HasProperty(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL == immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
return false;
}
return true;
}
static bool CopyNPVariant(NPVariant *dst, const NPVariant *src)
{
dst->type = src->type;
if (NPVARIANT_IS_STRING(*src)) {
NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8));
if (NULL == str) {
return false;
}
dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length;
memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length);
str[dst->value.stringValue.UTF8Length] = 0;
dst->value.stringValue.UTF8Characters = str;
}
else if (NPVARIANT_IS_OBJECT(*src)) {
NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src));
dst->value.objectValue = src->value.objectValue;
}
else {
dst->value = src->value;
}
return true;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (!CopyNPVariant(result, &(immutables[key]))) {
return false;
}
}
else if (alpha_mapper.count(key) > 0) {
if (!CopyNPVariant(result, &(alpha_mapper[key]))) {
return false;
}
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
if (!CopyNPVariant(result, &(numeric_mapper[key]))) {
return false;
}
}
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
// the key is already defined as immutable, check the new value type
if (value->type != immutables[key].type) {
return false;
}
// Seems ok, copy the new value
if (!CopyNPVariant(&(immutables[key]), value)) {
return false;
}
}
else if (!CopyNPVariant(&(alpha_mapper[key]), value)) {
return false;
}
}
else {
// assume int...
NPVariant var;
if (!CopyNPVariant(&var, value)) {
return false;
}
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (key >= numeric_mapper.size()) {
// there's a gap we need to fill
NPVariant pad;
VOID_TO_NPVARIANT(pad);
numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad);
}
numeric_mapper.at(key) = var;
NPVARIANT_TO_INT32(immutables["length"])++;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::RemoveProperty(NPIdentifier name) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (alpha_mapper.count(key) > 0) {
NPNFuncs.releasevariantvalue(&(alpha_mapper[key]));
alpha_mapper.erase(key);
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
NPNFuncs.releasevariantvalue(&(numeric_mapper[key]));
numeric_mapper.erase(numeric_mapper.begin() + key);
}
NPVARIANT_TO_INT32(immutables["length"])--;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) {
if (invalid) return false;
try {
*identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size());
if (NULL == *identifiers) {
return false;
}
*identifierCount = 0;
std::vector<NPVariant>::iterator it;
unsigned int i = 0;
char str[10] = "";
for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) {
// skip empty (padding) elements
if (NPVARIANT_IS_VOID(*it)) continue;
_snprintf(str, sizeof(str), "%u", i);
(*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str);
}
}
catch (...) {
}
return true;
}
| zzhongster-npactivex | ffactivex/GenericNPObject.cpp | C++ | mpl11 | 13,001 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "Host.h"
#include "npactivex.h"
#include "ObjectManager.h"
#include "objectProxy.h"
#include <npapi.h>
#include <npruntime.h>
CHost::CHost(NPP npp)
: ref_cnt_(1),
instance(npp),
lastObj(NULL)
{
}
CHost::~CHost(void)
{
UnRegisterObject();
np_log(instance, 3, "CHost::~CHost");
}
void CHost::AddRef()
{
++ref_cnt_;
}
void CHost::Release()
{
--ref_cnt_;
if (!ref_cnt_)
delete this;
}
NPObject *CHost::GetScriptableObject() {
return lastObj;
}
NPObject *CHost::RegisterObject() {
lastObj = CreateScriptableObject();
if (!lastObj)
return NULL;
lastObj->host = this;
NPObjectProxy embed;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed);
NPVariant var;
OBJECT_TO_NPVARIANT(lastObj, var);
// It doesn't matter which npp in setting.
NPNFuncs.setproperty(instance, embed, NPNFuncs.getstringidentifier("object"), &var);
return lastObj;
}
void CHost::UnRegisterObject() {
return;
NPObjectProxy embed;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed);
NPVariant var;
VOID_TO_NPVARIANT(var);
NPNFuncs.removeproperty(instance, embed, NPNFuncs.getstringidentifier("object"));
np_log(instance, 3, "UnRegisterObject");
lastObj = NULL;
}
NPP CHost::ResetNPP(NPP newNPP) {
// Doesn't support now..
_asm{int 3};
NPP ret = instance;
UnRegisterObject();
instance = newNPP;
np_log(newNPP, 3, "Reset NPP from 0x%08x to 0x%08x", ret, newNPP);
RegisterObject();
return ret;
}
ScriptBase *CHost::GetInternalObject(NPP npp, NPObject *embed_element)
{
NPVariantProxy var;
if (!NPNFuncs.getproperty(npp, embed_element, NPNFuncs.getstringidentifier("object"), &var))
return NULL;
if (NPVARIANT_IS_OBJECT(var)) {
ScriptBase *obj = static_cast<ScriptBase*>(NPVARIANT_TO_OBJECT(var));
NPNFuncs.retainobject(obj);
return obj;
}
return NULL;
}
ScriptBase *CHost::GetMyScriptObject() {
NPObjectProxy embed;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed);
return GetInternalObject(instance, embed);
} | zzhongster-npactivex | ffactivex/Host.cpp | C++ | mpl11 | 5,125 |
comment ?
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
.386
.model flat
__except_handler proto
.safeseh __except_handler
?
.386
.model flat
PUBLIC __KiUserExceptionDispatcher_hook
.data
public __KiUserExceptionDispatcher_origin
__KiUserExceptionDispatcher_origin dd 0
public __KiUserExceptionDispatcher_ATL_p
__KiUserExceptionDispatcher_ATL_p dd 0
.code
__KiUserExceptionDispatcher_hook proc
; The arguments are already on the stack
call __KiUserExceptionDispatcher_ATL_p
push __KiUserExceptionDispatcher_origin
ret
__KiUserExceptionDispatcher_hook endp
end
| zzhongster-npactivex | ffactivex/atlthunk_asm.asm | Assembly | mpl11 | 2,081 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <Windows.h>
#define ATL_THUNK_APIHOOK
EXCEPTION_DISPOSITION
__cdecl
_except_handler(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef EXCEPTION_DISPOSITION
(__cdecl *_except_handler_type)(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef struct tagATL_THUNK_PATTERN
{
LPBYTE pattern;
int pattern_size;
(void)(*enumerator)(struct _CONTEXT *);
}ATL_THUNK_PATTERN;
void InstallAtlThunkEnumeration();
void UninstallAtlThunkEnumeration(); | zzhongster-npactivex | ffactivex/atlthunk.h | C | mpl11 | 2,219 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "Host.h"
namespace ATL
{
template <typename T>
class CComObject;
}
class CControlEventSink;
class CControlSite;
class PropertyList;
class CAxHost : public CHost{
private:
CAxHost(const CAxHost &);
bool isValidClsID;
bool isKnown;
bool noWindow;
protected:
// The window handle to our plugin area in the browser
HWND Window;
WNDPROC OldProc;
// The class/prog id of the control
CLSID ClsID;
LPCWSTR CodeBaseUrl;
CComObject<CControlEventSink> *Sink;
RECT lastRect;
PropertyList *Props_;
public:
CAxHost(NPP inst);
~CAxHost();
static CLSID ParseCLSIDFromSetting(LPCSTR clsid, int length);
virtual NPP ResetNPP(NPP npp);
CComObject<CControlSite> *Site;
void SetNPWindow(NPWindow *window);
void ResetWindow();
PropertyList *Props() {
return Props_;
}
void Clear();
void setWindow(HWND win);
HWND getWinfow();
void UpdateRect(RECT rcPos);
bool verifyClsID(LPOLESTR oleClsID);
bool setClsID(const char *clsid);
bool setClsID(const CLSID& clsid);
CLSID getClsID() {
return this->ClsID;
}
void setNoWindow(bool value);
bool setClsIDFromProgID(const char *progid);
void setCodeBaseUrl(LPCWSTR clsid);
bool hasValidClsID();
bool CreateControl(bool subscribeToEvents);
void UpdateRectSize(LPRECT origRect);
void SetRectSize(LPSIZEL size);
bool AddEventHandler(wchar_t *name, wchar_t *handler);
HRESULT GetControlUnknown(IUnknown **pObj);
short HandleEvent(void *event);
ScriptBase *CreateScriptableObject();
};
| zzhongster-npactivex | ffactivex/axhost.h | C++ | mpl11 | 3,248 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType); | zzhongster-npactivex | ffactivex/authorize.h | C | mpl11 | 2,050 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ObjectManager.h"
#include "npactivex.h"
#include "host.h"
#include "axhost.h"
#include "objectProxy.h"
#include "scriptable.h"
#define MANAGER_OBJECT_ID "__activex_manager_IIID_"
NPClass ObjectManager::npClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ ObjectManager::_Allocate,
/* deallocate */ ObjectManager::Deallocate,
/* invalidate */ NULL,
/* hasMethod */ ObjectManager::HasMethod,
/* invoke */ ObjectManager::Invoke,
/* invokeDefault */ NULL,
/* hasProperty */ ObjectManager::HasProperty,
/* getProperty */ ObjectManager::GetProperty,
/* setProperty */ ObjectManager::SetProperty,
/* removeProperty */ NULL,
/* enumerate */ NULL,
/* construct */ NULL
};
ObjectManager::ObjectManager(NPP npp_) : CHost(npp_) {
}
ObjectManager::~ObjectManager(void)
{
for (uint i = 0; i < hosts.size(); ++i) {
hosts[i]->Release();
}
for (uint i = 0; i < dynamic_hosts.size(); ++i) {
dynamic_hosts[i]->Release();
}
}
ObjectManager* ObjectManager::GetManager(NPP npp) {
NPObjectProxy window;
NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window);
NPVariantProxy document, obj;
NPVariant par;
STRINGZ_TO_NPVARIANT(MANAGER_OBJECT_ID, par);
if (!NPNFuncs.getproperty(npp, window, NPNFuncs.getstringidentifier("document"), &document))
return NULL;
if (!NPNFuncs.invoke(npp, document.value.objectValue, NPNFuncs.getstringidentifier("getElementById"), &par, 1, &obj))
return NULL;
if (NPVARIANT_IS_OBJECT(obj)) {
NPObject *manager = NPVARIANT_TO_OBJECT(obj);
ScriptBase *script = GetInternalObject(npp, manager);
if (script)
return dynamic_cast<ObjectManager*>(script->host);
}
return NULL;
}
CHost* ObjectManager::GetPreviousObject(NPP npp) {
NPObjectProxy embed;
NPNFuncs.getvalue(npp, NPNVPluginElementNPObject, &embed);
return GetMyScriptObject()->host;
}
bool ObjectManager::HasMethod(NPObject *npobj, NPIdentifier name) {
return name == NPNFuncs.getstringidentifier("CreateControlByProgId");
}
bool ObjectManager::Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
ScriptManager *obj = static_cast<ScriptManager*>(npobj);
if (name == NPNFuncs.getstringidentifier("CreateControlByProgId")) {
if (argCount != 1 || !NPVARIANT_IS_STRING(args[0])) {
NPNFuncs.setexception(npobj, "Invalid arguments");
return false;
}
CAxHost* host = new CAxHost(obj->instance);
CStringA str(NPVARIANT_TO_STRING(args[0]).UTF8Characters, NPVARIANT_TO_STRING(args[0]).UTF8Length);
host->setClsIDFromProgID(str.GetString());
if (!host->CreateControl(false)) {
NPNFuncs.setexception(npobj, "Error creating object");
return false;
}
ObjectManager *manager = static_cast<ObjectManager*>(obj->host);
manager->dynamic_hosts.push_back(host);
OBJECT_TO_NPVARIANT(host->CreateScriptableObject(), *result);
return true;
}
return false;
}
bool ObjectManager::HasProperty(NPObject *npObj, NPIdentifier name) {
if (name == NPNFuncs.getstringidentifier("internalId"))
return true;
if (name == NPNFuncs.getstringidentifier("isValid"))
return true;
return false;
}
bool ObjectManager::GetProperty(NPObject *npObj, NPIdentifier name, NPVariant *value) {
if (name == NPNFuncs.getstringidentifier("internalId")) {
int len = strlen(MANAGER_OBJECT_ID);
char *stra = (char*)NPNFuncs.memalloc(len + 1);
strcpy(stra, MANAGER_OBJECT_ID);
STRINGN_TO_NPVARIANT(stra, len, *value);
return true;
}
if (name == NPNFuncs.getstringidentifier("isValid")) {
BOOLEAN_TO_NPVARIANT(TRUE, *value);
return true;
}
return false;
}
bool ObjectManager::SetProperty(NPObject *npObj, NPIdentifier name, const NPVariant *value) {
return false;
}
bool ObjectManager::RequestObjectOwnership(NPP newNpp, CAxHost* host) {
// reference count of host not changed.
for (uint i = 0; i < hosts.size(); ++i) {
if (hosts[i] == host) {
hosts[i] = hosts.back();
hosts.pop_back();
host->ResetNPP(newNpp);
newNpp->pdata = host;
return true;
}
}
return false;
}
void ObjectManager::RetainOwnership(CAxHost* host) {
hosts.push_back(host);
host->ResetNPP(instance);
}
ScriptBase* ObjectManager::CreateScriptableObject() {
ScriptBase* obj = static_cast<ScriptBase*>(NPNFuncs.createobject(instance, &npClass));
return obj;
}
void ObjectManager::Deallocate(NPObject *obj) {
delete static_cast<ScriptManager*>(obj);
} | zzhongster-npactivex | ffactivex/ObjectManager.cpp | C++ | mpl11 | 6,015 |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by npactivex.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| zzhongster-npactivex | ffactivex/resource.h | C | mpl11 | 403 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// npactivex.cpp : Defines the exported functions for the DLL application.
//
#include "npactivex.h"
#include "axhost.h"
#include "atlutil.h"
#include "objectProxy.h"
#include "authorize.h"
#include "common\PropertyList.h"
#include "common\ControlSite.h"
#include "ObjectManager.h"
// A list of trusted domains
// Each domain name may start with a '*' to specify that sub domains are
// trusted as well
// Note that a '.' is not enforced after the '*'
static const char *TrustedLocations[] = {NULL};
static const unsigned int numTrustedLocations = 0;
static const char *LocalhostName = "localhost";
static const bool TrustLocalhost = true;
//
// Gecko API
//
static const char PARAM_ID[] = "id";
static const char PARAM_NAME[] = "name";
static const char PARAM_CLSID[] = "clsid";
static const char PARAM_CLASSID[] = "classid";
static const char PARAM_PROGID[] = "progid";
static const char PARAM_DYNAMIC[] = "dynamic";
static const char PARAM_DEBUG[] = "debugLevel";
static const char PARAM_CODEBASEURL [] = "codeBase";
static const char PARAM_ONEVENT[] = "Event_";
static unsigned int log_level = -1;
// For catch breakpoints.
HRESULT NotImpl() {
return E_NOTIMPL;
}
void log_activex_logging(NPP instance, unsigned int level, const char* filename, int line, char *message, ...) {
if (instance == NULL || level > log_level) {
return;
}
NPObjectProxy globalObj = NULL;
NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log");
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
if (!NPNFuncs.hasmethod(instance, globalObj, commandId)) {
return;
}
int size = 0;
va_list list;
ATL::CStringA str;
ATL::CStringA str2;
va_start(list, message);
str.FormatV(message, list);
str2.Format("0x%08x %s:%d %s", instance, filename, line, str.GetString());
va_end(list);
NPVariant vars[1];
const char* formatted = str2.GetString();
STRINGZ_TO_NPVARIANT(formatted, vars[0]);
NPVariantProxy result1;
NPNFuncs.invoke(instance, globalObj, commandId, vars, 1, &result1);
}
void InstallLogAction(NPP instance) {
NPVariantProxy result1;
NPObjectProxy globalObj = NULL;
NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log");
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
if (NPNFuncs.hasmethod(instance, globalObj, commandId)) {
return;
}
const char* definition = "function __npactivex_log(message)"
"{var controlLogEvent='__npactivex_log_event__';"
"var e=document.createEvent('TextEvent');e.initTextEvent(controlLogEvent,false,false,null,message);window.dispatchEvent(e)}";
NPString def;
def.UTF8Characters = definition;
def.UTF8Length = strlen(definition);
NPNFuncs.evaluate(instance, globalObj, &def, &result1);
}
void
log_internal_console(NPP instance, unsigned int level, char *message, ...)
{
NPVariantProxy result1, result2;
NPVariant args;
NPObjectProxy globalObj = NULL, consoleObj = NULL;
bool rc = false;
char *formatted = NULL;
char *new_formatted = NULL;
int buff_len = 0;
int size = 0;
va_list list;
if (level > log_level) {
return;
}
buff_len = strlen(message);
char *new_message = (char *)malloc(buff_len + 10);
sprintf(new_message, "%%s %%d: %s", message);
buff_len += buff_len / 10;
formatted = (char *)calloc(1, buff_len);
while (true) {
va_start(list, message);
size = vsnprintf_s(formatted, buff_len, _TRUNCATE, new_message, list);
va_end(list);
if (size > -1 && size < buff_len)
break;
buff_len *= 2;
new_formatted = (char *)realloc(formatted, buff_len);
if (NULL == new_formatted) {
free(formatted);
return;
}
formatted = new_formatted;
new_formatted = NULL;
}
free(new_message);
if (instance == NULL) {
free(formatted);
return;
}
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
if (NPNFuncs.getproperty(instance, globalObj, NPNFuncs.getstringidentifier("console"), &result1)) {
consoleObj = NPVARIANT_TO_OBJECT(result1);
NPIdentifier handler = NPNFuncs.getstringidentifier("log");
STRINGZ_TO_NPVARIANT(formatted, args);
bool success = NPNFuncs.invoke(instance, consoleObj, handler, &args, 1, &result2);
}
free(formatted);
}
static bool
MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl)
{
USES_CONVERSION;
BOOL rc = false;
CUrl url;
if (!numTrustedLocations) {
return true;
}
rc = url.CrackUrl(matchUrl, ATL_URL_DECODE);
if (!rc) {
np_log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL");
return false;
}
if ( (url.GetScheme() == ATL_URL_SCHEME_FILE)
|| (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){
return TrustLocalhost;
}
for (unsigned int i = 0; i < numTrustedLocations; ++i) {
if (TrustedLocations[i][0] == '*') {
// sub domains are trusted
unsigned int len = strlen(TrustedLocations[i]);
bool match = 0;
if (url.GetHostNameLength() < len) {
// can't be a match
continue;
}
--len; // skip the '*'
match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name
TrustedLocations[i] + 1, // skip the '*'
len) == 0 ? true : false;
if (match) {
return true;
}
}
else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) {
return true;
}
}
return false;
}
static bool
VerifySiteLock(NPP instance)
{
// This approach is not used.
return true;
#if 0
USES_CONVERSION;
NPObjectProxy globalObj;
NPIdentifier identifier;
NPVariantProxy varLocation;
NPVariantProxy varHref;
bool rc = false;
// Get the window object.
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
// Create a "location" identifier.
identifier = NPNFuncs.getstringidentifier("location");
// Get the location property from the window object (which is another object).
rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation);
if (!rc){
np_log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object");
return false;
}
// Get a pointer to the "location" object.
NPObject *locationObj = varLocation.value.objectValue;
// Create a "href" identifier.
identifier = NPNFuncs.getstringidentifier("href");
// Get the location property from the location object.
rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref);
if (!rc) {
np_log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property");
return false;
}
rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters));
if (false == rc) {
np_log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted");
}
return rc;
#endif
}
static bool FillProperties(CAxHost *host, NPP instance) {
NPObjectProxy embed;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed);
// Traverse through childs
NPVariantProxy var_childNodes;
NPVariantProxy var_length;
NPVariant str_name, str_value;
if (!NPNFuncs.getproperty(instance, embed, NPNFuncs.getstringidentifier("childNodes"), &var_childNodes))
return true;
if (!NPVARIANT_IS_OBJECT(var_childNodes))
return true;
NPObject *childNodes = NPVARIANT_TO_OBJECT(var_childNodes);
VOID_TO_NPVARIANT(var_length);
if (!NPNFuncs.getproperty(instance, childNodes, NPNFuncs.getstringidentifier("length"), &var_length))
return true;
USES_CONVERSION;
int length = 0;
if (NPVARIANT_IS_INT32(var_length))
length = NPVARIANT_TO_INT32(var_length);
if (NPVARIANT_IS_DOUBLE(var_length))
length = static_cast<int>(NPVARIANT_TO_DOUBLE(var_length));
NPIdentifier idname = NPNFuncs.getstringidentifier("nodeName");
NPIdentifier idAttr = NPNFuncs.getstringidentifier("getAttribute");
STRINGZ_TO_NPVARIANT("name", str_name);
STRINGZ_TO_NPVARIANT("value", str_value);
for (int i = 0; i < length; ++i) {
NPIdentifier id = NPNFuncs.getintidentifier(i);
NPVariantProxy var_par;
NPVariantProxy var_nodeName, var_parName, var_parValue;
if (!NPNFuncs.getproperty(instance, childNodes, id, &var_par))
continue;
if (!NPVARIANT_IS_OBJECT(var_par))
continue;
NPObject *param_obj = NPVARIANT_TO_OBJECT(var_par);
if (!NPNFuncs.getproperty(instance, param_obj, idname, &var_nodeName))
continue;
if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "embed", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) == 0) {
NPVariantProxy type;
NPVariant typestr;
STRINGZ_TO_NPVARIANT("type", typestr);
if (!NPNFuncs.invoke(instance, param_obj, idAttr, &typestr, 1, &type))
continue;
if (!NPVARIANT_IS_STRING(type))
continue;
CStringA command, mimetype(NPVARIANT_TO_STRING(type).UTF8Characters, NPVARIANT_TO_STRING(type).UTF8Length);
command.Format("navigator.mimeTypes[\'%s\'] != null", mimetype);
NPString str = {command.GetString(), command.GetLength()};
NPVariantProxy value;
NPObjectProxy window;
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &window);
NPNFuncs.evaluate(instance, window, &str, &value);
if (NPVARIANT_IS_BOOLEAN(value) && NPVARIANT_TO_BOOLEAN(value)) {
// The embed is supported by chrome. Fallback automatically.
return false;
}
}
if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "param", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) != 0)
continue;
if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_name, 1, &var_parName))
continue;
if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_value, 1, &var_parValue))
continue;
if (!NPVARIANT_IS_STRING(var_parName) || !NPVARIANT_IS_STRING(var_parValue))
continue;
CComBSTR paramName(NPVARIANT_TO_STRING(var_parName).UTF8Length, NPVARIANT_TO_STRING(var_parName).UTF8Characters);
CComBSTR paramValue(NPVARIANT_TO_STRING(var_parValue).UTF8Length, NPVARIANT_TO_STRING(var_parValue).UTF8Characters);
// Add named parameter to list
CComVariant v(paramValue);
host->Props()->AddOrReplaceNamedProperty(paramName, v);
}
return true;
}
NPError CreateControl(NPP instance, int16 argc, char *argn[], char *argv[], CAxHost **phost) {
// Create a plugin instance, the actual control will be created once we
// are given a window handle
USES_CONVERSION;
PropertyList events;
CAxHost *host = new CAxHost(instance);
*phost = host;
if (!host) {
np_log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host");
return NPERR_OUT_OF_MEMORY_ERROR;
}
// Iterate over the arguments we've been passed
for (int i = 0; i < argc; ++i) {
// search for any needed information: clsid, event handling directives, etc.
if (strnicmp(argn[i], PARAM_CLASSID, sizeof(PARAM_CLASSID)) == 0) {
char clsid[100];
strncpy(clsid, argv[i], 80);
strcat(clsid, "}");
char* id = strchr(clsid, ':');
if (id == NULL)
continue;
*id = '{';
host->setClsID(id);
}
else if (0 == strnicmp(argn[i], PARAM_NAME, sizeof(PARAM_NAME)) ||
0 == strnicmp(argn[i], PARAM_ID, sizeof(PARAM_ID))) {
np_log(instance, 1, "instance %s: %s", argn[i], argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_CLSID, sizeof(PARAM_CLSID))) {
// The class id of the control we are asked to load
host->setClsID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_PROGID, sizeof(PARAM_PROGID))) {
// The class id of the control we are asked to load
host->setClsIDFromProgID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_DEBUG, sizeof(PARAM_DEBUG))) {
// Logging verbosity
log_level = atoi(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_ONEVENT, sizeof(PARAM_ONEVENT))) {
// A request to handle one of the activex's events in JS
events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i])));
}
else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, sizeof(PARAM_CODEBASEURL))) {
if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) {
host->setCodeBaseUrl(A2W(argv[i]));
}
else {
np_log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location");
}
}
else if (0 == strnicmp(argn[i], PARAM_DYNAMIC, sizeof(PARAM_DYNAMIC))) {
host->setNoWindow(true);
}
}
if (!FillProperties(host, instance)) {
return NPERR_GENERIC_ERROR;
}
// Make sure we have all the information we need to initialize a new instance
if (!host->hasValidClsID()) {
np_log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID");
// create later.
return NPERR_NO_ERROR;
}
instance->pdata = host;
// if no events were requested, don't fail if subscribing fails
if (!host->CreateControl(events.GetSize() ? true : false)) {
np_log(instance, 0, "AxHost.NPP_New: failed to create the control");
return NPERR_GENERIC_ERROR;
}
for (unsigned int j = 0; j < events.GetSize(); j++) {
if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) {
//rc = NPERR_GENERIC_ERROR;
//break;
}
}
np_log(instance, 1, "%08x AxHost.NPP_New: Create control finished", instance);
return NPERR_NO_ERROR;
}
/*
* Create a new plugin instance, most probably through an embed/object HTML
* element.
*
* Any private data we want to keep for this instance can be saved into
* [instance->pdata].
* [saved] might hold information a previous instance that was invoked from the
* same URL has saved for us.
*/
NPError
NPP_New(NPMIMEType pluginType,
NPP instance, uint16 mode,
int16 argc, char *argn[],
char *argv[], NPSavedData *saved)
{
NPError rc = NPERR_NO_ERROR;
NPObject *browser = NULL;
int16 i = 0;
if (!instance || (0 == NPNFuncs.size)) {
return NPERR_INVALID_PARAM;
}
instance->pdata = NULL;
#ifdef NO_REGISTRY_AUTHORIZE
// Verify that we're running from a trusted location
if (!VerifySiteLock(instance)) {
return NPERR_GENERIC_ERROR;
}
#else
if (!TestAuthorization (instance,
argc,
argn,
argv,
pluginType)) {
return NPERR_GENERIC_ERROR;
}
#endif
InstallLogAction(instance);
if (stricmp(pluginType, "application/x-itst-activex") == 0) {
CAxHost *host = NULL;
/*
ObjectManager* manager = ObjectManager::GetManager(instance);
if (manager && !(host = dynamic_cast<CAxHost*>(manager->GetPreviousObject(instance)))) {
// Object is created before
manager->RequestObjectOwnership(instance, host);
} else
*/
{
rc = CreateControl(instance, argc, argn, argv, &host);
if (NPERR_NO_ERROR != rc) {
delete host;
instance->pdata = NULL;
host = NULL;
return rc;
}
}
if (host) {
host->RegisterObject();
instance->pdata = host;
}
} else if (stricmp(pluginType, "application/activex-manager") == 0) {
// disabled now!!
return rc = NPERR_GENERIC_ERROR;
ObjectManager *manager = new ObjectManager(instance);
manager->RegisterObject();
instance->pdata = manager;
}
return rc;
}
/*
* Destroy an existing plugin instance.
*
* [save] can be used to save information for a future instance of our plugin
* that'll be invoked by the same URL.
*/
NPError
NPP_Destroy(NPP instance, NPSavedData **save)
{
if (!instance) {
return NPERR_INVALID_PARAM;
}
CHost *host = (CHost *)instance->pdata;
if (host) {
np_log(instance, 0, "NPP_Destroy: destroying the control...");
//host->UnRegisterObject();
host->Release();
instance->pdata = NULL;
/*
ObjectManager *manager = ObjectManager::GetManager(instance);
CAxHost *axHost = dynamic_cast<CAxHost*>(host);
if (manager && axHost) {
manager->RetainOwnership(axHost);
} else {
np_log(instance, 0, "NPP_Destroy: destroying the control...");
host->Release();
instance->pdata = NULL;
}*/
}
return NPERR_NO_ERROR;
}
/*
* Sets an instance's window parameters.
*/
NPError
NPP_SetWindow(NPP instance, NPWindow *window)
{
CAxHost *host = NULL;
if (!instance || !instance->pdata) {
return NPERR_INVALID_PARAM;
}
host = dynamic_cast<CAxHost*>((CHost *)instance->pdata);
if (host) {
host->SetNPWindow(window);
}
return NPERR_NO_ERROR;
}
| zzhongster-npactivex | ffactivex/npactivex.cpp | C++ | mpl11 | 18,363 |
maxVf = 200
# Generating the header
head = """// Copyright qiuc12@gmail.com
// This file is generated autmatically by python. DONT MODIFY IT!
#pragma once
#include <OleAuto.h>
class FakeDispatcher;
HRESULT DualProcessCommand(int commandId, FakeDispatcher *disp, ...);
extern "C" void DualProcessCommandWrap();
class FakeDispatcherBase : public IDispatch {
private:"""
pattern = """
\tvirtual HRESULT __stdcall fv{0}(char x) {{
\t\tva_list va = &x;
\t\tHRESULT ret = ProcessCommand({0}, va);
\t\tva_end(va);
\t\treturn ret;
\t}}
"""
pattern = """
\tvirtual HRESULT __stdcall fv{0}();"""
end = """
protected:
\tconst static int kMaxVf = {0};
}};
"""
f = open("FakeDispatcherBase.h", "w")
f.write(head)
for i in range(0, maxVf):
f.write(pattern.format(i))
f.write(end.format(maxVf))
f.close()
head = """; Copyright qiuc12@gmail.com
; This file is generated automatically by python. DON'T MODIFY IT!
"""
f = open("FakeDispatcherBase.asm", "w")
f.write(head)
f.write(".386\n")
f.write(".model flat\n")
f.write("_DualProcessCommandWrap proto\n")
ObjFormat = "?fv{0}@FakeDispatcherBase@@EAGJXZ"
for i in range(0, maxVf):
f.write("PUBLIC " + ObjFormat.format(i) + "\n")
f.write(".code\n")
for i in range(0, maxVf):
f.write(ObjFormat.format(i) + " proc\n")
f.write(" push {0}\n".format(i))
f.write(" jmp _DualProcessCommandWrap\n")
f.write(ObjFormat.format(i) + " endp\n")
f.write("\nend\n")
f.close()
| zzhongster-npactivex | ffactivex/FakeDispatcherBase_gen.py | Python | mpl11 | 1,484 |
comment ?
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
?
.386
.model flat
PUBLIC _DualProcessCommandWrap
_DualProcessCommand proto
.code
_DualProcessCommandWrap proc
push 0
call _DualProcessCommand
; Thanks god we can use ecx, edx for free
pop ecx ; length of par
pop edx ; command id
pop edx ; return address
add esp, ecx
jmp edx
_DualProcessCommandWrap endp
end
| zzhongster-npactivex | ffactivex/FakeDispatcherWrap.asm | Assembly | mpl11 | 1,879 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <Windows.h>
#include <OleAuto.h>
#include <npapi.h>
#include <npruntime.h>
#include "FakeDispatcherBase.h"
#include "objectProxy.h"
extern ITypeLib *pHtmlLib;
class CAxHost;
EXTERN_C const IID IID_IFakeDispatcher;
class FakeDispatcher :
public FakeDispatcherBase
{
private:
class FakeDispatcherEx: IDispatchEx {
private:
FakeDispatcher *target;
public:
FakeDispatcherEx(FakeDispatcher *target) : target(target) {
}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
__RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) {
return target->QueryInterface(riid, ppvObject);
}
virtual ULONG STDMETHODCALLTYPE AddRef( void) {
return target->AddRef();
}
virtual ULONG STDMETHODCALLTYPE Release( void) {
return target->Release();
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(
__RPC__out UINT *pctinfo) {
return target->GetTypeInfoCount(pctinfo);
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(
UINT iTInfo,
LCID lcid,
__RPC__deref_out_opt ITypeInfo **ppTInfo) {
return target->GetTypeInfo(iTInfo, lcid, ppTInfo);
}
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(
__RPC__in REFIID riid,
__RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
__RPC__in_range(0,16384) UINT cNames,
LCID lcid,
__RPC__out_ecount_full(cNames) DISPID *rgDispId) {
return target->GetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispId);
}
virtual HRESULT STDMETHODCALLTYPE Invoke(
DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr) {
return target->Invoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
virtual HRESULT STDMETHODCALLTYPE GetDispID(
__RPC__in BSTR bstrName,
DWORD grfdex,
__RPC__out DISPID *pid);
virtual HRESULT STDMETHODCALLTYPE InvokeEx(
__in DISPID id,
__in LCID lcid,
__in WORD wFlags,
__in DISPPARAMS *pdp,
__out_opt VARIANT *pvarRes,
__out_opt EXCEPINFO *pei,
__in_opt IServiceProvider *pspCaller);
virtual HRESULT STDMETHODCALLTYPE DeleteMemberByName(
__RPC__in BSTR bstrName,
DWORD grfdex);
virtual HRESULT STDMETHODCALLTYPE DeleteMemberByDispID(DISPID id);
virtual HRESULT STDMETHODCALLTYPE GetMemberProperties(
DISPID id,
DWORD grfdexFetch,
__RPC__out DWORD *pgrfdex);
virtual HRESULT STDMETHODCALLTYPE GetMemberName(
DISPID id,
__RPC__deref_out_opt BSTR *pbstrName);
virtual HRESULT STDMETHODCALLTYPE GetNextDispID(
DWORD grfdex,
DISPID id,
__RPC__out DISPID *pid);
virtual HRESULT STDMETHODCALLTYPE GetNameSpaceParent(
__RPC__deref_out_opt IUnknown **ppunk);
};
public:
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
__RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef( void) {
++ref;
return ref;
}
virtual ULONG STDMETHODCALLTYPE Release( void) {
--ref;
if (ref == 0)
delete this;
return ref;
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(
__RPC__out UINT *pctinfo) {
*pctinfo = 1;
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(
UINT iTInfo,
LCID lcid,
__RPC__deref_out_opt ITypeInfo **ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(
__RPC__in REFIID riid,
__RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
__RPC__in_range(0,16384) UINT cNames,
LCID lcid,
__RPC__out_ecount_full(cNames) DISPID *rgDispId);
virtual HRESULT STDMETHODCALLTYPE Invoke(
DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr);
NPObject *getObject() {
return npObject;
}
FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object);
~FakeDispatcher(void);
HRESULT ProcessCommand(int ID, int *parlength,va_list &list);
//friend HRESULT __cdecl DualProcessCommand(int parlength, int commandId, FakeDispatcher *disp, ...);
private:
static ITypeInfo* npTypeInfo;
const static int DISPATCH_VTABLE = 7;
FakeDispatcherEx *extended;
NPP npInstance;
NPObject *npObject;
ITypeLib *typeLib;
ITypeInfo *typeInfo;
CAxHost *internalObj;
bool HasValidTypeInfo();
int ref;
DWORD dualType;
#ifdef DEBUG
char name[50];
char tag[100];
GUID interfaceid;
#endif
UINT FindFuncByVirtualId(int vtbId);
};
| zzhongster-npactivex | ffactivex/FakeDispatcher.h | C++ | mpl11 | 6,240 |
// stdafx.cpp : source file that includes just the standard includes
// npactivex.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "npactivex.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| zzhongster-npactivex | ffactivex/stdafx.cpp | C++ | mpl11 | 299 |
#pragma once
#include <npapi.h>
#include <npruntime.h>
#include <OleAuto.h>
#include "scriptable.h"
#include "npactivex.h"
#include <map>
using std::map;
using std::pair;
class ScriptFunc : public NPObject
{
private:
static NPClass npClass;
Scriptable *script;
MEMBERID dispid;
void setControl(Scriptable *script, MEMBERID dispid) {
NPNFuncs.retainobject(script);
this->script = script;
this->dispid = dispid;
}
static map<pair<Scriptable*, MEMBERID>, ScriptFunc*> M;
bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result);
public:
ScriptFunc(NPP inst);
~ScriptFunc(void);
static NPObject *_Allocate(NPP npp, NPClass *npClass) {
return new ScriptFunc(npp);
}
static void _Deallocate(NPObject *object) {
ScriptFunc *obj = (ScriptFunc*)(object);
delete obj;
}
static ScriptFunc* GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid);
static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result) {
return ((ScriptFunc *)npobj)->InvokeDefault(args, argCount, result);
}
};
| zzhongster-npactivex | ffactivex/ScriptFunc.h | C++ | mpl11 | 1,139 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// This function is totally disabled now.
#if 0
#include <stdio.h>
#include <windows.h>
#include <winreg.h>
#include "npactivex.h"
#include "atlutil.h"
#include "authorize.h"
// ----------------------------------------------------------------------------
#define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/npactivex\\MimeTypes\\application/x-itst-activex"
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorizationUTF8 (const char *MimeType,
const char *AuthorizationType,
const char *DocumentUrl,
const char *ProgramId);
BOOL TestExplicitAuthorization (const wchar_t *MimeType,
const wchar_t *AuthorizationType,
const wchar_t *DocumentUrl,
const wchar_t *ProgramId);
BOOL WildcardMatch (const wchar_t *Mask,
const wchar_t *Value);
HKEY FindKey (const wchar_t *MimeType,
const wchar_t *AuthorizationType);
// ---------------------------------------------------------------------------
HKEY BaseKeys[] = {
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE
};
// ----------------------------------------------------------------------------
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType)
{
BOOL ret = FALSE;
NPObject *globalObj = NULL;
NPIdentifier identifier;
NPVariant varLocation;
NPVariant varHref;
bool rc = false;
int16 i;
char *wrkHref;
#ifdef NDEF
_asm{int 3};
#endif
if (Instance == NULL) {
return (FALSE);
}
// Determine owning document
// Get the window object.
NPNFuncs.getvalue(Instance,
NPNVWindowNPObject,
&globalObj);
// Create a "location" identifier.
identifier = NPNFuncs.getstringidentifier("location");
// Get the location property from the window object (which is another object).
rc = NPNFuncs.getproperty(Instance,
globalObj,
identifier,
&varLocation);
NPNFuncs.releaseobject(globalObj);
if (!rc){
np_log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object");
return false;
}
// Get a pointer to the "location" object.
NPObject *locationObj = varLocation.value.objectValue;
// Create a "href" identifier.
identifier = NPNFuncs.getstringidentifier("href");
// Get the location property from the location object.
rc = NPNFuncs.getproperty(Instance,
locationObj,
identifier,
&varHref);
NPNFuncs.releasevariantvalue(&varLocation);
if (!rc) {
np_log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property");
return false;
}
ret = TRUE;
wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1);
memcpy(wrkHref,
varHref.value.stringValue.UTF8Characters,
varHref.value.stringValue.UTF8Length);
wrkHref[varHref.value.stringValue.UTF8Length] = 0x00;
NPNFuncs.releasevariantvalue(&varHref);
for (i = 0;
i < ArgC;
++i) {
// search for any needed information: clsid, event handling directives, etc.
if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) {
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_CLSID,
wrkHref,
ArgV[i]);
} else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) {
// The class id of the control we are asked to load
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_PROGID,
wrkHref,
ArgV[i]);
} else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) {
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_CODEBASEURL,
wrkHref,
ArgV[i]);
}
}
np_log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False");
return (ret);
}
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorizationUTF8 (const char *MimeType,
const char *AuthorizationType,
const char *DocumentUrl,
const char *ProgramId)
{
USES_CONVERSION;
BOOL ret;
ret = TestExplicitAuthorization(A2W(MimeType),
A2W(AuthorizationType),
A2W(DocumentUrl),
A2W(ProgramId));
return (ret);
}
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorization (const wchar_t *MimeType,
const wchar_t *AuthorizationType,
const wchar_t *DocumentUrl,
const wchar_t *ProgramId)
{
BOOL ret = FALSE;
#ifndef NO_REGISTRY_AUTHORIZE
HKEY hKey;
HKEY hSubKey;
ULONG i;
ULONG j;
ULONG keyNameLen;
ULONG valueNameLen;
wchar_t keyName[_MAX_PATH];
wchar_t valueName[_MAX_PATH];
if (DocumentUrl == NULL) {
return (FALSE);
}
if (ProgramId == NULL) {
return (FALSE);
}
#ifdef NDEF
MessageBox(NULL,
DocumentUrl,
ProgramId,
MB_OK);
#endif
if ((hKey = FindKey(MimeType,
AuthorizationType)) != NULL) {
for (i = 0;
!ret;
i++) {
keyNameLen = sizeof(keyName);
if (RegEnumKey(hKey,
i,
keyName,
keyNameLen) == ERROR_SUCCESS) {
if (WildcardMatch(keyName,
DocumentUrl)) {
if (RegOpenKeyEx(hKey,
keyName,
0,
KEY_QUERY_VALUE,
&hSubKey) == ERROR_SUCCESS) {
for (j = 0;
;
j++) {
valueNameLen = sizeof(valueName);
if (RegEnumValue(hSubKey,
j,
valueName,
&valueNameLen,
NULL,
NULL,
NULL,
NULL) != ERROR_SUCCESS) {
break;
}
if (WildcardMatch(valueName,
ProgramId)) {
ret = TRUE;
break;
}
}
RegCloseKey(hSubKey);
}
if (ret) {
break;
}
}
} else {
break;
}
}
RegCloseKey(hKey);
}
#endif
return (ret);
}
// ----------------------------------------------------------------------------
BOOL WildcardMatch (const wchar_t *Mask,
const wchar_t *Value)
{
size_t i;
size_t j = 0;
size_t maskLen;
size_t valueLen;
maskLen = wcslen(Mask);
valueLen = wcslen(Value);
for (i = 0;
i < maskLen + 1;
i++) {
if (Mask[i] == '?') {
j++;
continue;
}
if (Mask[i] == '*') {
for (;
j < valueLen + 1;
j++) {
if (WildcardMatch(Mask + i + 1,
Value + j)) {
return (TRUE);
}
}
return (FALSE);
}
if ((j <= valueLen) &&
(Mask[i] == tolower(Value[j]))) {
j++;
continue;
}
return (FALSE);
}
return (TRUE);
}
// ----------------------------------------------------------------------------
HKEY FindKey (const wchar_t *MimeType,
const wchar_t *AuthorizationType)
{
HKEY ret = NULL;
HKEY plugins;
wchar_t searchKey[_MAX_PATH];
wchar_t pluginName[_MAX_PATH];
DWORD j;
size_t i;
for (i = 0;
i < ARRAYSIZE(BaseKeys);
i++) {
if (RegOpenKeyEx(BaseKeys[i],
L"SOFTWARE\\MozillaPlugins",
0,
KEY_ENUMERATE_SUB_KEYS,
&plugins) == ERROR_SUCCESS) {
for (j = 0;
ret == NULL;
j++) {
if (RegEnumKey(plugins,
j,
pluginName,
sizeof(pluginName)) != ERROR_SUCCESS) {
break;
}
wsprintf(searchKey,
L"%s\\MimeTypes\\%s\\%s",
pluginName,
MimeType,
AuthorizationType);
if (RegOpenKeyEx(plugins,
searchKey,
0,
KEY_ENUMERATE_SUB_KEYS,
&ret) == ERROR_SUCCESS) {
break;
}
ret = NULL;
}
RegCloseKey(plugins);
if (ret != NULL) {
break;
}
}
}
return (ret);
}
#endif | zzhongster-npactivex | ffactivex/authorize.cpp | C++ | mpl11 | 10,040 |
#include "ScriptFunc.h"
NPClass ScriptFunc::npClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ ScriptFunc::_Allocate,
/* deallocate */ ScriptFunc::_Deallocate,
/* invalidate */ NULL,
/* hasMethod */ NULL, //Scriptable::_HasMethod,
/* invoke */ NULL, //Scriptable::_Invoke,
/* invokeDefault */ ScriptFunc::_InvokeDefault,
/* hasProperty */ NULL,
/* getProperty */ NULL,
/* setProperty */ NULL,
/* removeProperty */ NULL,
/* enumerate */ NULL,
/* construct */ NULL
};
map<pair<Scriptable*, MEMBERID>, ScriptFunc*> ScriptFunc::M;
ScriptFunc::ScriptFunc(NPP inst)
{
}
ScriptFunc::~ScriptFunc(void)
{
if (script) {
pair<Scriptable*, MEMBERID> index(script, dispid);
NPNFuncs.releaseobject(script);
M.erase(index);
}
}
ScriptFunc* ScriptFunc::GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid) {
pair<Scriptable*, MEMBERID> index(script, dispid);
if (M[index] == NULL) {
ScriptFunc *new_obj = (ScriptFunc*)NPNFuncs.createobject(npp, &npClass);
NPNFuncs.retainobject(script);
new_obj->setControl(script, dispid);
M[index] = new_obj;
} else {
NPNFuncs.retainobject(M[index]);
}
return M[index];
}
bool ScriptFunc::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (!script)
return false;
bool ret = script->InvokeID(dispid, args, argCount, result);
if (!ret) {
np_log(script->instance, 0, "Invoke failed, DISPID 0x%08x", dispid);
}
return ret;
} | zzhongster-npactivex | ffactivex/ScriptFunc.cpp | C++ | mpl11 | 1,507 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <comdef.h>
#include "npactivex.h"
#include "scriptable.h"
#include "common/PropertyList.h"
#include "common/PropertyBag.h"
#include "common/ItemContainer.h"
#include "common/ControlSite.h"
#include "common/ControlSiteIPFrame.h"
#include "common/ControlEventSink.h"
#include "axhost.h"
#include "HTMLDocumentContainer.h"
#ifdef NO_REGISTRY_AUTHORIZE
static const char *WellKnownProgIds[] = {
NULL
};
static const char *WellKnownClsIds[] = {
NULL
};
#endif
static const bool AcceptOnlyWellKnown = false;
static const bool TrustWellKnown = true;
static bool
isWellKnownProgId(const char *progid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!progid) {
return false;
}
while (WellKnownProgIds[i]) {
if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static bool
isWellKnownClsId(const char *clsid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!clsid) {
return false;
}
while (WellKnownClsIds[i]) {
if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result;
CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA);
if (!host) {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
switch (msg)
{
case WM_SETFOCUS:
case WM_KILLFOCUS:
case WM_SIZE:
if (host->Site) {
host->Site->OnDefWindowMessage(msg, wParam, lParam, &result);
return result;
}
else {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Window being destroyed
case WM_DESTROY:
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return true;
}
CAxHost::CAxHost(NPP inst):
CHost(inst),
ClsID(CLSID_NULL),
isValidClsID(false),
Sink(NULL),
Site(NULL),
Window(NULL),
OldProc(NULL),
Props_(new PropertyList),
isKnown(false),
CodeBaseUrl(NULL),
noWindow(false)
{
}
CAxHost::~CAxHost()
{
np_log(instance, 0, "AxHost.~AXHost: destroying the control...");
if (Window){
if (OldProc) {
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
OldProc = NULL;
}
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
Clear();
delete Props_;
}
void CAxHost::Clear() {
if (Sink) {
Sink->UnsubscribeFromEvents();
Sink->Release();
Sink = NULL;
}
if (Site) {
Site->Detach();
Site->Release();
Site = NULL;
}
if (Props_) {
Props_->Clear();
}
CoFreeUnusedLibraries();
}
CLSID CAxHost::ParseCLSIDFromSetting(LPCSTR str, int length) {
CLSID ret;
CStringW input(str, length);
if (SUCCEEDED(CLSIDFromString(input, &ret)))
return ret;
int pos = input.Find(':');
if (pos != -1) {
CStringW wolestr(_T("{"));
wolestr.Append(input.Mid(pos + 1));
wolestr.Append(_T("}"));
if (SUCCEEDED(CLSIDFromString(wolestr.GetString(), &ret)))
return ret;
}
return CLSID_NULL;
}
void
CAxHost::setWindow(HWND win)
{
if (win != Window) {
if (win) {
// subclass window so we can intercept window messages and
// do our drawing to it
OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc);
// associate window with our CAxHost object so we can access
// it in the window procedure
::SetWindowLong(win, GWL_USERDATA, (LONG)this);
}
else {
if (OldProc)
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
Window = win;
}
}
void CAxHost::ResetWindow() {
UpdateRect(lastRect);
}
HWND
CAxHost::getWinfow()
{
return Window;
}
void
CAxHost::UpdateRect(RECT rcPos)
{
HRESULT hr = -1;
lastRect = rcPos;
if (Site && Window && !noWindow) {
if (Site->GetParentWindow() == NULL) {
hr = Site->Attach(Window, rcPos, NULL);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.UpdateRect: failed to attach control");
SIZEL zero = {0, 0};
SetRectSize(&zero);
}
}
if (Site->CheckAndResetNeedUpdateContainerSize()) {
UpdateRectSize(&rcPos);
} else {
Site->SetPosition(rcPos);
}
// Ensure clipping on parent to keep child controls happy
::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN);
}
}
void CAxHost::setNoWindow(bool noWindow) {
this->noWindow = noWindow;
}
void CAxHost::UpdateRectSize(LPRECT origRect) {
if (noWindow) {
return;
}
SIZEL szControl;
if (!Site->IsVisibleAtRuntime()) {
szControl.cx = 0;
szControl.cy = 0;
} else {
if (FAILED(Site->GetControlSize(&szControl))) {
return;
}
}
SIZEL szIn;
szIn.cx = origRect->right - origRect->left;
szIn.cy = origRect->bottom - origRect->top;
if (szControl.cx != szIn.cx || szControl.cy != szIn.cy) {
SetRectSize(&szControl);
}
}
void CAxHost::SetRectSize(LPSIZEL size) {
np_log(instance, 1, "Set object size: x = %d, y = %d", size->cx, size->cy);
NPObjectProxy object;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &object);
static NPIdentifier style = NPNFuncs.getstringidentifier("style");
static NPIdentifier height = NPNFuncs.getstringidentifier("height");
static NPIdentifier width = NPNFuncs.getstringidentifier("width");
NPVariant sHeight, sWidth;
CStringA strHeight, strWidth;
strHeight.Format("%dpx", size->cy);
strWidth.Format("%dpx", size->cx);
STRINGZ_TO_NPVARIANT(strHeight, sHeight);
STRINGZ_TO_NPVARIANT(strWidth, sWidth);
NPVariantProxy styleValue;
NPNFuncs.getproperty(instance, object, style, &styleValue);
NPObject *styleObject = NPVARIANT_TO_OBJECT(styleValue);
NPNFuncs.setproperty(instance, styleObject, height, &sHeight);
NPNFuncs.setproperty(instance, styleObject, width, &sWidth);
}
void CAxHost::SetNPWindow(NPWindow *window) {
RECT rcPos;
setWindow((HWND)window->window);
rcPos.left = 0;
rcPos.top = 0;
rcPos.right = window->width;
rcPos.bottom = window->height;
UpdateRect(rcPos);
}
bool
CAxHost::verifyClsID(LPOLESTR oleClsID)
{
CRegKey keyExplorer;
if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"),
KEY_READ)) {
CRegKey keyCLSID;
if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) {
DWORD dwType = REG_DWORD;
DWORD dwFlags = 0;
DWORD dwBufSize = sizeof(dwFlags);
if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID,
_T("Compatibility Flags"),
NULL,
&dwType,
(LPBYTE)
&dwFlags,
&dwBufSize)) {
// Flags for this reg key
const DWORD kKillBit = 0x00000400;
if (dwFlags & kKillBit) {
np_log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits");
return false;
}
}
}
}
return true;
}
bool
CAxHost::setClsID(const char *clsid)
{
HRESULT hr = -1;
USES_CONVERSION;
LPOLESTR oleClsID = A2OLE(clsid);
if (isWellKnownClsId(clsid)) {
isKnown = true;
}
else if (AcceptOnlyWellKnown) {
np_log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list");
return false;
}
// Check the Internet Explorer list of vulnerable controls
if (oleClsID && verifyClsID(oleClsID)) {
CLSID vclsid;
hr = CLSIDFromString(oleClsID, &vclsid);
if (SUCCEEDED(hr)) {
return setClsID(vclsid);
}
}
np_log(instance, 0, "AxHost.setClsID: failed to set the requested clsid");
return false;
}
bool CAxHost::setClsID(const CLSID& clsid) {
if (clsid != CLSID_NULL) {
this->ClsID = clsid;
isValidClsID = true;
//np_log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid);
return true;
}
return false;
}
void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl)
{
CodeBaseUrl = codeBaseUrl;
}
bool
CAxHost::setClsIDFromProgID(const char *progid)
{
HRESULT hr = -1;
CLSID clsid = CLSID_NULL;
USES_CONVERSION;
LPOLESTR oleClsID = NULL;
LPOLESTR oleProgID = A2OLE(progid);
if (AcceptOnlyWellKnown) {
if (isWellKnownProgId(progid)) {
isKnown = true;
}
else {
np_log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list");
return false;
}
}
hr = CLSIDFromProgID(oleProgID, &clsid);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID");
return false;
}
hr = StringFromCLSID(clsid, &oleClsID);
// Check the Internet Explorer list of vulnerable controls
if ( SUCCEEDED(hr)
&& oleClsID
&& verifyClsID(oleClsID)) {
ClsID = clsid;
if (!::IsEqualCLSID(ClsID, CLSID_NULL)) {
isValidClsID = true;
np_log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid);
return true;
}
}
np_log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID");
return false;
}
bool
CAxHost::hasValidClsID()
{
return isValidClsID;
}
static void HTMLContainerDeleter(IUnknown *unk) {
CComAggObject<HTMLDocumentContainer>* val = (CComAggObject<HTMLDocumentContainer>*)(unk);
val->InternalRelease();
}
bool
CAxHost::CreateControl(bool subscribeToEvents)
{
if (!isValidClsID) {
np_log(instance, 0, "AxHost.CreateControl: current location is not trusted");
return false;
}
// Create the control site
CComObject<CControlSite>::CreateInstance(&Site);
if (Site == NULL) {
np_log(instance, 0, "AxHost.CreateControl: CreateInstance failed");
return false;
}
Site->AddRef();
Site->m_bSupportWindowlessActivation = false;
if (TrustWellKnown && isKnown) {
Site->SetSecurityPolicy(NULL);
Site->m_bSafeForScriptingObjectsOnly = false;
}
else {
Site->m_bSafeForScriptingObjectsOnly = true;
}
CComAggObject<HTMLDocumentContainer> *document;
CComAggObject<HTMLDocumentContainer>::CreateInstance(Site->GetUnknown(), &document);
document->m_contained.Init(instance, pHtmlLib);
Site->SetInnerWindow(document, HTMLContainerDeleter);
// Create the object
HRESULT hr;
hr = Site->Create(ClsID, *Props(), CodeBaseUrl);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.CreateControl: failed to create site for 0x%08x", hr);
return false;
}
#if 0
IUnknown *control = NULL;
Site->GetControlUnknown(&control);
if (!control) {
np_log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)");
return false;
}
// Create the event sink
CComObject<CControlEventSink>::CreateInstance(&Sink);
Sink->AddRef();
Sink->instance = instance;
hr = Sink->SubscribeToEvents(control);
control->Release();
if (FAILED(hr) && subscribeToEvents) {
np_log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed");
// return false;
// It doesn't matter.
}
#endif
np_log(instance, 1, "AxHost.CreateControl: control created successfully");
return true;
}
bool
CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler)
{
HRESULT hr;
DISPID id = 0;
USES_CONVERSION;
LPOLESTR oleName = name;
if (!Sink) {
np_log(instance, 0, "AxHost.AddEventHandler: no valid sink");
return false;
}
hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name");
return false;
}
Sink->events[id] = handler;
np_log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name);
return true;
}
int16
CAxHost::HandleEvent(void *event)
{
NPEvent *npEvent = (NPEvent *)event;
LRESULT result = 0;
if (!npEvent) {
return 0;
}
// forward all events to the hosted control
return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result);
}
ScriptBase *
CAxHost::CreateScriptableObject()
{
Scriptable *obj = Scriptable::FromAxHost(instance, this);
if (Site == NULL) {
return obj;
}
static int markedSafe = 0;
if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe == 0)
{
if (MessageBox(NULL, _T("Some objects are not script-safe, would you continue?"), _T("Warining"), MB_YESNO | MB_ICONINFORMATION | MB_ICONASTERISK) == IDYES)
markedSafe = 1;
else
markedSafe = 2;
}
if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe != 1)
{
// Disable scripting.
obj->Invalidate();
}
return obj;
}
HRESULT CAxHost::GetControlUnknown(IUnknown **pObj) {
if (Site == NULL) {
return E_FAIL;
}
return Site->GetControlUnknown(pObj);
}
NPP CAxHost::ResetNPP(NPP npp) {
NPP ret = CHost::ResetNPP(npp);
setWindow(NULL);
Site->Detach();
if (Sink)
Sink->instance = npp;
return ret;
} | zzhongster-npactivex | ffactivex/axhost.cpp | C++ | mpl11 | 15,006 |
// (c) Code By Extreme
// Description:Inline Hook Engine
// Last update:2010-6-26
#include <Windows.h>
#include <stdio.h>
#include "Hook.h"
#define JMPSIZE 5
#define NOP 0x90
extern DWORD ade_getlength(LPVOID Start, DWORD WantLength);
static VOID BuildJmp(PBYTE Buffer,DWORD JmpFrom, DWORD JmpTo)
{
DWORD JmpAddr;
JmpAddr = JmpFrom - JmpTo - JMPSIZE;
Buffer[0] = 0xE9;
Buffer[1] = (BYTE)(JmpAddr & 0xFF);
Buffer[2] = (BYTE)((JmpAddr >> 8) & 0xFF);
Buffer[3] = (BYTE)((JmpAddr >> 16) & 0xFF);
Buffer[4] = (BYTE)((JmpAddr >> 24) & 0xFF);
}
VOID HEInitHook(PHOOKINFO HookInfo, LPVOID FuncAddr, LPVOID FakeAddr)
{
HookInfo->FakeAddr = FakeAddr;
HookInfo->FuncAddr = FuncAddr;
return;
}
BOOL HEStartHook(PHOOKINFO HookInfo)
{
BOOL CallRet;
BOOL FuncRet = 0;
PVOID BufAddr;
DWORD dwTmp;
DWORD OldProtect;
LPVOID FuncAddr;
DWORD CodeLength;
// Init the basic value
FuncAddr = HookInfo->FuncAddr;
CodeLength = ade_getlength(FuncAddr, JMPSIZE);
HookInfo->CodeLength = CodeLength;
if (HookInfo->FakeAddr == NULL
|| FuncAddr == NULL
|| CodeLength == NULL)
{
FuncRet = 1;
goto Exit1;
}
// Alloc buffer to store the code then write them to the head of the function
BufAddr = malloc(CodeLength);
if (BufAddr == NULL)
{
FuncRet = 2;
goto Exit1;
}
// Alloc buffer to store original code
HookInfo->Stub = (PBYTE)malloc(CodeLength + JMPSIZE);
if (HookInfo->Stub == NULL)
{
FuncRet = 3;
goto Exit2;
}
// Fill buffer to nop. This could make hook stable
FillMemory(BufAddr, CodeLength, NOP);
// Build buffers
BuildJmp((PBYTE)BufAddr, (DWORD)HookInfo->FakeAddr, (DWORD)FuncAddr);
BuildJmp(&(HookInfo->Stub[CodeLength]), (DWORD)((PBYTE)FuncAddr + CodeLength), (DWORD)((PBYTE)HookInfo->Stub + CodeLength));
// [V1.1] Bug fixed: VirtualProtect Stub
CallRet = VirtualProtect(HookInfo->Stub, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect);
if (!CallRet)
{
FuncRet = 4;
goto Exit3;
}
// Set the block of memory could be read and write
CallRet = VirtualProtect(FuncAddr, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect);
if (!CallRet)
{
FuncRet = 4;
goto Exit3;
}
// Copy the head of function to stub
CallRet = ReadProcessMemory(GetCurrentProcess(), FuncAddr, HookInfo->Stub, CodeLength, &dwTmp);
if (!CallRet || dwTmp != CodeLength)
{
FuncRet = 5;
goto Exit3;
}
// Write hook code back to the head of the function
CallRet = WriteProcessMemory(GetCurrentProcess(), FuncAddr, BufAddr, CodeLength, &dwTmp);
if (!CallRet || dwTmp != CodeLength)
{
FuncRet = 6;
goto Exit3;
}
// Make hook stable
FlushInstructionCache(GetCurrentProcess(), FuncAddr, CodeLength);
VirtualProtect(FuncAddr, CodeLength, OldProtect, &dwTmp);
// All done
goto Exit2;
// Error handle
Exit3:
free(HookInfo->Stub);
Exit2:
free (BufAddr);
Exit1:
return FuncRet;
}
BOOL HEStopHook(PHOOKINFO HookInfo)
{
BOOL CallRet;
DWORD dwTmp;
DWORD OldProtect;
LPVOID FuncAddr = HookInfo->FuncAddr;
DWORD CodeLength = HookInfo->CodeLength;
CallRet = VirtualProtect(FuncAddr, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect);
if (!CallRet)
{
return 1;
}
CallRet = WriteProcessMemory(GetCurrentProcess(), FuncAddr, HookInfo->Stub, CodeLength, &dwTmp);
if (!CallRet || dwTmp != CodeLength)
{
return 2;
}
FlushInstructionCache(GetCurrentProcess(), FuncAddr, CodeLength);
VirtualProtect(FuncAddr, CodeLength, OldProtect, &dwTmp);
free(HookInfo->Stub);
return 0;
} | zzhongster-npactivex | ffactivex/ApiHook/Hook.cpp | C++ | mpl11 | 3,588 |
#ifndef _HOOK_H_
#define _HOOK_H_
typedef struct _HOOKINFO_
{
PBYTE Stub;
DWORD CodeLength;
LPVOID FuncAddr;
LPVOID FakeAddr;
}HOOKINFO, *PHOOKINFO;
VOID HEInitHook(PHOOKINFO HookInfo, LPVOID FuncAddr, LPVOID FakeAddr);
BOOL HEStartHook(PHOOKINFO HookInfo);
BOOL HEStopHook(PHOOKINFO HookInfo);
#endif | zzhongster-npactivex | ffactivex/ApiHook/Hook.h | C | mpl11 | 323 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "atlthunk.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdio.h>
#include "ApiHook\Hook.h"
typedef struct tagEXCEPTION_REGISTER
{
tagEXCEPTION_REGISTER *prev;
_except_handler_type handler;
}EXCEPTION_REGISTER, *LPEXCEPTION_REGISTER;
/* Supported patterns:
C7 44 24 04 XX XX XX XX mov [esp+4], imm32
E9 YY YY YY YY jmp imm32
B9 XX XX XX XX mov ecx, imm32
E9 YY YY YY YY jmp imm32
BA XX XX XX XX mov edx, imm32
B9 YY YY YY YY mov ecx, imm32
FF E1 jmp ecx
B9 XX XX XX XX mov ecx, imm32
B8 YY YY YY YY mov eax, imm32
FF E0 jmp eax
59 pop ecx
58 pop eax
51 push ecx
FF 60 04 jmp [eax+4]
*/
/* Pattern 1:
C7 44 24 04 XX XX XX XX mov [esp+4], imm32
E9 YY YY YY YY jmp imm32
*/
BYTE pattern1[] = {0xC7, 0x44, 0x24, 0x04, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0};
void _process_pattern1(struct _CONTEXT *ContextRecord) {
LPDWORD esp = (LPDWORD)(ContextRecord->Esp);
DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 4);
DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 9);
esp[1] = imm1;
ContextRecord->Eip += imm2 + 13;
}
/* Pattern 2:
B9 XX XX XX XX mov ecx, imm32
E9 YY YY YY YY jmp imm32
*/
BYTE pattern2[] = {0xB9, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0};
void _process_pattern2(struct _CONTEXT *ContextRecord) {
DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1);
DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6);
ContextRecord->Ecx = imm1;
ContextRecord->Eip += imm2 + 10;
}
/* Pattern 3:
BA XX XX XX XX mov edx, imm32
B9 YY YY YY YY mov ecx, imm32
FF E1 jmp ecx
*/
BYTE pattern3[] = {0xBA, 0, 0, 0, 0, 0xB9, 0, 0, 0, 0, 0xFF, 0xE1};
void _process_pattern3(struct _CONTEXT *ContextRecord) {
DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1);
DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6);
ContextRecord->Edx = imm1;
ContextRecord->Ecx = imm2;
ContextRecord->Eip += imm2;
}
/*
B9 XX XX XX XX mov ecx, imm32
B8 YY YY YY YY mov eax, imm32
FF E0 jmp eax
*/
BYTE pattern4[] = {0xB9, 0, 0, 0, 0, 0xB8, 0, 0, 0, 0, 0xFF, 0xE0};
void _process_pattern4(struct _CONTEXT *ContextRecord) {
DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1);
DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6);
ContextRecord->Ecx = imm1;
ContextRecord->Eax = imm2;
ContextRecord->Eip += imm2;
}
/*
59 pop ecx
58 pop eax
51 push ecx
FF 60 04 jmp [eax+4]
*/
BYTE pattern5[] = {0x59, 0x58, 0x51, 0xFF, 0x60, 0x04};
void _process_pattern5(struct _CONTEXT *ContextRecord) {
LPDWORD stack = (LPDWORD)(ContextRecord->Esp);
ContextRecord->Ecx = stack[0];
ContextRecord->Eax = stack[1];
stack[1] = stack[0];
ContextRecord->Esp += 4;
ContextRecord->Eip = *(LPDWORD)(ContextRecord->Eax + 4);
}
ATL_THUNK_PATTERN patterns[] = {
{pattern1, sizeof(pattern1), _process_pattern1},
{pattern2, sizeof(pattern2), _process_pattern2},
{pattern3, sizeof(pattern3), _process_pattern3},
{pattern4, sizeof(pattern4), _process_pattern4},
{pattern5, sizeof(pattern5), _process_pattern5} };
ATL_THUNK_PATTERN *match_patterns(LPVOID eip)
{
LPBYTE codes = (LPBYTE)eip;
for (int i = 0; i < sizeof(patterns) / sizeof(patterns[0]); ++i) {
BOOL match = TRUE;
for (int j = 0; j < patterns[i].pattern_size && match; ++j) {
if (patterns[i].pattern[j] != 0 && patterns[i].pattern[j] != codes[j])
match = FALSE;
}
if (match) {
return &patterns[i];
}
}
return NULL;
}
EXCEPTION_DISPOSITION
__cdecl
_except_handler_atl_thunk(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext )
{
if ((ExceptionRecord->ExceptionFlags)
|| ExceptionRecord->ExceptionCode != STATUS_ACCESS_VIOLATION
|| ExceptionRecord->ExceptionAddress != (LPVOID)ContextRecord->Eip) {
// Not expected Access violation exception
return ExceptionContinueSearch;
}
// Try to match patterns
ATL_THUNK_PATTERN *pattern = match_patterns((LPVOID)ContextRecord->Eip);
if (pattern) {
//DWORD old;
// We can't always protect the ATL by except_handler, so we mark it executable.
//BOOL ret = VirtualProtect((LPVOID)ContextRecord->Eip, pattern->pattern_size, PAGE_EXECUTE_READWRITE, &old);
pattern->enumerator(ContextRecord);
return ExceptionContinueExecution;
}
else {
return ExceptionContinueSearch;
}
}
#ifndef ATL_THUNK_APIHOOK
_except_handler_type original_handler4;
#else
HOOKINFO hook_handler;
#endif
#if 0
EXCEPTION_DISPOSITION
__cdecl
my_except_handler4(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext )
{
//assert(original_handler);
EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord,
EstablisherFrame,
ContextRecord,
DispatcherContext);
if (step1 == ExceptionContinueExecution)
return step1;
#ifndef ATL_THUNK_APIHOOK
_except_handler_type original_handler = original_handler4;
#else
_except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub;
#endif
return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext);
}
EXCEPTION_DISPOSITION
__cdecl
my_except_handler3(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext )
{
//assert(original_handler);
EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord,
EstablisherFrame,
ContextRecord,
DispatcherContext);
if (step1 == ExceptionContinueExecution)
return step1;
#ifndef ATL_THUNK_APIHOOK
// We won't wrap handler3, this shouldn't be used..
_except_handler_type original_handler = original_handler3;
#else
_except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub;
#endif
return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext);
}
#endif
BOOL CheckDEPEnabled()
{
// In case of running in a XP SP2.
HMODULE hInst = LoadLibrary(TEXT("Kernel32.dll"));
typedef BOOL (WINAPI *SetProcessDEPPolicyType)(
__in DWORD dwFlags
);
typedef BOOL (WINAPI *GetProcessDEPPolicyType)(
__in HANDLE hProcess,
__out LPDWORD lpFlags,
__out PBOOL lpPermanent
);
SetProcessDEPPolicyType setProc = (SetProcessDEPPolicyType)GetProcAddress(hInst, "SetProcessDEPPolicy");
GetProcessDEPPolicyType getProc = (GetProcessDEPPolicyType)GetProcAddress(hInst, "GetProcessDEPPolicy");
if (setProc) {
// This is likely to fail, but we set it first.
setProc(PROCESS_DEP_ENABLE);
}
BOOL enabled = FALSE;
DWORD lpFlags;
BOOL lpPermanent;
if (getProc && getProc(GetCurrentProcess(), &lpFlags, &lpPermanent))
{
enabled = (lpFlags == (PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION | PROCESS_DEP_ENABLE));
}
return enabled;
}
extern "C" void _KiUserExceptionDispatcher_hook();
extern "C" DWORD _KiUserExceptionDispatcher_origin;
extern "C" DWORD _KiUserExceptionDispatcher_ATL_p;
typedef void (__stdcall *ZwContinueType)(struct _CONTEXT *, int);
ZwContinueType ZwContinue;
int __cdecl
_KiUserExceptionDispatcher_ATL(
struct _EXCEPTION_RECORD *ExceptionRecord,
struct _CONTEXT *ContextRecord) {
if (_except_handler_atl_thunk(ExceptionRecord, NULL, ContextRecord, NULL) == ExceptionContinueExecution) {
ZwContinue(ContextRecord, 0);
}
return 0;
}
bool atlThunkInstalled = false;
void InstallAtlThunkEnumeration() {
if (atlThunkInstalled)
return;
if (CheckDEPEnabled()) {
#ifndef ATL_THUNK_APIHOOK
// Chrome is protected by DEP.
EXCEPTION_REGISTER *reg;
__asm {
mov eax, fs:[0]
mov reg, eax
}
while ((DWORD)reg->prev != 0xFFFFFFFF)
reg = reg->prev;
// replace the old handler
original_handler = reg->handler;
reg->handler = _except_handler;
#else
_KiUserExceptionDispatcher_ATL_p = (DWORD)_KiUserExceptionDispatcher_ATL;
ZwContinue = (ZwContinueType) GetProcAddress(GetModuleHandle(TEXT("ntdll")), "ZwContinue");
HEInitHook(&hook_handler, GetProcAddress(GetModuleHandle(TEXT("ntdll")), "KiUserExceptionDispatcher") , _KiUserExceptionDispatcher_hook);
HEStartHook(&hook_handler);
_KiUserExceptionDispatcher_origin = (DWORD)hook_handler.Stub;
atlThunkInstalled = true;
#endif
}
}
void UninstallAtlThunkEnumeration() {
#ifdef ATL_THUNK_APIHOOK
if (!atlThunkInstalled)
return;
HEStopHook(&hook_handler);
atlThunkInstalled = false;
#endif
} | zzhongster-npactivex | ffactivex/AtlThunk.cpp | C++ | mpl11 | 10,401 |
; Copyright qiuc12@gmail.com
; This file is generated automatically by python. DON'T MODIFY IT!
.386
.model flat
_DualProcessCommandWrap proto
PUBLIC ?fv0@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv1@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv2@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv3@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv4@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv5@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv6@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv7@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv8@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv9@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv10@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv11@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv12@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv13@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv14@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv15@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv16@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv17@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv18@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv19@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv20@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv21@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv22@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv23@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv24@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv25@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv26@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv27@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv28@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv29@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv30@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv31@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv32@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv33@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv34@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv35@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv36@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv37@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv38@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv39@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv40@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv41@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv42@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv43@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv44@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv45@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv46@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv47@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv48@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv49@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv50@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv51@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv52@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv53@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv54@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv55@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv56@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv57@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv58@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv59@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv60@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv61@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv62@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv63@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv64@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv65@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv66@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv67@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv68@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv69@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv70@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv71@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv72@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv73@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv74@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv75@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv76@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv77@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv78@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv79@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv80@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv81@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv82@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv83@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv84@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv85@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv86@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv87@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv88@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv89@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv90@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv91@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv92@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv93@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv94@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv95@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv96@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv97@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv98@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv99@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv100@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv101@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv102@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv103@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv104@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv105@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv106@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv107@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv108@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv109@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv110@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv111@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv112@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv113@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv114@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv115@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv116@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv117@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv118@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv119@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv120@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv121@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv122@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv123@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv124@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv125@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv126@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv127@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv128@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv129@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv130@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv131@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv132@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv133@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv134@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv135@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv136@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv137@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv138@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv139@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv140@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv141@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv142@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv143@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv144@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv145@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv146@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv147@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv148@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv149@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv150@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv151@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv152@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv153@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv154@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv155@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv156@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv157@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv158@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv159@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv160@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv161@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv162@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv163@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv164@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv165@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv166@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv167@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv168@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv169@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv170@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv171@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv172@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv173@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv174@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv175@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv176@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv177@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv178@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv179@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv180@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv181@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv182@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv183@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv184@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv185@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv186@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv187@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv188@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv189@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv190@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv191@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv192@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv193@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv194@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv195@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv196@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv197@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv198@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv199@FakeDispatcherBase@@EAGJXZ
.code
?fv0@FakeDispatcherBase@@EAGJXZ proc
push 0
jmp _DualProcessCommandWrap
?fv0@FakeDispatcherBase@@EAGJXZ endp
?fv1@FakeDispatcherBase@@EAGJXZ proc
push 1
jmp _DualProcessCommandWrap
?fv1@FakeDispatcherBase@@EAGJXZ endp
?fv2@FakeDispatcherBase@@EAGJXZ proc
push 2
jmp _DualProcessCommandWrap
?fv2@FakeDispatcherBase@@EAGJXZ endp
?fv3@FakeDispatcherBase@@EAGJXZ proc
push 3
jmp _DualProcessCommandWrap
?fv3@FakeDispatcherBase@@EAGJXZ endp
?fv4@FakeDispatcherBase@@EAGJXZ proc
push 4
jmp _DualProcessCommandWrap
?fv4@FakeDispatcherBase@@EAGJXZ endp
?fv5@FakeDispatcherBase@@EAGJXZ proc
push 5
jmp _DualProcessCommandWrap
?fv5@FakeDispatcherBase@@EAGJXZ endp
?fv6@FakeDispatcherBase@@EAGJXZ proc
push 6
jmp _DualProcessCommandWrap
?fv6@FakeDispatcherBase@@EAGJXZ endp
?fv7@FakeDispatcherBase@@EAGJXZ proc
push 7
jmp _DualProcessCommandWrap
?fv7@FakeDispatcherBase@@EAGJXZ endp
?fv8@FakeDispatcherBase@@EAGJXZ proc
push 8
jmp _DualProcessCommandWrap
?fv8@FakeDispatcherBase@@EAGJXZ endp
?fv9@FakeDispatcherBase@@EAGJXZ proc
push 9
jmp _DualProcessCommandWrap
?fv9@FakeDispatcherBase@@EAGJXZ endp
?fv10@FakeDispatcherBase@@EAGJXZ proc
push 10
jmp _DualProcessCommandWrap
?fv10@FakeDispatcherBase@@EAGJXZ endp
?fv11@FakeDispatcherBase@@EAGJXZ proc
push 11
jmp _DualProcessCommandWrap
?fv11@FakeDispatcherBase@@EAGJXZ endp
?fv12@FakeDispatcherBase@@EAGJXZ proc
push 12
jmp _DualProcessCommandWrap
?fv12@FakeDispatcherBase@@EAGJXZ endp
?fv13@FakeDispatcherBase@@EAGJXZ proc
push 13
jmp _DualProcessCommandWrap
?fv13@FakeDispatcherBase@@EAGJXZ endp
?fv14@FakeDispatcherBase@@EAGJXZ proc
push 14
jmp _DualProcessCommandWrap
?fv14@FakeDispatcherBase@@EAGJXZ endp
?fv15@FakeDispatcherBase@@EAGJXZ proc
push 15
jmp _DualProcessCommandWrap
?fv15@FakeDispatcherBase@@EAGJXZ endp
?fv16@FakeDispatcherBase@@EAGJXZ proc
push 16
jmp _DualProcessCommandWrap
?fv16@FakeDispatcherBase@@EAGJXZ endp
?fv17@FakeDispatcherBase@@EAGJXZ proc
push 17
jmp _DualProcessCommandWrap
?fv17@FakeDispatcherBase@@EAGJXZ endp
?fv18@FakeDispatcherBase@@EAGJXZ proc
push 18
jmp _DualProcessCommandWrap
?fv18@FakeDispatcherBase@@EAGJXZ endp
?fv19@FakeDispatcherBase@@EAGJXZ proc
push 19
jmp _DualProcessCommandWrap
?fv19@FakeDispatcherBase@@EAGJXZ endp
?fv20@FakeDispatcherBase@@EAGJXZ proc
push 20
jmp _DualProcessCommandWrap
?fv20@FakeDispatcherBase@@EAGJXZ endp
?fv21@FakeDispatcherBase@@EAGJXZ proc
push 21
jmp _DualProcessCommandWrap
?fv21@FakeDispatcherBase@@EAGJXZ endp
?fv22@FakeDispatcherBase@@EAGJXZ proc
push 22
jmp _DualProcessCommandWrap
?fv22@FakeDispatcherBase@@EAGJXZ endp
?fv23@FakeDispatcherBase@@EAGJXZ proc
push 23
jmp _DualProcessCommandWrap
?fv23@FakeDispatcherBase@@EAGJXZ endp
?fv24@FakeDispatcherBase@@EAGJXZ proc
push 24
jmp _DualProcessCommandWrap
?fv24@FakeDispatcherBase@@EAGJXZ endp
?fv25@FakeDispatcherBase@@EAGJXZ proc
push 25
jmp _DualProcessCommandWrap
?fv25@FakeDispatcherBase@@EAGJXZ endp
?fv26@FakeDispatcherBase@@EAGJXZ proc
push 26
jmp _DualProcessCommandWrap
?fv26@FakeDispatcherBase@@EAGJXZ endp
?fv27@FakeDispatcherBase@@EAGJXZ proc
push 27
jmp _DualProcessCommandWrap
?fv27@FakeDispatcherBase@@EAGJXZ endp
?fv28@FakeDispatcherBase@@EAGJXZ proc
push 28
jmp _DualProcessCommandWrap
?fv28@FakeDispatcherBase@@EAGJXZ endp
?fv29@FakeDispatcherBase@@EAGJXZ proc
push 29
jmp _DualProcessCommandWrap
?fv29@FakeDispatcherBase@@EAGJXZ endp
?fv30@FakeDispatcherBase@@EAGJXZ proc
push 30
jmp _DualProcessCommandWrap
?fv30@FakeDispatcherBase@@EAGJXZ endp
?fv31@FakeDispatcherBase@@EAGJXZ proc
push 31
jmp _DualProcessCommandWrap
?fv31@FakeDispatcherBase@@EAGJXZ endp
?fv32@FakeDispatcherBase@@EAGJXZ proc
push 32
jmp _DualProcessCommandWrap
?fv32@FakeDispatcherBase@@EAGJXZ endp
?fv33@FakeDispatcherBase@@EAGJXZ proc
push 33
jmp _DualProcessCommandWrap
?fv33@FakeDispatcherBase@@EAGJXZ endp
?fv34@FakeDispatcherBase@@EAGJXZ proc
push 34
jmp _DualProcessCommandWrap
?fv34@FakeDispatcherBase@@EAGJXZ endp
?fv35@FakeDispatcherBase@@EAGJXZ proc
push 35
jmp _DualProcessCommandWrap
?fv35@FakeDispatcherBase@@EAGJXZ endp
?fv36@FakeDispatcherBase@@EAGJXZ proc
push 36
jmp _DualProcessCommandWrap
?fv36@FakeDispatcherBase@@EAGJXZ endp
?fv37@FakeDispatcherBase@@EAGJXZ proc
push 37
jmp _DualProcessCommandWrap
?fv37@FakeDispatcherBase@@EAGJXZ endp
?fv38@FakeDispatcherBase@@EAGJXZ proc
push 38
jmp _DualProcessCommandWrap
?fv38@FakeDispatcherBase@@EAGJXZ endp
?fv39@FakeDispatcherBase@@EAGJXZ proc
push 39
jmp _DualProcessCommandWrap
?fv39@FakeDispatcherBase@@EAGJXZ endp
?fv40@FakeDispatcherBase@@EAGJXZ proc
push 40
jmp _DualProcessCommandWrap
?fv40@FakeDispatcherBase@@EAGJXZ endp
?fv41@FakeDispatcherBase@@EAGJXZ proc
push 41
jmp _DualProcessCommandWrap
?fv41@FakeDispatcherBase@@EAGJXZ endp
?fv42@FakeDispatcherBase@@EAGJXZ proc
push 42
jmp _DualProcessCommandWrap
?fv42@FakeDispatcherBase@@EAGJXZ endp
?fv43@FakeDispatcherBase@@EAGJXZ proc
push 43
jmp _DualProcessCommandWrap
?fv43@FakeDispatcherBase@@EAGJXZ endp
?fv44@FakeDispatcherBase@@EAGJXZ proc
push 44
jmp _DualProcessCommandWrap
?fv44@FakeDispatcherBase@@EAGJXZ endp
?fv45@FakeDispatcherBase@@EAGJXZ proc
push 45
jmp _DualProcessCommandWrap
?fv45@FakeDispatcherBase@@EAGJXZ endp
?fv46@FakeDispatcherBase@@EAGJXZ proc
push 46
jmp _DualProcessCommandWrap
?fv46@FakeDispatcherBase@@EAGJXZ endp
?fv47@FakeDispatcherBase@@EAGJXZ proc
push 47
jmp _DualProcessCommandWrap
?fv47@FakeDispatcherBase@@EAGJXZ endp
?fv48@FakeDispatcherBase@@EAGJXZ proc
push 48
jmp _DualProcessCommandWrap
?fv48@FakeDispatcherBase@@EAGJXZ endp
?fv49@FakeDispatcherBase@@EAGJXZ proc
push 49
jmp _DualProcessCommandWrap
?fv49@FakeDispatcherBase@@EAGJXZ endp
?fv50@FakeDispatcherBase@@EAGJXZ proc
push 50
jmp _DualProcessCommandWrap
?fv50@FakeDispatcherBase@@EAGJXZ endp
?fv51@FakeDispatcherBase@@EAGJXZ proc
push 51
jmp _DualProcessCommandWrap
?fv51@FakeDispatcherBase@@EAGJXZ endp
?fv52@FakeDispatcherBase@@EAGJXZ proc
push 52
jmp _DualProcessCommandWrap
?fv52@FakeDispatcherBase@@EAGJXZ endp
?fv53@FakeDispatcherBase@@EAGJXZ proc
push 53
jmp _DualProcessCommandWrap
?fv53@FakeDispatcherBase@@EAGJXZ endp
?fv54@FakeDispatcherBase@@EAGJXZ proc
push 54
jmp _DualProcessCommandWrap
?fv54@FakeDispatcherBase@@EAGJXZ endp
?fv55@FakeDispatcherBase@@EAGJXZ proc
push 55
jmp _DualProcessCommandWrap
?fv55@FakeDispatcherBase@@EAGJXZ endp
?fv56@FakeDispatcherBase@@EAGJXZ proc
push 56
jmp _DualProcessCommandWrap
?fv56@FakeDispatcherBase@@EAGJXZ endp
?fv57@FakeDispatcherBase@@EAGJXZ proc
push 57
jmp _DualProcessCommandWrap
?fv57@FakeDispatcherBase@@EAGJXZ endp
?fv58@FakeDispatcherBase@@EAGJXZ proc
push 58
jmp _DualProcessCommandWrap
?fv58@FakeDispatcherBase@@EAGJXZ endp
?fv59@FakeDispatcherBase@@EAGJXZ proc
push 59
jmp _DualProcessCommandWrap
?fv59@FakeDispatcherBase@@EAGJXZ endp
?fv60@FakeDispatcherBase@@EAGJXZ proc
push 60
jmp _DualProcessCommandWrap
?fv60@FakeDispatcherBase@@EAGJXZ endp
?fv61@FakeDispatcherBase@@EAGJXZ proc
push 61
jmp _DualProcessCommandWrap
?fv61@FakeDispatcherBase@@EAGJXZ endp
?fv62@FakeDispatcherBase@@EAGJXZ proc
push 62
jmp _DualProcessCommandWrap
?fv62@FakeDispatcherBase@@EAGJXZ endp
?fv63@FakeDispatcherBase@@EAGJXZ proc
push 63
jmp _DualProcessCommandWrap
?fv63@FakeDispatcherBase@@EAGJXZ endp
?fv64@FakeDispatcherBase@@EAGJXZ proc
push 64
jmp _DualProcessCommandWrap
?fv64@FakeDispatcherBase@@EAGJXZ endp
?fv65@FakeDispatcherBase@@EAGJXZ proc
push 65
jmp _DualProcessCommandWrap
?fv65@FakeDispatcherBase@@EAGJXZ endp
?fv66@FakeDispatcherBase@@EAGJXZ proc
push 66
jmp _DualProcessCommandWrap
?fv66@FakeDispatcherBase@@EAGJXZ endp
?fv67@FakeDispatcherBase@@EAGJXZ proc
push 67
jmp _DualProcessCommandWrap
?fv67@FakeDispatcherBase@@EAGJXZ endp
?fv68@FakeDispatcherBase@@EAGJXZ proc
push 68
jmp _DualProcessCommandWrap
?fv68@FakeDispatcherBase@@EAGJXZ endp
?fv69@FakeDispatcherBase@@EAGJXZ proc
push 69
jmp _DualProcessCommandWrap
?fv69@FakeDispatcherBase@@EAGJXZ endp
?fv70@FakeDispatcherBase@@EAGJXZ proc
push 70
jmp _DualProcessCommandWrap
?fv70@FakeDispatcherBase@@EAGJXZ endp
?fv71@FakeDispatcherBase@@EAGJXZ proc
push 71
jmp _DualProcessCommandWrap
?fv71@FakeDispatcherBase@@EAGJXZ endp
?fv72@FakeDispatcherBase@@EAGJXZ proc
push 72
jmp _DualProcessCommandWrap
?fv72@FakeDispatcherBase@@EAGJXZ endp
?fv73@FakeDispatcherBase@@EAGJXZ proc
push 73
jmp _DualProcessCommandWrap
?fv73@FakeDispatcherBase@@EAGJXZ endp
?fv74@FakeDispatcherBase@@EAGJXZ proc
push 74
jmp _DualProcessCommandWrap
?fv74@FakeDispatcherBase@@EAGJXZ endp
?fv75@FakeDispatcherBase@@EAGJXZ proc
push 75
jmp _DualProcessCommandWrap
?fv75@FakeDispatcherBase@@EAGJXZ endp
?fv76@FakeDispatcherBase@@EAGJXZ proc
push 76
jmp _DualProcessCommandWrap
?fv76@FakeDispatcherBase@@EAGJXZ endp
?fv77@FakeDispatcherBase@@EAGJXZ proc
push 77
jmp _DualProcessCommandWrap
?fv77@FakeDispatcherBase@@EAGJXZ endp
?fv78@FakeDispatcherBase@@EAGJXZ proc
push 78
jmp _DualProcessCommandWrap
?fv78@FakeDispatcherBase@@EAGJXZ endp
?fv79@FakeDispatcherBase@@EAGJXZ proc
push 79
jmp _DualProcessCommandWrap
?fv79@FakeDispatcherBase@@EAGJXZ endp
?fv80@FakeDispatcherBase@@EAGJXZ proc
push 80
jmp _DualProcessCommandWrap
?fv80@FakeDispatcherBase@@EAGJXZ endp
?fv81@FakeDispatcherBase@@EAGJXZ proc
push 81
jmp _DualProcessCommandWrap
?fv81@FakeDispatcherBase@@EAGJXZ endp
?fv82@FakeDispatcherBase@@EAGJXZ proc
push 82
jmp _DualProcessCommandWrap
?fv82@FakeDispatcherBase@@EAGJXZ endp
?fv83@FakeDispatcherBase@@EAGJXZ proc
push 83
jmp _DualProcessCommandWrap
?fv83@FakeDispatcherBase@@EAGJXZ endp
?fv84@FakeDispatcherBase@@EAGJXZ proc
push 84
jmp _DualProcessCommandWrap
?fv84@FakeDispatcherBase@@EAGJXZ endp
?fv85@FakeDispatcherBase@@EAGJXZ proc
push 85
jmp _DualProcessCommandWrap
?fv85@FakeDispatcherBase@@EAGJXZ endp
?fv86@FakeDispatcherBase@@EAGJXZ proc
push 86
jmp _DualProcessCommandWrap
?fv86@FakeDispatcherBase@@EAGJXZ endp
?fv87@FakeDispatcherBase@@EAGJXZ proc
push 87
jmp _DualProcessCommandWrap
?fv87@FakeDispatcherBase@@EAGJXZ endp
?fv88@FakeDispatcherBase@@EAGJXZ proc
push 88
jmp _DualProcessCommandWrap
?fv88@FakeDispatcherBase@@EAGJXZ endp
?fv89@FakeDispatcherBase@@EAGJXZ proc
push 89
jmp _DualProcessCommandWrap
?fv89@FakeDispatcherBase@@EAGJXZ endp
?fv90@FakeDispatcherBase@@EAGJXZ proc
push 90
jmp _DualProcessCommandWrap
?fv90@FakeDispatcherBase@@EAGJXZ endp
?fv91@FakeDispatcherBase@@EAGJXZ proc
push 91
jmp _DualProcessCommandWrap
?fv91@FakeDispatcherBase@@EAGJXZ endp
?fv92@FakeDispatcherBase@@EAGJXZ proc
push 92
jmp _DualProcessCommandWrap
?fv92@FakeDispatcherBase@@EAGJXZ endp
?fv93@FakeDispatcherBase@@EAGJXZ proc
push 93
jmp _DualProcessCommandWrap
?fv93@FakeDispatcherBase@@EAGJXZ endp
?fv94@FakeDispatcherBase@@EAGJXZ proc
push 94
jmp _DualProcessCommandWrap
?fv94@FakeDispatcherBase@@EAGJXZ endp
?fv95@FakeDispatcherBase@@EAGJXZ proc
push 95
jmp _DualProcessCommandWrap
?fv95@FakeDispatcherBase@@EAGJXZ endp
?fv96@FakeDispatcherBase@@EAGJXZ proc
push 96
jmp _DualProcessCommandWrap
?fv96@FakeDispatcherBase@@EAGJXZ endp
?fv97@FakeDispatcherBase@@EAGJXZ proc
push 97
jmp _DualProcessCommandWrap
?fv97@FakeDispatcherBase@@EAGJXZ endp
?fv98@FakeDispatcherBase@@EAGJXZ proc
push 98
jmp _DualProcessCommandWrap
?fv98@FakeDispatcherBase@@EAGJXZ endp
?fv99@FakeDispatcherBase@@EAGJXZ proc
push 99
jmp _DualProcessCommandWrap
?fv99@FakeDispatcherBase@@EAGJXZ endp
?fv100@FakeDispatcherBase@@EAGJXZ proc
push 100
jmp _DualProcessCommandWrap
?fv100@FakeDispatcherBase@@EAGJXZ endp
?fv101@FakeDispatcherBase@@EAGJXZ proc
push 101
jmp _DualProcessCommandWrap
?fv101@FakeDispatcherBase@@EAGJXZ endp
?fv102@FakeDispatcherBase@@EAGJXZ proc
push 102
jmp _DualProcessCommandWrap
?fv102@FakeDispatcherBase@@EAGJXZ endp
?fv103@FakeDispatcherBase@@EAGJXZ proc
push 103
jmp _DualProcessCommandWrap
?fv103@FakeDispatcherBase@@EAGJXZ endp
?fv104@FakeDispatcherBase@@EAGJXZ proc
push 104
jmp _DualProcessCommandWrap
?fv104@FakeDispatcherBase@@EAGJXZ endp
?fv105@FakeDispatcherBase@@EAGJXZ proc
push 105
jmp _DualProcessCommandWrap
?fv105@FakeDispatcherBase@@EAGJXZ endp
?fv106@FakeDispatcherBase@@EAGJXZ proc
push 106
jmp _DualProcessCommandWrap
?fv106@FakeDispatcherBase@@EAGJXZ endp
?fv107@FakeDispatcherBase@@EAGJXZ proc
push 107
jmp _DualProcessCommandWrap
?fv107@FakeDispatcherBase@@EAGJXZ endp
?fv108@FakeDispatcherBase@@EAGJXZ proc
push 108
jmp _DualProcessCommandWrap
?fv108@FakeDispatcherBase@@EAGJXZ endp
?fv109@FakeDispatcherBase@@EAGJXZ proc
push 109
jmp _DualProcessCommandWrap
?fv109@FakeDispatcherBase@@EAGJXZ endp
?fv110@FakeDispatcherBase@@EAGJXZ proc
push 110
jmp _DualProcessCommandWrap
?fv110@FakeDispatcherBase@@EAGJXZ endp
?fv111@FakeDispatcherBase@@EAGJXZ proc
push 111
jmp _DualProcessCommandWrap
?fv111@FakeDispatcherBase@@EAGJXZ endp
?fv112@FakeDispatcherBase@@EAGJXZ proc
push 112
jmp _DualProcessCommandWrap
?fv112@FakeDispatcherBase@@EAGJXZ endp
?fv113@FakeDispatcherBase@@EAGJXZ proc
push 113
jmp _DualProcessCommandWrap
?fv113@FakeDispatcherBase@@EAGJXZ endp
?fv114@FakeDispatcherBase@@EAGJXZ proc
push 114
jmp _DualProcessCommandWrap
?fv114@FakeDispatcherBase@@EAGJXZ endp
?fv115@FakeDispatcherBase@@EAGJXZ proc
push 115
jmp _DualProcessCommandWrap
?fv115@FakeDispatcherBase@@EAGJXZ endp
?fv116@FakeDispatcherBase@@EAGJXZ proc
push 116
jmp _DualProcessCommandWrap
?fv116@FakeDispatcherBase@@EAGJXZ endp
?fv117@FakeDispatcherBase@@EAGJXZ proc
push 117
jmp _DualProcessCommandWrap
?fv117@FakeDispatcherBase@@EAGJXZ endp
?fv118@FakeDispatcherBase@@EAGJXZ proc
push 118
jmp _DualProcessCommandWrap
?fv118@FakeDispatcherBase@@EAGJXZ endp
?fv119@FakeDispatcherBase@@EAGJXZ proc
push 119
jmp _DualProcessCommandWrap
?fv119@FakeDispatcherBase@@EAGJXZ endp
?fv120@FakeDispatcherBase@@EAGJXZ proc
push 120
jmp _DualProcessCommandWrap
?fv120@FakeDispatcherBase@@EAGJXZ endp
?fv121@FakeDispatcherBase@@EAGJXZ proc
push 121
jmp _DualProcessCommandWrap
?fv121@FakeDispatcherBase@@EAGJXZ endp
?fv122@FakeDispatcherBase@@EAGJXZ proc
push 122
jmp _DualProcessCommandWrap
?fv122@FakeDispatcherBase@@EAGJXZ endp
?fv123@FakeDispatcherBase@@EAGJXZ proc
push 123
jmp _DualProcessCommandWrap
?fv123@FakeDispatcherBase@@EAGJXZ endp
?fv124@FakeDispatcherBase@@EAGJXZ proc
push 124
jmp _DualProcessCommandWrap
?fv124@FakeDispatcherBase@@EAGJXZ endp
?fv125@FakeDispatcherBase@@EAGJXZ proc
push 125
jmp _DualProcessCommandWrap
?fv125@FakeDispatcherBase@@EAGJXZ endp
?fv126@FakeDispatcherBase@@EAGJXZ proc
push 126
jmp _DualProcessCommandWrap
?fv126@FakeDispatcherBase@@EAGJXZ endp
?fv127@FakeDispatcherBase@@EAGJXZ proc
push 127
jmp _DualProcessCommandWrap
?fv127@FakeDispatcherBase@@EAGJXZ endp
?fv128@FakeDispatcherBase@@EAGJXZ proc
push 128
jmp _DualProcessCommandWrap
?fv128@FakeDispatcherBase@@EAGJXZ endp
?fv129@FakeDispatcherBase@@EAGJXZ proc
push 129
jmp _DualProcessCommandWrap
?fv129@FakeDispatcherBase@@EAGJXZ endp
?fv130@FakeDispatcherBase@@EAGJXZ proc
push 130
jmp _DualProcessCommandWrap
?fv130@FakeDispatcherBase@@EAGJXZ endp
?fv131@FakeDispatcherBase@@EAGJXZ proc
push 131
jmp _DualProcessCommandWrap
?fv131@FakeDispatcherBase@@EAGJXZ endp
?fv132@FakeDispatcherBase@@EAGJXZ proc
push 132
jmp _DualProcessCommandWrap
?fv132@FakeDispatcherBase@@EAGJXZ endp
?fv133@FakeDispatcherBase@@EAGJXZ proc
push 133
jmp _DualProcessCommandWrap
?fv133@FakeDispatcherBase@@EAGJXZ endp
?fv134@FakeDispatcherBase@@EAGJXZ proc
push 134
jmp _DualProcessCommandWrap
?fv134@FakeDispatcherBase@@EAGJXZ endp
?fv135@FakeDispatcherBase@@EAGJXZ proc
push 135
jmp _DualProcessCommandWrap
?fv135@FakeDispatcherBase@@EAGJXZ endp
?fv136@FakeDispatcherBase@@EAGJXZ proc
push 136
jmp _DualProcessCommandWrap
?fv136@FakeDispatcherBase@@EAGJXZ endp
?fv137@FakeDispatcherBase@@EAGJXZ proc
push 137
jmp _DualProcessCommandWrap
?fv137@FakeDispatcherBase@@EAGJXZ endp
?fv138@FakeDispatcherBase@@EAGJXZ proc
push 138
jmp _DualProcessCommandWrap
?fv138@FakeDispatcherBase@@EAGJXZ endp
?fv139@FakeDispatcherBase@@EAGJXZ proc
push 139
jmp _DualProcessCommandWrap
?fv139@FakeDispatcherBase@@EAGJXZ endp
?fv140@FakeDispatcherBase@@EAGJXZ proc
push 140
jmp _DualProcessCommandWrap
?fv140@FakeDispatcherBase@@EAGJXZ endp
?fv141@FakeDispatcherBase@@EAGJXZ proc
push 141
jmp _DualProcessCommandWrap
?fv141@FakeDispatcherBase@@EAGJXZ endp
?fv142@FakeDispatcherBase@@EAGJXZ proc
push 142
jmp _DualProcessCommandWrap
?fv142@FakeDispatcherBase@@EAGJXZ endp
?fv143@FakeDispatcherBase@@EAGJXZ proc
push 143
jmp _DualProcessCommandWrap
?fv143@FakeDispatcherBase@@EAGJXZ endp
?fv144@FakeDispatcherBase@@EAGJXZ proc
push 144
jmp _DualProcessCommandWrap
?fv144@FakeDispatcherBase@@EAGJXZ endp
?fv145@FakeDispatcherBase@@EAGJXZ proc
push 145
jmp _DualProcessCommandWrap
?fv145@FakeDispatcherBase@@EAGJXZ endp
?fv146@FakeDispatcherBase@@EAGJXZ proc
push 146
jmp _DualProcessCommandWrap
?fv146@FakeDispatcherBase@@EAGJXZ endp
?fv147@FakeDispatcherBase@@EAGJXZ proc
push 147
jmp _DualProcessCommandWrap
?fv147@FakeDispatcherBase@@EAGJXZ endp
?fv148@FakeDispatcherBase@@EAGJXZ proc
push 148
jmp _DualProcessCommandWrap
?fv148@FakeDispatcherBase@@EAGJXZ endp
?fv149@FakeDispatcherBase@@EAGJXZ proc
push 149
jmp _DualProcessCommandWrap
?fv149@FakeDispatcherBase@@EAGJXZ endp
?fv150@FakeDispatcherBase@@EAGJXZ proc
push 150
jmp _DualProcessCommandWrap
?fv150@FakeDispatcherBase@@EAGJXZ endp
?fv151@FakeDispatcherBase@@EAGJXZ proc
push 151
jmp _DualProcessCommandWrap
?fv151@FakeDispatcherBase@@EAGJXZ endp
?fv152@FakeDispatcherBase@@EAGJXZ proc
push 152
jmp _DualProcessCommandWrap
?fv152@FakeDispatcherBase@@EAGJXZ endp
?fv153@FakeDispatcherBase@@EAGJXZ proc
push 153
jmp _DualProcessCommandWrap
?fv153@FakeDispatcherBase@@EAGJXZ endp
?fv154@FakeDispatcherBase@@EAGJXZ proc
push 154
jmp _DualProcessCommandWrap
?fv154@FakeDispatcherBase@@EAGJXZ endp
?fv155@FakeDispatcherBase@@EAGJXZ proc
push 155
jmp _DualProcessCommandWrap
?fv155@FakeDispatcherBase@@EAGJXZ endp
?fv156@FakeDispatcherBase@@EAGJXZ proc
push 156
jmp _DualProcessCommandWrap
?fv156@FakeDispatcherBase@@EAGJXZ endp
?fv157@FakeDispatcherBase@@EAGJXZ proc
push 157
jmp _DualProcessCommandWrap
?fv157@FakeDispatcherBase@@EAGJXZ endp
?fv158@FakeDispatcherBase@@EAGJXZ proc
push 158
jmp _DualProcessCommandWrap
?fv158@FakeDispatcherBase@@EAGJXZ endp
?fv159@FakeDispatcherBase@@EAGJXZ proc
push 159
jmp _DualProcessCommandWrap
?fv159@FakeDispatcherBase@@EAGJXZ endp
?fv160@FakeDispatcherBase@@EAGJXZ proc
push 160
jmp _DualProcessCommandWrap
?fv160@FakeDispatcherBase@@EAGJXZ endp
?fv161@FakeDispatcherBase@@EAGJXZ proc
push 161
jmp _DualProcessCommandWrap
?fv161@FakeDispatcherBase@@EAGJXZ endp
?fv162@FakeDispatcherBase@@EAGJXZ proc
push 162
jmp _DualProcessCommandWrap
?fv162@FakeDispatcherBase@@EAGJXZ endp
?fv163@FakeDispatcherBase@@EAGJXZ proc
push 163
jmp _DualProcessCommandWrap
?fv163@FakeDispatcherBase@@EAGJXZ endp
?fv164@FakeDispatcherBase@@EAGJXZ proc
push 164
jmp _DualProcessCommandWrap
?fv164@FakeDispatcherBase@@EAGJXZ endp
?fv165@FakeDispatcherBase@@EAGJXZ proc
push 165
jmp _DualProcessCommandWrap
?fv165@FakeDispatcherBase@@EAGJXZ endp
?fv166@FakeDispatcherBase@@EAGJXZ proc
push 166
jmp _DualProcessCommandWrap
?fv166@FakeDispatcherBase@@EAGJXZ endp
?fv167@FakeDispatcherBase@@EAGJXZ proc
push 167
jmp _DualProcessCommandWrap
?fv167@FakeDispatcherBase@@EAGJXZ endp
?fv168@FakeDispatcherBase@@EAGJXZ proc
push 168
jmp _DualProcessCommandWrap
?fv168@FakeDispatcherBase@@EAGJXZ endp
?fv169@FakeDispatcherBase@@EAGJXZ proc
push 169
jmp _DualProcessCommandWrap
?fv169@FakeDispatcherBase@@EAGJXZ endp
?fv170@FakeDispatcherBase@@EAGJXZ proc
push 170
jmp _DualProcessCommandWrap
?fv170@FakeDispatcherBase@@EAGJXZ endp
?fv171@FakeDispatcherBase@@EAGJXZ proc
push 171
jmp _DualProcessCommandWrap
?fv171@FakeDispatcherBase@@EAGJXZ endp
?fv172@FakeDispatcherBase@@EAGJXZ proc
push 172
jmp _DualProcessCommandWrap
?fv172@FakeDispatcherBase@@EAGJXZ endp
?fv173@FakeDispatcherBase@@EAGJXZ proc
push 173
jmp _DualProcessCommandWrap
?fv173@FakeDispatcherBase@@EAGJXZ endp
?fv174@FakeDispatcherBase@@EAGJXZ proc
push 174
jmp _DualProcessCommandWrap
?fv174@FakeDispatcherBase@@EAGJXZ endp
?fv175@FakeDispatcherBase@@EAGJXZ proc
push 175
jmp _DualProcessCommandWrap
?fv175@FakeDispatcherBase@@EAGJXZ endp
?fv176@FakeDispatcherBase@@EAGJXZ proc
push 176
jmp _DualProcessCommandWrap
?fv176@FakeDispatcherBase@@EAGJXZ endp
?fv177@FakeDispatcherBase@@EAGJXZ proc
push 177
jmp _DualProcessCommandWrap
?fv177@FakeDispatcherBase@@EAGJXZ endp
?fv178@FakeDispatcherBase@@EAGJXZ proc
push 178
jmp _DualProcessCommandWrap
?fv178@FakeDispatcherBase@@EAGJXZ endp
?fv179@FakeDispatcherBase@@EAGJXZ proc
push 179
jmp _DualProcessCommandWrap
?fv179@FakeDispatcherBase@@EAGJXZ endp
?fv180@FakeDispatcherBase@@EAGJXZ proc
push 180
jmp _DualProcessCommandWrap
?fv180@FakeDispatcherBase@@EAGJXZ endp
?fv181@FakeDispatcherBase@@EAGJXZ proc
push 181
jmp _DualProcessCommandWrap
?fv181@FakeDispatcherBase@@EAGJXZ endp
?fv182@FakeDispatcherBase@@EAGJXZ proc
push 182
jmp _DualProcessCommandWrap
?fv182@FakeDispatcherBase@@EAGJXZ endp
?fv183@FakeDispatcherBase@@EAGJXZ proc
push 183
jmp _DualProcessCommandWrap
?fv183@FakeDispatcherBase@@EAGJXZ endp
?fv184@FakeDispatcherBase@@EAGJXZ proc
push 184
jmp _DualProcessCommandWrap
?fv184@FakeDispatcherBase@@EAGJXZ endp
?fv185@FakeDispatcherBase@@EAGJXZ proc
push 185
jmp _DualProcessCommandWrap
?fv185@FakeDispatcherBase@@EAGJXZ endp
?fv186@FakeDispatcherBase@@EAGJXZ proc
push 186
jmp _DualProcessCommandWrap
?fv186@FakeDispatcherBase@@EAGJXZ endp
?fv187@FakeDispatcherBase@@EAGJXZ proc
push 187
jmp _DualProcessCommandWrap
?fv187@FakeDispatcherBase@@EAGJXZ endp
?fv188@FakeDispatcherBase@@EAGJXZ proc
push 188
jmp _DualProcessCommandWrap
?fv188@FakeDispatcherBase@@EAGJXZ endp
?fv189@FakeDispatcherBase@@EAGJXZ proc
push 189
jmp _DualProcessCommandWrap
?fv189@FakeDispatcherBase@@EAGJXZ endp
?fv190@FakeDispatcherBase@@EAGJXZ proc
push 190
jmp _DualProcessCommandWrap
?fv190@FakeDispatcherBase@@EAGJXZ endp
?fv191@FakeDispatcherBase@@EAGJXZ proc
push 191
jmp _DualProcessCommandWrap
?fv191@FakeDispatcherBase@@EAGJXZ endp
?fv192@FakeDispatcherBase@@EAGJXZ proc
push 192
jmp _DualProcessCommandWrap
?fv192@FakeDispatcherBase@@EAGJXZ endp
?fv193@FakeDispatcherBase@@EAGJXZ proc
push 193
jmp _DualProcessCommandWrap
?fv193@FakeDispatcherBase@@EAGJXZ endp
?fv194@FakeDispatcherBase@@EAGJXZ proc
push 194
jmp _DualProcessCommandWrap
?fv194@FakeDispatcherBase@@EAGJXZ endp
?fv195@FakeDispatcherBase@@EAGJXZ proc
push 195
jmp _DualProcessCommandWrap
?fv195@FakeDispatcherBase@@EAGJXZ endp
?fv196@FakeDispatcherBase@@EAGJXZ proc
push 196
jmp _DualProcessCommandWrap
?fv196@FakeDispatcherBase@@EAGJXZ endp
?fv197@FakeDispatcherBase@@EAGJXZ proc
push 197
jmp _DualProcessCommandWrap
?fv197@FakeDispatcherBase@@EAGJXZ endp
?fv198@FakeDispatcherBase@@EAGJXZ proc
push 198
jmp _DualProcessCommandWrap
?fv198@FakeDispatcherBase@@EAGJXZ endp
?fv199@FakeDispatcherBase@@EAGJXZ proc
push 199
jmp _DualProcessCommandWrap
?fv199@FakeDispatcherBase@@EAGJXZ endp
end
| zzhongster-npactivex | ffactivex/FakeDispatcherBase.asm | Assembly | mpl11 | 32,722 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <atlbase.h>
#include <comdef.h>
#include <npapi.h>
#include <npfunctions.h>
#include <npruntime.h>
#include "variants.h"
#include "FakeDispatcher.h"
#include "Host.h"
extern NPNetscapeFuncs NPNFuncs;
class CAxHost;
struct Scriptable: public ScriptBase
{
private:
Scriptable(const Scriptable &);
// This method iterates all members of the current interface, looking for the member with the
// id of member_id. If not found within this interface, it will iterate all base interfaces
// recursively, until a match is found, or all the hierarchy was searched.
bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind);
DISPID ResolveName(NPIdentifier name, unsigned int invKind);
//bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult);
CComQIPtr<IDispatch> disp;
bool invalid;
DISPID dispid;
void setControl(IUnknown *unk) {
disp = unk;
}
bool IsProperty(DISPID member_id);
public:
Scriptable(NPP npp):
ScriptBase(npp),
invalid(false) {
dispid = -1;
}
~Scriptable() {
}
static NPClass npClass;
static Scriptable* FromIUnknown(NPP npp, IUnknown *unk) {
Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass);
new_obj->setControl(unk);
return new_obj;
}
static Scriptable* FromAxHost(NPP npp, CAxHost* host);
HRESULT getControl(IUnknown **obj) {
if (disp) {
*obj = disp.p;
(*obj)->AddRef();
return S_OK;
}
return E_NOT_SET;
}
void Invalidate() {invalid = true;}
bool HasMethod(NPIdentifier name);
bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result);
bool InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result);
bool HasProperty(NPIdentifier name);
bool GetProperty(NPIdentifier name, NPVariant *result);
bool SetProperty(NPIdentifier name, const NPVariant *value);
bool Enumerate(NPIdentifier **value, uint32_t *count);
private:
// Some wrappers to adapt NPAPI's interface.
static NPObject* _Allocate(NPP npp, NPClass *aClass);
static void _Deallocate(NPObject *obj);
static void _Invalidate(NPObject *obj)
{
if (obj) {
((Scriptable *)obj)->Invalidate();
}
}
static bool _HasMethod(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasMethod(name);
}
static bool _Invoke(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result) {
return ((Scriptable *)npobj)->Invoke(name, args, argCount, result);
}
static bool _HasProperty(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasProperty(name);
}
static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return ((Scriptable *)npobj)->GetProperty(name, result);
}
static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return ((Scriptable *)npobj)->SetProperty(name, value);
}
static bool _Enumerate(NPObject *npobj, NPIdentifier **value, uint32_t *count) {
return ((Scriptable *)npobj)->Enumerate(value, count);
}
};
| zzhongster-npactivex | ffactivex/scriptable.h | C++ | mpl11 | 4,934 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <npapi.h>
#include <npruntime.h>
struct ScriptBase;
class CHost
{
public:
void AddRef();
void Release();
CHost(NPP npp);
virtual ~CHost(void);
NPObject *GetScriptableObject();
NPP GetInstance() {
return instance;
}
static ScriptBase *GetInternalObject(NPP npp, NPObject *embed_element);
NPObject *RegisterObject();
void UnRegisterObject();
virtual NPP ResetNPP(NPP newNpp);
protected:
NPP instance;
ScriptBase *lastObj;
ScriptBase *GetMyScriptObject();
virtual ScriptBase *CreateScriptableObject() = 0;
private:
int ref_cnt_;
};
struct ScriptBase: NPObject {
NPP instance;
CHost* host;
ScriptBase(NPP instance_) : instance(instance_) {
}
}; | zzhongster-npactivex | ffactivex/Host.h | C++ | mpl11 | 2,246 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "scriptable.h"
#include "axhost.h"
#include "ScriptFunc.h"
#include "npactivex.h"
NPClass Scriptable::npClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ Scriptable::_Allocate,
/* deallocate */ Scriptable::_Deallocate,
/* invalidate */ Scriptable::_Invalidate,
/* hasMethod */ NULL, //Scriptable::_HasMethod,
/* invoke */ NULL, //Scriptable::_Invoke,
/* invokeDefault */ NULL,
/* hasProperty */ Scriptable::_HasProperty,
/* getProperty */ Scriptable::_GetProperty,
/* setProperty */ Scriptable::_SetProperty,
/* removeProperty */ NULL,
/* enumerate */ Scriptable::_Enumerate,
/* construct */ NULL
};
bool Scriptable::find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) {
bool found = false;
unsigned int i = 0;
FUNCDESC *fDesc;
for (i = 0; (i < attr->cFuncs) && !found; ++i) {
HRESULT hr = info->GetFuncDesc(i, &fDesc);
if (SUCCEEDED(hr)
&& fDesc
&& (fDesc->memid == member_id)) {
if (invKind & fDesc->invkind)
found = true;
}
info->ReleaseFuncDesc(fDesc);
}
#if 0
if (!found && (invKind & ~INVOKE_FUNC)) {
VARDESC *vDesc;
for (i = 0;
(i < attr->cVars)
&& !found;
++i) {
HRESULT hr = info->GetVarDesc(i, &vDesc);
if ( SUCCEEDED(hr)
&& vDesc
&& (vDesc->memid == member_id)) {
found = true;
}
info->ReleaseVarDesc(vDesc);
}
}
if (!found) {
// iterate inherited interfaces
HREFTYPE refType = NULL;
for (i = 0; (i < attr->cImplTypes) && !found; ++i) {
ITypeInfoPtr baseInfo;
TYPEATTR *baseAttr;
if (FAILED(info->GetRefTypeOfImplType(0, &refType))) {
continue;
}
if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) {
continue;
}
baseInfo->AddRef();
if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) {
continue;
}
found = find_member(baseInfo, baseAttr, member_id, invKind);
baseInfo->ReleaseTypeAttr(baseAttr);
}
}
#endif
return found;
}
bool Scriptable::IsProperty(DISPID member_id) {
ITypeInfo *typeinfo;
if (FAILED(disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &typeinfo))) {
return false;
}
TYPEATTR *typeAttr;
typeinfo->GetTypeAttr(&typeAttr);
bool ret = find_member(typeinfo, typeAttr, member_id, DISPATCH_METHOD);
typeinfo->ReleaseTypeAttr(typeAttr);
typeinfo->Release();
return !ret;
}
DISPID Scriptable::ResolveName(NPIdentifier name, unsigned int invKind) {
bool found = false;
DISPID dID = -1;
USES_CONVERSION;
if (!name || !invKind) {
return -1;
}
if (!disp) {
return -1;
}
if (!NPNFuncs.identifierisstring(name)) {
return -1;
}
NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name);
LPOLESTR oleName = A2W(npname);
disp->GetIDsOfNames(IID_NULL, &oleName, 1, 0, &dID);
return dID;
#if 0
int funcInv;
if (FindElementInvKind(disp, dID, &funcInv)) {
if (funcInv & invKind)
return dID;
else
return -1;
} else {
if ((dID != -1) && (invKind & INVOKE_PROPERTYGET)) {
// Try to get property to check.
// Use two parameters. It will definitely fail in property get/set, but it will return other orrer if it's not property.
CComVariant var[2];
DISPPARAMS par = {var, NULL, 2, 0};
CComVariant result;
HRESULT hr = disp->Invoke(dID, IID_NULL, 1, invKind, &par, &result, NULL, NULL);
if (hr == DISP_E_MEMBERNOTFOUND || hr == DISP_E_TYPEMISMATCH)
return -1;
}
}
return dID;
#endif
if (dID != -1) {
ITypeInfoPtr info;
disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info);
if (!info) {
return -1;
}
TYPEATTR *attr;
if (FAILED(info->GetTypeAttr(&attr))) {
return -1;
}
found = find_member(info, attr, dID, invKind);
info->ReleaseTypeAttr(attr);
}
return found ? dID : -1;
}
bool Scriptable::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
np_log(instance, 2, "Invoke %s", NPNFuncs.utf8fromidentifier(name));
DISPID id = ResolveName(name, INVOKE_FUNC);
bool ret = InvokeID(id, args, argCount, result);
if (!ret) {
np_log(instance, 0, "Invoke failed: %s", NPNFuncs.utf8fromidentifier(name));
}
return ret;
}
bool Scriptable::InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (-1 == id) {
return false;
}
CComVariant *vArgs = NULL;
if (argCount) {
vArgs = new CComVariant[argCount];
if (!vArgs) {
return false;
}
for (unsigned int i = 0; i < argCount; ++i) {
// copy the arguments in reverse order
NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance);
}
}
DISPPARAMS params = {NULL, NULL, 0, 0};
params.cArgs = argCount;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = vArgs;
CComVariant vResult;
HRESULT rc = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, ¶ms, &vResult, NULL, NULL);
if (vArgs) {
delete []vArgs;
}
if (FAILED(rc)) {
return false;
}
Variant2NPVar(&vResult, result, instance);
return true;
}
bool Scriptable::HasMethod(NPIdentifier name) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_FUNC);
return (id != -1) ? true : false;
}
bool Scriptable::HasProperty(NPIdentifier name) {
static NPIdentifier classid = NPNFuncs.getstringidentifier("classid");
if (name == classid) {
return true;
}
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT);
return (id != -1) ? true : false;
}
bool Scriptable::GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid)
return false;
static NPIdentifier classid = NPNFuncs.getstringidentifier("classid");
if (name == classid) {
CAxHost *host = (CAxHost*)this->host;
if (this->disp == NULL) {
char* cstr = (char*)NPNFuncs.memalloc(1);
cstr[0] = 0;
STRINGZ_TO_NPVARIANT(cstr, *result);
return true;
} else {
USES_CONVERSION;
char* cstr = (char*)NPNFuncs.memalloc(50);
strcpy(cstr, "CLSID:");
LPOLESTR clsidstr;
StringFromCLSID(host->getClsID(), &clsidstr);
// Remove braces.
clsidstr[lstrlenW(clsidstr) - 1] = '\0';
strcat(cstr, OLE2A(clsidstr + 1));
CoTaskMemFree(clsidstr);
STRINGZ_TO_NPVARIANT(cstr, *result);
return true;
}
}
DISPID id = ResolveName(name, INVOKE_PROPERTYGET);
if (-1 == id) {
np_log(instance, 0, "Cannot find property: %s", NPNFuncs.utf8fromidentifier(name));
return false;
}
DISPPARAMS params;
params.cArgs = 0;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = NULL;
CComVariant vResult;
if (IsProperty(id)) {
HRESULT hr = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, ¶ms, &vResult, NULL, NULL);
if (SUCCEEDED(hr)) {
Variant2NPVar(&vResult, result, instance);
np_log(instance, 2, "GetProperty %s", NPNFuncs.utf8fromidentifier(name));
return true;
}
}
np_log(instance, 2, "GetMethodObject %s", NPNFuncs.utf8fromidentifier(name));
OBJECT_TO_NPVARIANT(ScriptFunc::GetFunctionObject(instance, this, id), *result);
return true;
}
bool Scriptable::SetProperty(NPIdentifier name, const NPVariant *value) {
static NPIdentifier classid = NPNFuncs.getstringidentifier("classid");
if (name == classid) {
np_log(instance, 1, "Set classid property: %s", value->value.stringValue);
CAxHost* axhost = (CAxHost*)host;
CLSID newCLSID = CAxHost::ParseCLSIDFromSetting(value->value.stringValue.UTF8Characters, value->value.stringValue.UTF8Length);
if (newCLSID != GUID_NULL && (!axhost->hasValidClsID() || newCLSID != axhost->getClsID())) {
axhost->Clear();
if (axhost->setClsID(newCLSID)) {
axhost->CreateControl(false);
IUnknown *unk;
if (SUCCEEDED(axhost->GetControlUnknown(&unk))) {
this->setControl(unk);
unk->Release();
}
axhost->ResetWindow();
}
}
return true;
}
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYPUT);
if (-1 == id) {
return false;
}
CComVariant val;
NPVar2Variant(value, &val, instance);
DISPPARAMS params;
// Special initialization needed when using propery put.
DISPID dispidNamed = DISPID_PROPERTYPUT;
params.cNamedArgs = 1;
params.rgdispidNamedArgs = &dispidNamed;
params.cArgs = 1;
params.rgvarg = &val;
CComVariant vResult;
WORD wFlags = DISPATCH_PROPERTYPUT;
if (val.vt == VT_DISPATCH) {
wFlags |= DISPATCH_PROPERTYPUTREF;
}
const char* pname = NPNFuncs.utf8fromidentifier(name);
if (FAILED(disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, ¶ms, &vResult, NULL, NULL))) {
np_log(instance, 0, "SetProperty failed %s", pname);
return false;
}
np_log(instance, 0, "SetProperty %s", pname);
return true;
}
Scriptable* Scriptable::FromAxHost(NPP npp, CAxHost* host)
{
Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass);
IUnknown *unk;
if (SUCCEEDED(host->GetControlUnknown(&unk))) {
new_obj->setControl(unk);
new_obj->host = host;
unk->Release();
}
return new_obj;
}
NPObject* Scriptable::_Allocate(NPP npp, NPClass *aClass)
{
return new Scriptable(npp);
}
void Scriptable::_Deallocate(NPObject *obj) {
if (obj) {
Scriptable *a = static_cast<Scriptable*>(obj);
//np_log(a->instance, 3, "Dealocate obj");
delete a;
}
}
bool Scriptable::Enumerate(NPIdentifier **value, uint32_t *count) {
UINT cnt;
if (!disp || FAILED(disp->GetTypeInfoCount(&cnt)))
return false;
*count = 0;
for (UINT i = 0; i < cnt; ++i) {
CComPtr<ITypeInfo> info;
disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info);
TYPEATTR *attr;
info->GetTypeAttr(&attr);
*count += attr->cFuncs;
info->ReleaseTypeAttr(attr);
}
uint32_t pos = 0;
NPIdentifier *v = (NPIdentifier*) NPNFuncs.memalloc(sizeof(NPIdentifier) * *count);
USES_CONVERSION;
for (UINT i = 0; i < cnt; ++i) {
CComPtr<ITypeInfo> info;
disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info);
TYPEATTR *attr;
info->GetTypeAttr(&attr);
BSTR name;
for (uint j = 0; j < attr->cFuncs; ++j) {
FUNCDESC *desc;
info->GetFuncDesc(j, &desc);
if (SUCCEEDED(info->GetDocumentation(desc->memid, &name, NULL, NULL, NULL))) {
LPCSTR str = OLE2A(name);
v[pos++] = NPNFuncs.getstringidentifier(str);
SysFreeString(name);
}
info->ReleaseFuncDesc(desc);
}
info->ReleaseTypeAttr(attr);
}
*count = pos;
*value = v;
return true;
} | zzhongster-npactivex | ffactivex/scriptable.cpp | C++ | mpl11 | 12,450 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// dllmain.cpp : Defines the entry point for the DLL application.
#include "npactivex.h"
#include "axhost.h"
#include "atlthunk.h"
#include "FakeDispatcher.h"
CComModule _Module;
NPNetscapeFuncs NPNFuncs;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// ==============================
// ! Scriptability related code !
// ==============================
//
// here the plugin is asked by Mozilla to tell if it is scriptable
// we should return a valid interface id and a pointer to
// nsScriptablePeer interface which we should have implemented
// and which should be defined in the corressponding *.xpt file
// in the bin/components folder
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
if(instance == NULL)
return NPERR_GENERIC_ERROR;
CAxHost *host = (CAxHost *)instance->pdata;
if(host == NULL)
return NPERR_GENERIC_ERROR;
switch (variable) {
case NPPVpluginNameString:
*((char **)value) = "ITSTActiveX";
break;
case NPPVpluginDescriptionString:
*((char **)value) = "IT Structures ActiveX for Firefox";
break;
case NPPVpluginScriptableNPObject:
*(NPObject **)value = host->GetScriptableObject();
break;
default:
rv = NPERR_GENERIC_ERROR;
}
return rv;
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream* stream,
NPBool seekable,
uint16* stype)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int32_t NPP_WriteReady (NPP instance, NPStream *stream)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = 0x0fffffff;
return rv;
}
int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = len;
return rv;
}
NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname)
{
if(instance == NULL)
return;
}
void NPP_Print (NPP instance, NPPrint* printInfo)
{
if(instance == NULL)
return;
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData)
{
if(instance == NULL)
return;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int16 NPP_HandleEvent(NPP instance, void* event)
{
if(instance == NULL)
return 0;
int16 rv = 0;
CAxHost *host = dynamic_cast<CAxHost*>((CHost *)instance->pdata);
if (host)
rv = host->HandleEvent(event);
return rv;
}
NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
if(pFuncs->size < sizeof(NPPluginFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = NPP_HandleEvent;
pFuncs->urlnotify = NPP_URLNotify;
pFuncs->getvalue = NPP_GetValue;
pFuncs->setvalue = NPP_SetValue;
pFuncs->javaClass = NULL;
return NPERR_NO_ERROR;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
/*
* Initialize the plugin. Called the first time the browser comes across a
* MIME Type this plugin is registered to handle.
*/
NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs)
{
#ifdef DEBUG
CString text;
text.Format(_T("NPActiveX Pid %d"), GetCurrentProcessId());
MessageBox(NULL, text, _T(""), MB_OK);
#endif
CoInitialize(NULL);
InstallAtlThunkEnumeration();
if (pHtmlLib == NULL) {
OLECHAR path[MAX_PATH];
GetEnvironmentVariableW(OLESTR("SYSTEMROOT"), path, MAX_PATH - 30);
StrCatW(path, L"\\system32\\mshtml.tlb");
HRESULT hr = LoadTypeLib(path, &pHtmlLib);
}
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
#ifdef NDEF
// The following statements prevented usage of newer Mozilla sources than installed browser at runtime
if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
if(pFuncs->size < sizeof(NPNetscapeFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
#endif
if (!AtlAxWinInit()) {
return NPERR_GENERIC_ERROR;
}
_pAtlModule = &_Module;
memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs));
memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs)));
return NPERR_NO_ERROR;
}
/*
* Shutdown the plugin. Called when no more instanced of this plugin exist and
* the browser wants to unload it.
*/
NPError OSCALL NP_Shutdown(void)
{
AtlAxWinTerm();
UninstallAtlThunkEnumeration();
return NPERR_NO_ERROR;
}
| zzhongster-npactivex | ffactivex/dllmain.cpp | C++ | mpl11 | 7,451 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "NPSafeArray.h"
#include "npactivex.h"
#include "objectProxy.h"
#include <OleAuto.h>
NPClass NPSafeArray::npClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ NPSafeArray::Allocate,
/* deallocate */ NPSafeArray::Deallocate,
/* invalidate */ NPSafeArray::Invalidate,
/* hasMethod */ NPSafeArray::HasMethod,
/* invoke */ NPSafeArray::Invoke,
/* invokeDefault */ NPSafeArray::InvokeDefault,
/* hasProperty */ NPSafeArray::HasProperty,
/* getProperty */ NPSafeArray::GetProperty,
/* setProperty */ NPSafeArray::SetProperty,
/* removeProperty */ NULL,
/* enumerate */ NULL,
/* construct */ NPSafeArray::InvokeDefault
};
NPSafeArray::NPSafeArray(NPP npp): ScriptBase(npp)
{
NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window);
}
NPSafeArray::~NPSafeArray(void)
{
}
// Some wrappers to adapt NPAPI's interface.
NPObject* NPSafeArray::Allocate(NPP npp, NPClass *aClass) {
return new NPSafeArray(npp);
}
void NPSafeArray::Deallocate(NPObject *obj){
delete static_cast<NPSafeArray*>(obj);
}
LPSAFEARRAY NPSafeArray::GetArrayPtr() {
return arr_.m_psa;
}
NPInvokeDefaultFunctionPtr NPSafeArray::GetFuncPtr(NPIdentifier name) {
if (name == NPNFuncs.getstringidentifier("getItem")) {
return NPSafeArray::GetItem;
} else if (name == NPNFuncs.getstringidentifier("toArray")) {
return NPSafeArray::ToArray;
} else if (name == NPNFuncs.getstringidentifier("lbound")) {
return NPSafeArray::LBound;
} else if (name == NPNFuncs.getstringidentifier("ubound")) {
return NPSafeArray::UBound;
} else if (name == NPNFuncs.getstringidentifier("dimensions")) {
return NPSafeArray::Dimensions;
} else {
return NULL;
}
}
void NPSafeArray::Invalidate(NPObject *obj) {
NPSafeArray *safe = static_cast<NPSafeArray*>(obj);
safe->arr_.Destroy();
}
bool NPSafeArray::HasMethod(NPObject *npobj, NPIdentifier name) {
return GetFuncPtr(name) != NULL;
}
void NPSafeArray::RegisterVBArray(NPP npp) {
NPObjectProxy window;
NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window);
NPIdentifier vbarray = NPNFuncs.getstringidentifier("VBArray");
if (!NPNFuncs.hasproperty(npp, window, vbarray)) {
NPVariantProxy var;
NPObject *def = NPNFuncs.createobject(npp, &npClass);
OBJECT_TO_NPVARIANT(def, var);
NPNFuncs.setproperty(npp, window, vbarray, &var);
}
}
NPSafeArray *NPSafeArray::CreateFromArray(NPP instance, SAFEARRAY *array) {
NPSafeArray *ret = (NPSafeArray *)NPNFuncs.createobject(instance, &npClass);
ret->arr_.Attach(array);
return ret;
}
bool NPSafeArray::Invoke(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result) {
NPSafeArray *safe = static_cast<NPSafeArray*>(npobj);
if (safe->arr_.m_psa == NULL)
return false;
NPInvokeDefaultFunctionPtr ptr = GetFuncPtr(name);
if (ptr) {
return ptr(npobj, args, argCount, result);
} else {
return false;
}
}
bool NPSafeArray::InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result) {
NPSafeArray *safe = static_cast<NPSafeArray*>(npobj);
if (safe->arr_.m_psa != NULL)
return false;
if (argCount < 1)
return false;
if (!NPVARIANT_IS_OBJECT(*args)) {
return false;
}
NPObject *obj = NPVARIANT_TO_OBJECT(*args);
if (obj->_class != &NPSafeArray::npClass) {
return false;
}
NPSafeArray *safe_original = static_cast<NPSafeArray*>(obj);
if (safe_original->arr_.m_psa == NULL) {
return false;
}
NPSafeArray *ret = CreateFromArray(safe->instance, safe_original->arr_);
OBJECT_TO_NPVARIANT(ret, *result);
return true;
}
bool NPSafeArray::GetItem(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result) {
NPSafeArray *safe = static_cast<NPSafeArray*>(npobj);
if (safe->arr_.m_psa == NULL)
return false;
LONG dim = safe->arr_.GetDimensions();
if (argCount < safe->arr_.GetDimensions()) {
return false;
}
CAutoVectorPtr<LONG>pos(new LONG[dim]);
for (int i = 0; i < dim; ++i) {
if (NPVARIANT_IS_DOUBLE(args[i])) {
pos[i] = (LONG)NPVARIANT_TO_DOUBLE(args[i]);
} else if (NPVARIANT_IS_INT32(args[i])) {
pos[i] = NPVARIANT_TO_INT32(args[i]);
} else {
return false;
}
}
VARIANT var;
if (!SUCCEEDED(safe->arr_.MultiDimGetAt(pos, var))) {
return false;
}
Variant2NPVar(&var, result, safe->instance);
return true;
}
bool NPSafeArray::Dimensions(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result) {
NPSafeArray *safe = static_cast<NPSafeArray*>(npobj);
if (safe->arr_.m_psa == NULL)
return false;
INT32_TO_NPVARIANT(safe->arr_.GetDimensions(), *result);
return true;
}
bool NPSafeArray::UBound(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result) {
NPSafeArray *safe = static_cast<NPSafeArray*>(npobj);
if (safe->arr_.m_psa == NULL)
return false;
int dim = 1;
if (argCount >= 1) {
if (NPVARIANT_IS_INT32(*args)) {
dim = NPVARIANT_TO_INT32(*args);
} else if (NPVARIANT_IS_DOUBLE(*args)) {
dim = (LONG)NPVARIANT_TO_DOUBLE(*args);
} else {
return false;
}
}
try{
INT32_TO_NPVARIANT(safe->arr_.GetUpperBound(dim - 1), *result);
} catch (...) {
return false;
}
return true;
}
bool NPSafeArray::LBound(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result) {
NPSafeArray *safe = static_cast<NPSafeArray*>(npobj);
if (safe->arr_.m_psa == NULL)
return false;
int dim = 1;
if (argCount >= 1) {
if (NPVARIANT_IS_INT32(*args)) {
dim = NPVARIANT_TO_INT32(*args);
} else if (NPVARIANT_IS_DOUBLE(*args)) {
dim = (LONG)NPVARIANT_TO_DOUBLE(*args);
} else {
return false;
}
}
try{
INT32_TO_NPVARIANT(safe->arr_.GetLowerBound(dim - 1), *result);
} catch (...) {
return false;
}
return true;
}
bool NPSafeArray::ToArray(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result) {
NPSafeArray *safe = static_cast<NPSafeArray*>(npobj);
if (safe->arr_.m_psa == NULL)
return false;
long count = 1, dim = safe->arr_.GetDimensions();
for (int d = 0; d < dim; ++d) {
count *= safe->arr_.GetCount(d);
}
NPString command = {"[]", 2};
if (!NPNFuncs.evaluate(safe->instance, safe->window, &command, result))
return false;
VARIANT* vars = (VARIANT*)safe->arr_.m_psa->pvData;
NPIdentifier push = NPNFuncs.getstringidentifier("push");
for (long i = 0; i < count; ++i) {
NPVariantProxy v;
NPVariant arg;
Variant2NPVar(&vars[i], &arg, safe->instance);
if (!NPNFuncs.invoke(safe->instance, NPVARIANT_TO_OBJECT(*result), push, &arg, 1, &v)) {
return false;
}
}
return true;
}
bool NPSafeArray::HasProperty(NPObject *npobj, NPIdentifier name) {
return false;
}
bool NPSafeArray::GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return false;
}
bool NPSafeArray::SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return false;
} | zzhongster-npactivex | ffactivex/NPSafeArray.cpp | C++ | mpl11 | 8,634 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <atlbase.h>
#include <atlsafe.h>
#include <npapi.h>
#include <npfunctions.h>
#include "FakeDispatcher.h"
#include <npruntime.h>
#include "scriptable.h"
#include "GenericNPObject.h"
#include <OleAuto.h>
#include "variants.h"
#include "NPSafeArray.h"
void
BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance)
{
char *npStr = NULL;
size_t sourceLen;
size_t bytesNeeded;
sourceLen = lstrlenW(bstr);
bytesNeeded = WideCharToMultiByte(CP_UTF8,
0,
bstr,
sourceLen,
NULL,
0,
NULL,
NULL);
bytesNeeded += 1;
// complete lack of documentation on Mozilla's part here, I have no
// idea how this string is supposed to be freed
npStr = (char *)NPNFuncs.memalloc(bytesNeeded);
if (npStr) {
int len = WideCharToMultiByte(CP_UTF8,
0,
bstr,
sourceLen,
npStr,
bytesNeeded - 1,
NULL,
NULL);
npStr[len] = 0;
STRINGN_TO_NPVARIANT(npStr, len, (*npvar));
}
else {
VOID_TO_NPVARIANT(*npvar);
}
}
BSTR NPStringToBstr(const NPString npstr) {
size_t bytesNeeded;
bytesNeeded = MultiByteToWideChar(
CP_UTF8, 0, npstr.UTF8Characters, npstr.UTF8Length, NULL, 0);
bytesNeeded += 1;
BSTR bstr = (BSTR)CoTaskMemAlloc(sizeof(OLECHAR) * bytesNeeded);
if (bstr) {
int len = MultiByteToWideChar(
CP_UTF8, 0, npstr.UTF8Characters, npstr.UTF8Length, bstr, bytesNeeded);
bstr[len] = 0;
return bstr;
}
return NULL;
}
void
Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance)
{
FakeDispatcher *disp = NULL;
if (!unk) {
NULL_TO_NPVARIANT(*npvar);
} else if (SUCCEEDED(unk->QueryInterface(IID_IFakeDispatcher, (void**)&disp))) {
OBJECT_TO_NPVARIANT(disp->getObject(), *npvar);
NPNFuncs.retainobject(disp->getObject());
disp->Release();
} else {
NPObject *obj = Scriptable::FromIUnknown(instance, unk);
OBJECT_TO_NPVARIANT(obj, (*npvar));
}
}
#define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val))
void
Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance)
{
NPObject *obj = NULL;
if (!var || !npvar) {
return;
}
VOID_TO_NPVARIANT(*npvar);
USES_CONVERSION;
switch (var->vt & ~VT_BYREF) {
case VT_ARRAY | VT_VARIANT:
NPSafeArray::RegisterVBArray(instance);
NPSafeArray *obj;
obj = NPSafeArray::CreateFromArray(instance, var->parray);
OBJECT_TO_NPVARIANT(obj, (*npvar));
break;
case VT_EMPTY:
VOID_TO_NPVARIANT((*npvar));
break;
case VT_NULL:
NULL_TO_NPVARIANT((*npvar));
break;
case VT_LPSTR:
// not sure it can even appear in a VARIANT, but...
STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar));
break;
case VT_BSTR:
BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance);
break;
case VT_I1:
INT32_TO_NPVARIANT((INT32)GETVALUE(var, cVal), (*npvar));
break;
case VT_I2:
INT32_TO_NPVARIANT((INT32)GETVALUE(var, iVal), (*npvar));
break;
case VT_I4:
INT32_TO_NPVARIANT((INT32)GETVALUE(var, lVal), (*npvar));
break;
case VT_UI1:
INT32_TO_NPVARIANT((INT32)GETVALUE(var, bVal), (*npvar));
break;
case VT_UI2:
INT32_TO_NPVARIANT((INT32)GETVALUE(var, uiVal), (*npvar));
break;
case VT_UI4:
INT32_TO_NPVARIANT((INT32)GETVALUE(var, ulVal), (*npvar));
break;
case VT_INT:
INT32_TO_NPVARIANT((INT32)GETVALUE(var, lVal), (*npvar));
break;
case VT_BOOL:
BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar));
break;
case VT_R4:
DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar));
break;
case VT_R8:
DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar));
break;
case VT_DATE:
DOUBLE_TO_NPVARIANT(GETVALUE(var, date), (*npvar));
break;
case VT_DISPATCH:
case VT_USERDEFINED:
case VT_UNKNOWN:
Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance);
break;
case VT_VARIANT:
Variant2NPVar(var->pvarVal, npvar, instance);
break;
default:
// Some unsupported type
np_log(instance, 0, "Unsupported variant type %d", var->vt);
VOID_TO_NPVARIANT(*npvar);
break;
}
}
#undef GETVALUE
ITypeLib *pHtmlLib;
void
NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance)
{
if (!var || !npvar) {
return;
}
var->vt = VT_EMPTY;
switch (npvar->type) {
case NPVariantType_Void:
var->vt = VT_EMPTY;
var->ulVal = 0;
break;
case NPVariantType_Null:
var->vt = VT_NULL;
var->byref = NULL;
break;
case NPVariantType_Bool:
var->vt = VT_BOOL;
var->ulVal = npvar->value.boolValue;
break;
case NPVariantType_Int32:
var->vt = VT_I4;
var->ulVal = npvar->value.intValue;
break;
case NPVariantType_Double:
var->vt = VT_R8;
var->dblVal = npvar->value.doubleValue;
break;
case NPVariantType_String:
(CComVariant&)*var = NPStringToBstr(npvar->value.stringValue);
break;
case NPVariantType_Object:
NPObject *object = NPVARIANT_TO_OBJECT(*npvar);
var->vt = VT_DISPATCH;
if (object->_class == &Scriptable::npClass) {
Scriptable* scriptObj = (Scriptable*)object;
scriptObj->getControl(&var->punkVal);
} else if (object->_class == &NPSafeArray::npClass) {
NPSafeArray* arrayObj = (NPSafeArray*)object;
var->vt = VT_ARRAY | VT_VARIANT;
var->parray = arrayObj->GetArrayPtr();
} else {
IUnknown *val = new FakeDispatcher(instance, pHtmlLib, object);
var->punkVal = val;
}
break;
}
}
size_t VariantSize(VARTYPE vt) {
if ((vt & VT_BYREF) || (vt & VT_ARRAY))
return sizeof(LPVOID);
switch (vt)
{
case VT_EMPTY:
case VT_NULL:
case VT_VOID:
return 0;
case VT_I1:
case VT_UI1:
return 1;
case VT_I2:
case VT_UI2:
return 2;
case VT_R8:
case VT_DATE:
case VT_I8:
case VT_UI8:
case VT_CY:
return 8;
case VT_I4:
case VT_R4:
case VT_UI4:
case VT_BOOL:
return 4;
case VT_BSTR:
case VT_DISPATCH:
case VT_ERROR:
case VT_UNKNOWN:
case VT_DECIMAL:
case VT_INT:
case VT_UINT:
case VT_HRESULT:
case VT_PTR:
case VT_SAFEARRAY:
case VT_CARRAY:
case VT_USERDEFINED:
case VT_LPSTR:
case VT_LPWSTR:
case VT_INT_PTR:
case VT_UINT_PTR:
return sizeof(LPVOID);
case VT_VARIANT:
return sizeof(VARIANT);
default:
return 0;
}
}
HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest) {
// var is converted from NPVariant, so only limited types are possible.
HRESULT hr = S_OK;
switch (vt.vt)
{
case VT_EMPTY:
case VT_VOID:
case VT_NULL:
return S_OK;
case VT_I1:
case VT_UI1:
case VT_I2:
case VT_UI2:
case VT_I4:
case VT_R4:
case VT_UI4:
case VT_BOOL:
case VT_INT:
case VT_UINT:
int intvalue;
intvalue = NULL;
if (var.vt == VT_R8)
intvalue = (int)var.dblVal;
else if (var.vt == VT_BOOL)
intvalue = (int)var.boolVal;
else if (var.vt == VT_UI4)
intvalue = var.intVal;
else
return E_FAIL;
**(int**)dest = intvalue;
hr = S_OK;
break;
case VT_R8:
double dblvalue;
dblvalue = 0.0;
if (var.vt == VT_R8)
dblvalue = (double)var.dblVal;
else if (var.vt == VT_BOOL)
dblvalue = (double)var.boolVal;
else if (var.vt == VT_UI4)
dblvalue = var.intVal;
else
return E_FAIL;
**(double**)dest = dblvalue;
hr = S_OK;
break;
case VT_DATE:
case VT_I8:
case VT_UI8:
case VT_CY:
// I don't know how to deal with these types..
__asm{int 3};
case VT_BSTR:
case VT_DISPATCH:
case VT_ERROR:
case VT_UNKNOWN:
case VT_DECIMAL:
case VT_HRESULT:
case VT_SAFEARRAY:
case VT_CARRAY:
case VT_LPSTR:
case VT_LPWSTR:
case VT_INT_PTR:
case VT_UINT_PTR:
**(ULONG***)dest = var.pulVal;
break;
case VT_USERDEFINED:
{
if (var.vt != VT_UNKNOWN && var.vt != VT_DISPATCH) {
return E_FAIL;
} else {
ITypeInfo *newType;
baseType->GetRefTypeInfo(vt.hreftype, &newType);
IUnknown *unk = var.punkVal;
TYPEATTR *attr;
newType->GetTypeAttr(&attr);
hr = unk->QueryInterface(attr->guid, (LPVOID*)dest);
unk->Release();
newType->ReleaseTypeAttr(attr);
newType->Release();
}
}
break;
case VT_PTR:
return ConvertVariantToGivenType(baseType, *vt.lptdesc, var, *(LPVOID*)dest);
break;
case VT_VARIANT:
memcpy(*(VARIANT**)dest, &var, sizeof(var));
default:
_asm{int 3}
}
return hr;
}
void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var) {
BOOL pointer = FALSE;
switch (desc.vt) {
case VT_BSTR:
case VT_DISPATCH:
case VT_ERROR:
case VT_UNKNOWN:
case VT_SAFEARRAY:
case VT_CARRAY:
case VT_LPSTR:
case VT_LPWSTR:
case VT_INT_PTR:
case VT_UINT_PTR:
case VT_PTR:
// These are pointers
pointer = TRUE;
break;
default:
if (var->vt & VT_BYREF)
pointer = TRUE;
}
if (pointer) {
var->vt = desc.vt;
var->pulVal = *(PULONG*)source;
} else if (desc.vt == VT_VARIANT) {
// It passed by object, but we use as a pointer
var->vt = desc.vt;
var->pulVal = (PULONG)source;
} else {
var->vt = desc.vt | VT_BYREF;
var->pulVal = (PULONG)source;
}
} | zzhongster-npactivex | ffactivex/variants.cpp | C++ | mpl11 | 10,989 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "npapi.h"
#include <npfunctions.h>
#include <prtypes.h>
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
#include <atlcom.h>
#include <atlctl.h>
#include <varargs.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
//#define NO_REGISTRY_AUTHORIZE
#define np_log(instance, level, message, ...) log_activex_logging(instance, level, __FILE__, __LINE__, message, ##__VA_ARGS__)
// For catch breakpoints.
HRESULT NotImpl();
#define LogNotImplemented(instance) (np_log(instance, 0, "Not Implemented operation!!"), NotImpl())
void
log_activex_logging(NPP instance, unsigned int level, const char* file, int line, char *message, ...);
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved);
NPError NPP_Destroy(NPP instance, NPSavedData **save);
NPError NPP_SetWindow(NPP instance, NPWindow *window);
#define REGISTER_MANAGER | zzhongster-npactivex | ffactivex/npactivex.h | C | mpl11 | 2,994 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "Host.h"
#include <atlsafe.h>
#include "objectProxy.h"
class NPSafeArray: public ScriptBase
{
public:
NPSafeArray(NPP npp);
~NPSafeArray(void);
static NPSafeArray* CreateFromArray(NPP instance, SAFEARRAY* array);
static void RegisterVBArray(NPP npp);
static NPClass npClass;
SAFEARRAY* NPSafeArray::GetArrayPtr();
private:
static NPInvokeDefaultFunctionPtr GetFuncPtr(NPIdentifier name);
CComSafeArray<VARIANT> arr_;
NPObjectProxy window;
// Some wrappers to adapt NPAPI's interface.
static NPObject* Allocate(NPP npp, NPClass *aClass);
static void Deallocate(NPObject *obj);
static void Invalidate(NPObject *obj);
static bool HasMethod(NPObject *npobj, NPIdentifier name);
static bool Invoke(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool GetItem(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool ToArray(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool UBound(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool LBound(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool Dimensions(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool HasProperty(NPObject *npobj, NPIdentifier name);
static bool GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result);
static bool SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value);
};
| zzhongster-npactivex | ffactivex/NPSafeArray.h | C++ | mpl11 | 3,324 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
struct ITypeInfo;
void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance);
void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance);
size_t VariantSize(VARTYPE vt);
HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest);
void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var); | zzhongster-npactivex | ffactivex/variants.h | C | mpl11 | 2,086 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "oleidl.h"
#include <npapi.h>
#include <npruntime.h>
#include "npactivex.h"
#include "objectProxy.h"
#include "FakeDispatcher.h"
class HTMLDocumentContainer :
public CComObjectRoot,
public IOleContainer,
public IServiceProviderImpl<HTMLDocumentContainer>,
public IWebBrowser2
{
public:
HTMLDocumentContainer();
void Init(NPP instance, ITypeLib *htmlLib);
~HTMLDocumentContainer(void);
// IOleContainer
virtual HRESULT STDMETHODCALLTYPE EnumObjects(
/* [in] */ DWORD grfFlags,
/* [out] */ __RPC__deref_out_opt IEnumUnknown **ppenum) {
return LogNotImplemented(npp);
}
virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(
/* [unique][in] */ __RPC__in_opt IBindCtx *pbc,
/* [in] */ __RPC__in LPOLESTR pszDisplayName,
/* [out] */ __RPC__out ULONG *pchEaten,
/* [out] */ __RPC__deref_out_opt IMoniker **ppmkOut) {
return LogNotImplemented(npp);
}
virtual HRESULT STDMETHODCALLTYPE LockContainer(
/* [in] */ BOOL fLock) {
return LogNotImplemented(npp);
}
// IWebBrowser2
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate2(
/* [in] */ __RPC__in VARIANT *URL,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE QueryStatusWB(
/* [in] */ OLECMDID cmdID,
/* [retval][out] */ __RPC__out OLECMDF *pcmdf) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ExecWB(
/* [in] */ OLECMDID cmdID,
/* [in] */ OLECMDEXECOPT cmdexecopt,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *pvaIn,
/* [unique][optional][out][in] */ __RPC__inout_opt VARIANT *pvaOut) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowBrowserBar(
/* [in] */ __RPC__in VARIANT *pvaClsid,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarShow,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarSize) {return LogNotImplemented(npp);};
virtual /* [bindable][propget][id] */ HRESULT STDMETHODCALLTYPE get_ReadyState(
/* [out][retval] */ __RPC__out READYSTATE *plReadyState) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Offline(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbOffline) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Offline(
/* [in] */ VARIANT_BOOL bOffline) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Silent(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbSilent) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Silent(
/* [in] */ VARIANT_BOOL bSilent) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsBrowser(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsBrowser(
/* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsDropTarget(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsDropTarget(
/* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TheaterMode(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_TheaterMode(
/* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_AddressBar(
/* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {*Value = True;return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_AddressBar(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Resizable(
/* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Resizable(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Quit( void) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ClientToWindow(
/* [out][in] */ __RPC__inout int *pcx,
/* [out][in] */ __RPC__inout int *pcy) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE PutProperty(
/* [in] */ __RPC__in BSTR Property,
/* [in] */ VARIANT vtValue) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GetProperty(
/* [in] */ __RPC__in BSTR Property,
/* [retval][out] */ __RPC__out VARIANT *pvtValue) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Name(
/* [retval][out] */ __RPC__deref_out_opt BSTR *Name) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_HWND(
/* [retval][out] */ __RPC__out SHANDLE_PTR *pHWND) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullName(
/* [retval][out] */ __RPC__deref_out_opt BSTR *FullName) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Path(
/* [retval][out] */ __RPC__deref_out_opt BSTR *Path) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Visible(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Visible(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusBar(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusBar(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusText(
/* [retval][out] */ __RPC__deref_out_opt BSTR *StatusText) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusText(
/* [in] */ __RPC__in BSTR StatusText) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_ToolBar(
/* [retval][out] */ __RPC__out int *Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_ToolBar(
/* [in] */ int Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_MenuBar(
/* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_MenuBar(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullScreen(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbFullScreen) {*pbFullScreen = FALSE; return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_FullScreen(
/* [in] */ VARIANT_BOOL bFullScreen) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoBack( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoForward( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoHome( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoSearch( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate(
/* [in] */ __RPC__in BSTR URL,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh2(
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Level) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Stop( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Application(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Parent(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Container(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Document(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp);
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TopLevelContainer(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Type(
/* [retval][out] */ __RPC__deref_out_opt BSTR *Type) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Left(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Left(
/* [in] */ long Left) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Top(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Top(
/* [in] */ long Top) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Width(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Width(
/* [in] */ long Width) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Height(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Height(
/* [in] */ long Height) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationName(
/* [retval][out] */ __RPC__deref_out_opt BSTR *LocationName) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationURL(
/* [retval][out] */ __RPC__deref_out_opt BSTR *LocationURL);
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Busy(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(
/* [out] */ __RPC__out UINT *pctinfo) {return LogNotImplemented(npp);}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) {return LogNotImplemented(npp);}
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(
/* [in] */ __RPC__in REFIID riid,
/* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
/* [range][in] */ __RPC__in_range(0,16384) UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId) {return LogNotImplemented(npp);}
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr) {return LogNotImplemented(npp);}
BEGIN_COM_MAP(HTMLDocumentContainer)
COM_INTERFACE_ENTRY(IOleContainer)
COM_INTERFACE_ENTRY(IServiceProvider)
COM_INTERFACE_ENTRY(IWebBrowser2)
COM_INTERFACE_ENTRY_IID(IID_IWebBrowserApp, IWebBrowser2)
COM_INTERFACE_ENTRY_IID(IID_IWebBrowser, IWebBrowser2)
COM_INTERFACE_ENTRY_AGGREGATE_BLIND(dispatcher)
END_COM_MAP()
static const GUID IID_TopLevelBrowser;
BEGIN_SERVICE_MAP(HTMLDocumentContainer)
SERVICE_ENTRY(IID_IWebBrowserApp)
SERVICE_ENTRY(IID_IWebBrowser2)
SERVICE_ENTRY(IID_IWebBrowser)
SERVICE_ENTRY(SID_SContainerDispatch);
SERVICE_ENTRY(IID_TopLevelBrowser)
END_SERVICE_MAP()
private:
FakeDispatcher *dispatcher;
NPObjectProxy document_;
NPP npp;
};
| zzhongster-npactivex | ffactivex/HTMLDocumentContainer.h | C++ | mpl11 | 17,424 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <map>
#include <vector>
#include <atlbase.h>
#include <comdef.h>
#include <npapi.h>
#include <npfunctions.h>
#include <npruntime.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
extern NPClass GenericNPObjectClass;
typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result);
struct ltnum
{
bool operator()(long n1, long n2) const
{
return n1 < n2;
}
};
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result);
class GenericNPObject: public NPObject
{
private:
GenericNPObject(const GenericNPObject &);
bool invalid;
DefaultInvoker defInvoker;
void *defInvokerObject;
std::vector<NPVariant> numeric_mapper;
// the members of alpha mapper can be reassigned to anything the user wishes
std::map<const char *, NPVariant, ltstr> alpha_mapper;
// these cannot accept other types than they are initially defined with
std::map<const char *, NPVariant, ltstr> immutables;
public:
friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *);
GenericNPObject(NPP instance);
GenericNPObject(NPP instance, bool isMethodObj);
~GenericNPObject();
void Invalidate() {invalid = true;}
void SetDefaultInvoker(DefaultInvoker di, void *context) {
defInvoker = di;
defInvokerObject = context;
}
static bool _HasMethod(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->HasMethod(name);
}
static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) {
return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result);
}
static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (((GenericNPObject *)npobj)->defInvoker) {
return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result);
}
else {
return false;
}
}
static bool _HasProperty(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->HasProperty(name);
}
static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return ((GenericNPObject *)npobj)->GetProperty(name, result);
}
static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return ((GenericNPObject *)npobj)->SetProperty(name, value);
}
static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->RemoveProperty(name);
}
static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) {
return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount);
}
bool HasMethod(NPIdentifier name);
bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result);
bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result);
bool HasProperty(NPIdentifier name);
bool GetProperty(NPIdentifier name, NPVariant *result);
bool SetProperty(NPIdentifier name, const NPVariant *value);
bool RemoveProperty(NPIdentifier name);
bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount);
};
| zzhongster-npactivex | ffactivex/GenericNPObject.h | C++ | mpl11 | 5,100 |
#pragma once
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
| zzhongster-npactivex | ffactivex/targetver.h | C | mpl11 | 1,428 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <atlstr.h>
#include "npactivex.h"
#include "scriptable.h"
#include "axhost.h"
#include "ObjectManager.h"
#include "FakeDispatcher.h"
// {1DDBD54F-2F8A-4186-972B-2A84FE1135FE}
static const GUID IID_IFakeDispatcher =
{ 0x1ddbd54f, 0x2f8a, 0x4186, { 0x97, 0x2b, 0x2a, 0x84, 0xfe, 0x11, 0x35, 0xfe } };
ITypeInfo* FakeDispatcher::npTypeInfo = (ITypeInfo*)-1;
#define DispatchLog(level, message, ...) np_log(this->npInstance, level, "Disp 0x%08x " message, this, ##__VA_ARGS__)
FakeDispatcher::FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object)
: npInstance(npInstance), typeLib(typeLib), npObject(object), typeInfo(NULL), internalObj(NULL), extended(NULL)
{
ref = 1;
typeLib->AddRef();
NPNFuncs.retainobject(object);
ScriptBase *base = ObjectManager::GetInternalObject(npInstance, object);
if (base)
internalObj = dynamic_cast<CAxHost*>(base->host);
#ifdef DEBUG
name[0] = 0;
tag[0] = 0;
interfaceid = GUID_NULL;
#endif
NPVariantProxy npName, npTag;
ATL::CStringA sname, stag;
NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("id"), &npName);
if (npName.type != NPVariantType_String || npName.value.stringValue.UTF8Length == 0)
NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("name"), &npName);
if (npName.type == NPVariantType_String) {
sname = CStringA(npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length);
#ifdef DEBUG
strncpy(name, npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length);
name[npName.value.stringValue.UTF8Length] = 0;
#endif
}
if (NPNFuncs.hasmethod(npInstance, object, NPNFuncs.getstringidentifier("toString"))) {
NPNFuncs.invoke(npInstance, object, NPNFuncs.getstringidentifier("toString"), &npTag, 0, &npTag);
if (npTag.type == NPVariantType_String) {
stag = CStringA(npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length);
#ifdef DEBUG
strncpy(tag, npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length);
tag[npTag.value.stringValue.UTF8Length] = 0;
#endif
}
}
DispatchLog(1, "Type: %s, Name: %s", stag.GetString(), sname.GetString());
}
/* [local] */ HRESULT STDMETHODCALLTYPE
FakeDispatcher::Invoke(
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr) {
USES_CONVERSION;
// Convert variants
int nArgs = pDispParams->cArgs;
NPVariantProxy *npvars = new NPVariantProxy[nArgs];
for (int i = 0; i < nArgs; ++i) {
Variant2NPVar(&pDispParams->rgvarg[nArgs - 1 - i], &npvars[i], npInstance);
}
// Determine method to call.
HRESULT hr = E_FAIL;
BSTR pBstrName;
NPVariantProxy result;
NPIdentifier identifier = NULL;
NPIdentifier itemIdentifier = NULL;
if (HasValidTypeInfo() && SUCCEEDED(typeInfo->GetDocumentation(dispIdMember, &pBstrName, NULL, NULL, NULL))) {
LPSTR str = OLE2A(pBstrName);
SysFreeString(pBstrName);
DispatchLog(2, "Invoke 0x%08x %d %s", dispIdMember, wFlags, str);
if (dispIdMember == 0x401 && strcmp(str, "url") == 0) {
str = "baseURI";
} else if (dispIdMember == 0x40A && strcmp(str, "parentWindow") == 0) {
str = "defaultView";
}
identifier = NPNFuncs.getstringidentifier(str);
if (dispIdMember == 0 && (wFlags & DISPATCH_METHOD) && strcmp(str, "item") == 0) {
// Item can be evaluated as the default property.
if (NPVARIANT_IS_INT32(npvars[0]))
itemIdentifier = NPNFuncs.getintidentifier(npvars[0].value.intValue);
else if (NPVARIANT_IS_STRING(npvars[0]))
itemIdentifier = NPNFuncs.getstringidentifier(npvars[0].value.stringValue.UTF8Characters);
}
else if (dispIdMember == 0x3E9 && (wFlags & DISPATCH_PROPERTYGET) && strcmp(str, "Script") == 0) {
identifier = NPNFuncs.getstringidentifier("defaultView");
}
}
else if (typeInfo == npTypeInfo && dispIdMember != NULL && dispIdMember != -1) {
identifier = (NPIdentifier) dispIdMember;
}
if (FAILED(hr) && itemIdentifier != NULL) {
if (NPNFuncs.hasproperty(npInstance, npObject, itemIdentifier)) {
if (NPNFuncs.getproperty(npInstance, npObject, itemIdentifier, &result)) {
hr = S_OK;
}
}
}
if (FAILED(hr) && (wFlags & DISPATCH_METHOD)) {
if (NPNFuncs.invoke(npInstance, npObject, identifier, npvars, nArgs, &result)) {
hr = S_OK;
}
}
if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYGET)) {
if (NPNFuncs.hasproperty(npInstance, npObject, identifier)) {
if (NPNFuncs.getproperty(npInstance, npObject, identifier, &result)) {
hr = S_OK;
}
}
}
if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYPUT)) {
if (nArgs == 1 && NPNFuncs.setproperty(npInstance, npObject, identifier, npvars))
hr = S_OK;
}
if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_METHOD)) {
// Call default method.
if (NPNFuncs.invokeDefault(npInstance, npObject, npvars, nArgs, &result)) {
hr = S_OK;
}
}
if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_PROPERTYGET) && pDispParams->cArgs == 0) {
// Return toString()
static NPIdentifier strIdentify = NPNFuncs.getstringidentifier("toString");
if (NPNFuncs.invoke(npInstance, npObject, strIdentify, NULL, 0, &result))
hr = S_OK;
}
if (SUCCEEDED(hr)) {
NPVar2Variant(&result, pVarResult, npInstance);
} else {
DispatchLog(2, "Invoke failed 0x%08x %d", dispIdMember, wFlags);
}
delete [] npvars;
return hr;
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject)
{
HRESULT hr = E_FAIL;
if (riid == IID_IDispatch || riid == IID_IUnknown) {
*ppvObject = this;
AddRef();
hr = S_OK;
} else if (riid == IID_IDispatchEx) {
if (extended == NULL)
extended = new FakeDispatcherEx(this);
*ppvObject = extended;
AddRef();
hr = S_OK;
} else if (riid == IID_IFakeDispatcher) {
*ppvObject = this;
AddRef();
hr = S_OK;
} else if (!typeInfo) {
hr = typeLib->GetTypeInfoOfGuid(riid, &typeInfo);
if (SUCCEEDED(hr)) {
TYPEATTR *attr;
typeInfo->GetTypeAttr(&attr);
dualType = attr->wTypeFlags;
*ppvObject = static_cast<FakeDispatcher*>(this);
AddRef();
typeInfo->ReleaseTypeAttr(attr);
}
} else {
FakeDispatcher *another_obj = new FakeDispatcher(npInstance, typeLib, npObject);
hr = another_obj->QueryInterface(riid, ppvObject);
another_obj->Release();
}
if (FAILED(hr) && internalObj) {
IUnknown *unk;
internalObj->GetControlUnknown(&unk);
hr = unk->QueryInterface(riid, ppvObject);
unk->Release();
/*
// Try to find the internal object
NPIdentifier object_id = NPNFuncs.getstringidentifier(object_property);
NPVariant npVar;
if (NPNFuncs.getproperty(npInstance, npObject, object_id, &npVar) && npVar.type == NPVariantType_Int32) {
IUnknown *internalObject = (IUnknown*)NPVARIANT_TO_INT32(npVar);
hr = internalObject->QueryInterface(riid, ppvObject);
}*/
}
#ifdef DEBUG
if (hr == S_OK) {
interfaceid = riid;
} else {
// Unsupported Interface!
}
#endif
USES_CONVERSION;
LPOLESTR clsid;
StringFromCLSID(riid, &clsid);
if (FAILED(hr)) {
DispatchLog(0, "Unsupported Interface %s", OLE2A(clsid));
} else {
DispatchLog(0, "QueryInterface %s", OLE2A(clsid));
}
return hr;
}
FakeDispatcher::~FakeDispatcher(void)
{
if (HasValidTypeInfo()) {
typeInfo->Release();
}
if (extended) {
delete extended;
}
DispatchLog(3, "Release");
NPNFuncs.releaseobject(npObject);
typeLib->Release();
}
// This function is used because the symbol of FakeDispatcher::ProcessCommand is not determined in asm file.
extern "C" HRESULT __cdecl DualProcessCommand(int parlength, int commandId, int returnAddr, FakeDispatcher *disp, ...){
// returnAddr is a placeholder for the calling proc.
va_list va;
va_start(va, disp);
// The parlength is on the stack, the modification will be reflect.
HRESULT ret = disp->ProcessCommand(commandId, &parlength, va);
va_end(va);
return ret;
}
HRESULT FakeDispatcher::GetTypeInfo(
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) {
if (iTInfo == 0 && HasValidTypeInfo()) {
*ppTInfo = typeInfo;
typeInfo->AddRef();
return S_OK;
}
return E_INVALIDARG;
}
HRESULT FakeDispatcher::GetIDsOfNames(
/* [in] */ __RPC__in REFIID riid,
/* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
/* [range][in] */ __RPC__in_range(0,16384) UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId){
if (HasValidTypeInfo()) {
return typeInfo->GetIDsOfNames(rgszNames, cNames, rgDispId);
} else {
USES_CONVERSION;
typeInfo = npTypeInfo;
for (UINT i = 0; i < cNames; ++i) {
DispatchLog(2, "GetIDsOfNames %s", OLE2A(rgszNames[i]));
rgDispId[i] = (DISPID) NPNFuncs.getstringidentifier(OLE2A(rgszNames[i]));
}
return S_OK;
}
}
HRESULT FakeDispatcher::ProcessCommand(int vfid, int *parlength, va_list &args)
{
// This exception is critical if we can't find the size of parameters.
if (!HasValidTypeInfo()) {
DispatchLog(0, "VT interface %d called without type info", vfid);
__asm int 3;
}
UINT index = FindFuncByVirtualId(vfid);
if (index == (UINT)-1) {
DispatchLog(0, "Unknown VT interface id");
__asm int 3;
}
FUNCDESC *func;
// We should count pointer of "this" first.
*parlength = sizeof(LPVOID);
if (FAILED(typeInfo->GetFuncDesc(index, &func)))
__asm int 3;
DISPPARAMS varlist;
// We don't need to clear them.
VARIANT *list = new VARIANT[func->cParams];
varlist.cArgs = func->cParams;
varlist.cNamedArgs = 0;
varlist.rgdispidNamedArgs = NULL;
varlist.rgvarg = list;
// Thanks that there won't be any out variants in HTML.
for (int i = 0; i < func->cParams; ++i) {
int listPos = func->cParams - 1 - i;
ELEMDESC *desc = &func->lprgelemdescParam[listPos];
memset(&list[listPos], 0, sizeof(list[listPos]));
RawTypeToVariant(desc->tdesc, args, &list[listPos]);
size_t varsize = VariantSize(desc->tdesc.vt);
size_t intvarsz = (varsize + sizeof(int) - 1) & (~(sizeof(int) - 1));
args += intvarsz;
*parlength += intvarsz;
}
// We needn't clear it. Caller takes ownership.
VARIANT result;
HRESULT ret = Invoke(func->memid, IID_NULL, NULL, func->invkind, &varlist, &result, NULL, NULL);
if (SUCCEEDED(ret))
ret = ConvertVariantToGivenType(typeInfo, func->elemdescFunc.tdesc, result, args);
size_t varsize = VariantSize(func->elemdescFunc.tdesc.vt);
// It should always be a pointer. It always should be counted.
size_t intvarsz = varsize ? sizeof(LPVOID) : 0;
*parlength += intvarsz;
delete[] list;
return ret;
}
UINT FakeDispatcher::FindFuncByVirtualId(int vtbId) {
if (dualType & TYPEFLAG_FDUAL)
return vtbId + DISPATCH_VTABLE;
else
return vtbId;
}
bool FakeDispatcher::HasValidTypeInfo() {
return typeInfo && typeInfo != npTypeInfo;
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetDispID(
__RPC__in BSTR bstrName,
DWORD grfdex,
__RPC__out DISPID *pid) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::InvokeEx(
__in DISPID id,
__in LCID lcid,
__in WORD wFlags,
__in DISPPARAMS *pdp,
__out_opt VARIANT *pvarRes,
__out_opt EXCEPINFO *pei,
__in_opt IServiceProvider *pspCaller) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByName(
__RPC__in BSTR bstrName,
DWORD grfdex) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByDispID(DISPID id) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberProperties(
DISPID id,
DWORD grfdexFetch,
__RPC__out DWORD *pgrfdex) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberName(
DISPID id,
__RPC__deref_out_opt BSTR *pbstrName) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNextDispID(
DWORD grfdex,
DISPID id,
__RPC__out DISPID *pid) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNameSpaceParent(
__RPC__deref_out_opt IUnknown **ppunk) {
return LogNotImplemented(target->npInstance);
}
| zzhongster-npactivex | ffactivex/FakeDispatcher.cpp | C++ | mpl11 | 14,416 |
// Copyright qiuc12@gmail.com
// This file is generated autmatically by python. DONT MODIFY IT!
#pragma once
#include <OleAuto.h>
class FakeDispatcher;
HRESULT DualProcessCommand(int commandId, FakeDispatcher *disp, ...);
extern "C" void DualProcessCommandWrap();
class FakeDispatcherBase : public IDispatch {
private:
virtual HRESULT __stdcall fv0();
virtual HRESULT __stdcall fv1();
virtual HRESULT __stdcall fv2();
virtual HRESULT __stdcall fv3();
virtual HRESULT __stdcall fv4();
virtual HRESULT __stdcall fv5();
virtual HRESULT __stdcall fv6();
virtual HRESULT __stdcall fv7();
virtual HRESULT __stdcall fv8();
virtual HRESULT __stdcall fv9();
virtual HRESULT __stdcall fv10();
virtual HRESULT __stdcall fv11();
virtual HRESULT __stdcall fv12();
virtual HRESULT __stdcall fv13();
virtual HRESULT __stdcall fv14();
virtual HRESULT __stdcall fv15();
virtual HRESULT __stdcall fv16();
virtual HRESULT __stdcall fv17();
virtual HRESULT __stdcall fv18();
virtual HRESULT __stdcall fv19();
virtual HRESULT __stdcall fv20();
virtual HRESULT __stdcall fv21();
virtual HRESULT __stdcall fv22();
virtual HRESULT __stdcall fv23();
virtual HRESULT __stdcall fv24();
virtual HRESULT __stdcall fv25();
virtual HRESULT __stdcall fv26();
virtual HRESULT __stdcall fv27();
virtual HRESULT __stdcall fv28();
virtual HRESULT __stdcall fv29();
virtual HRESULT __stdcall fv30();
virtual HRESULT __stdcall fv31();
virtual HRESULT __stdcall fv32();
virtual HRESULT __stdcall fv33();
virtual HRESULT __stdcall fv34();
virtual HRESULT __stdcall fv35();
virtual HRESULT __stdcall fv36();
virtual HRESULT __stdcall fv37();
virtual HRESULT __stdcall fv38();
virtual HRESULT __stdcall fv39();
virtual HRESULT __stdcall fv40();
virtual HRESULT __stdcall fv41();
virtual HRESULT __stdcall fv42();
virtual HRESULT __stdcall fv43();
virtual HRESULT __stdcall fv44();
virtual HRESULT __stdcall fv45();
virtual HRESULT __stdcall fv46();
virtual HRESULT __stdcall fv47();
virtual HRESULT __stdcall fv48();
virtual HRESULT __stdcall fv49();
virtual HRESULT __stdcall fv50();
virtual HRESULT __stdcall fv51();
virtual HRESULT __stdcall fv52();
virtual HRESULT __stdcall fv53();
virtual HRESULT __stdcall fv54();
virtual HRESULT __stdcall fv55();
virtual HRESULT __stdcall fv56();
virtual HRESULT __stdcall fv57();
virtual HRESULT __stdcall fv58();
virtual HRESULT __stdcall fv59();
virtual HRESULT __stdcall fv60();
virtual HRESULT __stdcall fv61();
virtual HRESULT __stdcall fv62();
virtual HRESULT __stdcall fv63();
virtual HRESULT __stdcall fv64();
virtual HRESULT __stdcall fv65();
virtual HRESULT __stdcall fv66();
virtual HRESULT __stdcall fv67();
virtual HRESULT __stdcall fv68();
virtual HRESULT __stdcall fv69();
virtual HRESULT __stdcall fv70();
virtual HRESULT __stdcall fv71();
virtual HRESULT __stdcall fv72();
virtual HRESULT __stdcall fv73();
virtual HRESULT __stdcall fv74();
virtual HRESULT __stdcall fv75();
virtual HRESULT __stdcall fv76();
virtual HRESULT __stdcall fv77();
virtual HRESULT __stdcall fv78();
virtual HRESULT __stdcall fv79();
virtual HRESULT __stdcall fv80();
virtual HRESULT __stdcall fv81();
virtual HRESULT __stdcall fv82();
virtual HRESULT __stdcall fv83();
virtual HRESULT __stdcall fv84();
virtual HRESULT __stdcall fv85();
virtual HRESULT __stdcall fv86();
virtual HRESULT __stdcall fv87();
virtual HRESULT __stdcall fv88();
virtual HRESULT __stdcall fv89();
virtual HRESULT __stdcall fv90();
virtual HRESULT __stdcall fv91();
virtual HRESULT __stdcall fv92();
virtual HRESULT __stdcall fv93();
virtual HRESULT __stdcall fv94();
virtual HRESULT __stdcall fv95();
virtual HRESULT __stdcall fv96();
virtual HRESULT __stdcall fv97();
virtual HRESULT __stdcall fv98();
virtual HRESULT __stdcall fv99();
virtual HRESULT __stdcall fv100();
virtual HRESULT __stdcall fv101();
virtual HRESULT __stdcall fv102();
virtual HRESULT __stdcall fv103();
virtual HRESULT __stdcall fv104();
virtual HRESULT __stdcall fv105();
virtual HRESULT __stdcall fv106();
virtual HRESULT __stdcall fv107();
virtual HRESULT __stdcall fv108();
virtual HRESULT __stdcall fv109();
virtual HRESULT __stdcall fv110();
virtual HRESULT __stdcall fv111();
virtual HRESULT __stdcall fv112();
virtual HRESULT __stdcall fv113();
virtual HRESULT __stdcall fv114();
virtual HRESULT __stdcall fv115();
virtual HRESULT __stdcall fv116();
virtual HRESULT __stdcall fv117();
virtual HRESULT __stdcall fv118();
virtual HRESULT __stdcall fv119();
virtual HRESULT __stdcall fv120();
virtual HRESULT __stdcall fv121();
virtual HRESULT __stdcall fv122();
virtual HRESULT __stdcall fv123();
virtual HRESULT __stdcall fv124();
virtual HRESULT __stdcall fv125();
virtual HRESULT __stdcall fv126();
virtual HRESULT __stdcall fv127();
virtual HRESULT __stdcall fv128();
virtual HRESULT __stdcall fv129();
virtual HRESULT __stdcall fv130();
virtual HRESULT __stdcall fv131();
virtual HRESULT __stdcall fv132();
virtual HRESULT __stdcall fv133();
virtual HRESULT __stdcall fv134();
virtual HRESULT __stdcall fv135();
virtual HRESULT __stdcall fv136();
virtual HRESULT __stdcall fv137();
virtual HRESULT __stdcall fv138();
virtual HRESULT __stdcall fv139();
virtual HRESULT __stdcall fv140();
virtual HRESULT __stdcall fv141();
virtual HRESULT __stdcall fv142();
virtual HRESULT __stdcall fv143();
virtual HRESULT __stdcall fv144();
virtual HRESULT __stdcall fv145();
virtual HRESULT __stdcall fv146();
virtual HRESULT __stdcall fv147();
virtual HRESULT __stdcall fv148();
virtual HRESULT __stdcall fv149();
virtual HRESULT __stdcall fv150();
virtual HRESULT __stdcall fv151();
virtual HRESULT __stdcall fv152();
virtual HRESULT __stdcall fv153();
virtual HRESULT __stdcall fv154();
virtual HRESULT __stdcall fv155();
virtual HRESULT __stdcall fv156();
virtual HRESULT __stdcall fv157();
virtual HRESULT __stdcall fv158();
virtual HRESULT __stdcall fv159();
virtual HRESULT __stdcall fv160();
virtual HRESULT __stdcall fv161();
virtual HRESULT __stdcall fv162();
virtual HRESULT __stdcall fv163();
virtual HRESULT __stdcall fv164();
virtual HRESULT __stdcall fv165();
virtual HRESULT __stdcall fv166();
virtual HRESULT __stdcall fv167();
virtual HRESULT __stdcall fv168();
virtual HRESULT __stdcall fv169();
virtual HRESULT __stdcall fv170();
virtual HRESULT __stdcall fv171();
virtual HRESULT __stdcall fv172();
virtual HRESULT __stdcall fv173();
virtual HRESULT __stdcall fv174();
virtual HRESULT __stdcall fv175();
virtual HRESULT __stdcall fv176();
virtual HRESULT __stdcall fv177();
virtual HRESULT __stdcall fv178();
virtual HRESULT __stdcall fv179();
virtual HRESULT __stdcall fv180();
virtual HRESULT __stdcall fv181();
virtual HRESULT __stdcall fv182();
virtual HRESULT __stdcall fv183();
virtual HRESULT __stdcall fv184();
virtual HRESULT __stdcall fv185();
virtual HRESULT __stdcall fv186();
virtual HRESULT __stdcall fv187();
virtual HRESULT __stdcall fv188();
virtual HRESULT __stdcall fv189();
virtual HRESULT __stdcall fv190();
virtual HRESULT __stdcall fv191();
virtual HRESULT __stdcall fv192();
virtual HRESULT __stdcall fv193();
virtual HRESULT __stdcall fv194();
virtual HRESULT __stdcall fv195();
virtual HRESULT __stdcall fv196();
virtual HRESULT __stdcall fv197();
virtual HRESULT __stdcall fv198();
virtual HRESULT __stdcall fv199();
protected:
const static int kMaxVf = 200;
};
| zzhongster-npactivex | ffactivex/FakeDispatcherBase.h | C++ | mpl11 | 7,671 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "ItemContainer.h"
CItemContainer::CItemContainer()
{
}
CItemContainer::~CItemContainer()
{
}
///////////////////////////////////////////////////////////////////////////////
// IParseDisplayName implementation
HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut)
{
// TODO
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IOleContainer implementation
HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum)
{
HRESULT hr = E_NOTIMPL;
/*
if (ppenum == NULL)
{
return E_POINTER;
}
*ppenum = NULL;
typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk;
enumunk* p = NULL;
p = new enumunk;
if(p == NULL)
{
return E_OUTOFMEMORY;
}
hr = p->Init();
if (SUCCEEDED(hr))
{
hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum);
}
if (FAILED(hRes))
{
delete p;
}
*/
return hr;
}
HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock)
{
// TODO
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleItemContainer implementation
HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject)
{
if (pszItem == NULL)
{
return E_INVALIDARG;
}
if (ppvObject == NULL)
{
return E_INVALIDARG;
}
*ppvObject = NULL;
return MK_E_NOOBJECT;
}
HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage)
{
// TODO
return MK_E_NOOBJECT;
}
HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem)
{
// TODO
return MK_E_NOOBJECT;
}
| zzhongster-npactivex | ffactivex/common/ItemContainer.cpp | C++ | mpl11 | 4,191 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLEVENTSINK_H
#define CONTROLEVENTSINK_H
#include <map>
// This class listens for events from the specified control
class CControlEventSink :
public CComObjectRootEx<CComSingleThreadModel>,
public IDispatch
{
public:
CControlEventSink();
// Current event connection point
CComPtr<IConnectionPoint> m_spEventCP;
CComPtr<ITypeInfo> m_spEventSinkTypeInfo;
DWORD m_dwEventCookie;
IID m_EventIID;
typedef std::map<DISPID, wchar_t *> EventMap;
EventMap events;
NPP instance;
protected:
virtual ~CControlEventSink();
bool m_bSubscribed;
static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw)
{
CControlEventSink *pThis = (CControlEventSink *) pv;
if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) &&
IsEqualIID(pThis->m_EventIID, riid))
{
return pThis->QueryInterface(__uuidof(IDispatch), ppv);
}
return E_NOINTERFACE;
}
public:
BEGIN_COM_MAP(CControlEventSink)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI)
END_COM_MAP()
virtual HRESULT SubscribeToEvents(IUnknown *pControl);
virtual void UnsubscribeFromEvents();
virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo);
virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr);
// IDispatch
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo);
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr);
};
typedef CComObject<CControlEventSink> CControlEventSinkInstance;
#endif | zzhongster-npactivex | ffactivex/common/ControlEventSink.h | C++ | mpl11 | 4,288 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef IOLECOMMANDIMPL_H
#define IOLECOMMANDIMPL_H
// Implementation of the IOleCommandTarget interface. The template is
// reasonably generic and reusable which is a good thing given how needlessly
// complicated this interface is. Blame Microsoft for that and not me.
//
// To use this class, derive your class from it like this:
//
// class CComMyClass : public IOleCommandTargetImpl<CComMyClass>
// {
// ... Ensure IOleCommandTarget is listed in the interface map ...
// BEGIN_COM_MAP(CComMyClass)
// COM_INTERFACE_ENTRY(IOleCommandTarget)
// // etc.
// END_COM_MAP()
// ... And then later on define the command target table ...
// BEGIN_OLECOMMAND_TABLE()
// OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page")
// OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page")
// OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode")
// END_OLECOMMAND_TABLE()
// ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ...
// HWND GetCommandTargetWindow() const
// {
// return m_hWnd;
// }
// ... Now procedures that OLECOMMAND_HANDLER calls ...
// static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
// }
//
// The command table defines which commands the object supports. Commands are
// defined by a command id and a command group plus a WM_COMMAND id or procedure,
// and a verb and short description.
//
// Notice that there are two macros for handling Ole Commands. The first,
// OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from
// GetCommandTargetWindow() (that the derived class must implement if it uses
// this macro).
//
// The second, OLECOMMAND_HANDLER calls a static handler procedure that
// conforms to the OleCommandProc typedef. The first parameter, pThis means
// the static handler has access to the methods and variables in the class
// instance.
//
// The OLECOMMAND_HANDLER macro is generally more useful when a command
// takes parameters or needs to return a result to the caller.
//
template< class T >
class IOleCommandTargetImpl : public IOleCommandTarget
{
struct OleExecData
{
const GUID *pguidCmdGroup;
DWORD nCmdID;
DWORD nCmdexecopt;
VARIANT *pvaIn;
VARIANT *pvaOut;
};
public:
typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
struct OleCommandInfo
{
ULONG nCmdID;
const GUID *pCmdGUID;
ULONG nWindowsCmdID;
OleCommandProc pfnCommandProc;
wchar_t *szVerbText;
wchar_t *szStatusText;
};
// Query the status of the specified commands (test if is it supported etc.)
virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText)
{
T* pT = static_cast<T*>(this);
if (prgCmds == NULL)
{
return E_INVALIDARG;
}
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
BOOL bCmdGroupFound = FALSE;
BOOL bTextSet = FALSE;
// Iterate through list of commands and flag them as supported/unsupported
for (ULONG nCmd = 0; nCmd < cCmds; nCmd++)
{
// Unsupported by default
prgCmds[nCmd].cmdf = 0;
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != prgCmds[nCmd].cmdID)
{
continue;
}
// Command is supported so flag it and possibly enable it
prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED;
if (pCI->nWindowsCmdID != 0)
{
prgCmds[nCmd].cmdf |= OLECMDF_ENABLED;
}
// Copy the status/verb text for the first supported command only
if (!bTextSet && pCmdText)
{
// See what text the caller wants
wchar_t *pszTextToCopy = NULL;
if (pCmdText->cmdtextf & OLECMDTEXTF_NAME)
{
pszTextToCopy = pCI->szVerbText;
}
else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS)
{
pszTextToCopy = pCI->szStatusText;
}
// Copy the text
pCmdText->cwActual = 0;
memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t));
if (pszTextToCopy)
{
// Don't exceed the provided buffer size
size_t nTextLen = wcslen(pszTextToCopy);
if (nTextLen > pCmdText->cwBuf)
{
nTextLen = pCmdText->cwBuf;
}
wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen);
pCmdText->cwActual = nTextLen;
}
bTextSet = TRUE;
}
break;
}
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return S_OK;
}
// Execute the specified command
virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut)
{
T* pT = static_cast<T*>(this);
BOOL bCmdGroupFound = FALSE;
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != nCmdID)
{
continue;
}
// Send ourselves a WM_COMMAND windows message with the associated
// identifier and exec data
OleExecData cData;
cData.pguidCmdGroup = pguidCmdGroup;
cData.nCmdID = nCmdID;
cData.nCmdexecopt = nCmdexecopt;
cData.pvaIn = pvaIn;
cData.pvaOut = pvaOut;
if (pCI->pfnCommandProc)
{
pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP)
{
HWND hwndTarget = pT->GetCommandTargetWindow();
if (hwndTarget)
{
::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData);
}
}
else
{
// Command supported but not implemented
continue;
}
return S_OK;
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return OLECMDERR_E_NOTSUPPORTED;
}
};
// Macros to be placed in any class derived from the IOleCommandTargetImpl
// class. These define what commands are exposed from the object.
#define BEGIN_OLECOMMAND_TABLE() \
OleCommandInfo *GetCommandTable() \
{ \
static OleCommandInfo s_aSupportedCommands[] = \
{
#define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \
{ id, group, cmd, NULL, verb, desc },
#define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \
{ id, group, 0, handler, verb, desc },
#define END_OLECOMMAND_TABLE() \
{ 0, &GUID_NULL, 0, NULL, NULL, NULL } \
}; \
return s_aSupportedCommands; \
};
#endif | zzhongster-npactivex | ffactivex/common/IOleCommandTargetImpl.h | C++ | mpl11 | 10,589 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
* Brent Booker
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include <Objsafe.h>
#include "ControlSite.h"
#include "PropertyBag.h"
#include "ControlSiteIPFrame.h"
class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy
{
// Test if the specified class id implements the specified category
BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists);
public:
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid);
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid);
};
BOOL
CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists)
{
bClassExists = FALSE;
// Test if there is a CLSID entry. If there isn't then obviously
// the object doesn't exist and therefore doesn't implement any category.
// In this situation, the function returns REGDB_E_CLASSNOTREG.
CRegKey key;
if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS)
{
// Must fail if we can't even open this!
return FALSE;
}
LPOLESTR szCLSID = NULL;
if (FAILED(StringFromCLSID(clsid, &szCLSID)))
{
return FALSE;
}
USES_CONVERSION;
CRegKey keyCLSID;
LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ);
CoTaskMemFree(szCLSID);
if (lResult != ERROR_SUCCESS)
{
// Class doesn't exist
return FALSE;
}
keyCLSID.Close();
// CLSID exists, so try checking what categories it implements
bClassExists = TRUE;
CComQIPtr<ICatInformation> spCatInfo;
HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo);
if (spCatInfo == NULL)
{
// Must fail if we can't open the category manager
return FALSE;
}
// See what categories the class implements
CComQIPtr<IEnumCATID> spEnumCATID;
if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID)))
{
// Can't enumerate classes in category so fail
return FALSE;
}
// Search for matching categories
BOOL bFound = FALSE;
CATID catidNext = GUID_NULL;
while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK)
{
if (::IsEqualCATID(catid, catidNext))
{
return TRUE;
}
}
return FALSE;
}
// Test if the class is safe to host
BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid)
{
return TRUE;
}
// Test if the specified class is marked safe for scripting
BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists)
{
// Test the category the object belongs to
return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists);
}
// Test if the instantiated object is safe for scripting on the specified interface
BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid)
{
if (!pObject) {
return FALSE;
}
// Ask the control if its safe for scripting
CComQIPtr<IObjectSafety> spObjectSafety = pObject;
if (!spObjectSafety)
{
return FALSE;
}
DWORD dwSupported = 0; // Supported options (mask)
DWORD dwEnabled = 0; // Enabled options
// Assume scripting via IDispatch, now we doesn't support IDispatchEx
if (SUCCEEDED(spObjectSafety->GetInterfaceSafetyOptions(
iid, &dwSupported, &dwEnabled)))
{
if (dwEnabled & dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER)
{
// Object is safe
return TRUE;
}
}
// Set it to support untrusted caller.
if(FAILED(spObjectSafety->SetInterfaceSafetyOptions(
iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER)))
{
return FALSE;
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// Constructor
CControlSite::CControlSite()
{
TRACE_METHOD(CControlSite::CControlSite);
m_hWndParent = NULL;
m_CLSID = CLSID_NULL;
m_bSetClientSiteFirst = FALSE;
m_bVisibleAtRuntime = TRUE;
memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos));
m_bInPlaceActive = FALSE;
m_bUIActive = FALSE;
m_bInPlaceLocked = FALSE;
m_bWindowless = FALSE;
m_bSupportWindowlessActivation = TRUE;
m_bSafeForScriptingObjectsOnly = FALSE;
m_pSecurityPolicy = GetDefaultControlSecurityPolicy();
// Initialise ambient properties
m_nAmbientLocale = 0;
m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT);
m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW);
m_bAmbientUserMode = true;
m_bAmbientShowHatching = true;
m_bAmbientShowGrabHandles = true;
m_bAmbientAppearance = true; // 3d
// Windowless variables
m_hDCBuffer = NULL;
m_hRgnBuffer = NULL;
m_hBMBufferOld = NULL;
m_hBMBuffer = NULL;
m_spInner = NULL;
m_needUpdateContainerSize = false;
m_currentSize.cx = m_currentSize.cy = -1;
}
// Destructor
CControlSite::~CControlSite()
{
TRACE_METHOD(CControlSite::~CControlSite);
Detach();
if (m_spInner && m_spInnerDeallocater) {
m_spInnerDeallocater(m_spInner);
}
}
// Create the specified control, optionally providing properties to initialise
// it with and a name.
HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl,
LPCWSTR szCodebase, IBindCtx *pBindContext)
{
TRACE_METHOD(CControlSite::Create);
m_CLSID = clsid;
m_ParameterList = pl;
// See if security policy will allow the control to be hosted
if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid))
{
return E_FAIL;
}
// See if object is script safe
BOOL checkForObjectSafety = FALSE;
if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly)
{
BOOL bClassExists = FALSE;
BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists);
if (!bClassExists && szCodebase)
{
// Class doesn't exist, so allow code below to fetch it
}
else if (!bIsSafe)
{
// The class is not flagged as safe for scripting, so
// we'll have to create it to ask it if its safe.
checkForObjectSafety = TRUE;
}
}
//Now Check if the control version needs to be updated.
BOOL bUpdateControlVersion = FALSE;
wchar_t *szURL = NULL;
DWORD dwFileVersionMS = 0xffffffff;
DWORD dwFileVersionLS = 0xffffffff;
if(szCodebase)
{
HKEY hk = NULL;
wchar_t wszKey[60] = L"";
wchar_t wszData[MAX_PATH];
LPWSTR pwszClsid = NULL;
DWORD dwSize = 255;
DWORD dwHandle, dwLength, dwRegReturn;
DWORD dwExistingFileVerMS = 0xffffffff;
DWORD dwExistingFileVerLS = 0xffffffff;
BOOL bFoundLocalVerInfo = FALSE;
StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid);
swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32");
if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS )
{
dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize );
RegCloseKey( hk );
}
if(dwRegReturn == ERROR_SUCCESS)
{
VS_FIXEDFILEINFO *pFileInfo;
UINT uLen;
dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle );
LPBYTE lpData = new BYTE[dwLength];
GetFileVersionInfoW(wszData, 0, dwLength, lpData );
bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen );
if(bFoundLocalVerInfo)
{
dwExistingFileVerMS = pFileInfo->dwFileVersionMS;
dwExistingFileVerLS = pFileInfo->dwFileVersionLS;
}
delete [] lpData;
}
// Test if the code base ends in #version=a,b,c,d
const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#'));
if (szHash)
{
if (wcsnicmp(szHash, L"#version=", 9) == 0)
{
int a, b, c, d;
if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4)
{
dwFileVersionMS = MAKELONG(b,a);
dwFileVersionLS = MAKELONG(d,c);
//If local version info was found compare it
if(bFoundLocalVerInfo)
{
if(dwFileVersionMS > dwExistingFileVerMS)
bUpdateControlVersion = TRUE;
if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS))
bUpdateControlVersion = TRUE;
}
}
}
szURL = _wcsdup(szCodebase);
// Terminate at the hash mark
if (szURL)
szURL[szHash - szCodebase] = wchar_t('\0');
}
else
{
szURL = _wcsdup(szCodebase);
}
}
CComPtr<IUnknown> spObject;
HRESULT hr;
//If the control needs to be updated do not call CoCreateInstance otherwise you will lock files
//and force a reboot on CoGetClassObjectFromURL
if(!bUpdateControlVersion)
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
m_bSafeForScriptingObjectsOnly = m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch));
// Drop through, success!
}
}
// Do we need to download the control?
if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion))
{
if (!szURL)
return E_OUTOFMEMORY;
CComPtr<IBindCtx> spBindContext;
CComPtr<IBindStatusCallback> spBindStatusCallback;
CComPtr<IBindStatusCallback> spOldBSC;
// Create our own bind context or use the one provided?
BOOL useInternalBSC = FALSE;
if (!pBindContext)
{
useInternalBSC = TRUE;
hr = CreateBindCtx(0, &spBindContext);
if (FAILED(hr))
{
free(szURL);
return hr;
}
spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this);
hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0);
if (FAILED(hr))
{
free(szURL);
return hr;
}
}
else
{
spBindContext = pBindContext;
}
//If the version from the CODEBASE value is greater than the installed control
//Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt
if(bUpdateControlVersion)
{
hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext,
CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER,
0, IID_IClassFactory, NULL);
}
else
{
hr = CoGetClassObjectFromURL(CLSID_NULL, szURL, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown,
NULL);
}
free(szURL);
// Handle the internal binding synchronously so the object exists
// or an error code is available when the method returns.
if (useInternalBSC)
{
if (MK_S_ASYNCHRONOUS == hr)
{
m_bBindingInProgress = TRUE;
m_hrBindResult = E_FAIL;
// Spin around waiting for binding to complete
HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
while (m_bBindingInProgress)
{
MSG msg;
// Process pending messages
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!::GetMessage(&msg, NULL, 0, 0))
{
m_bBindingInProgress = FALSE;
break;
}
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
if (!m_bBindingInProgress)
break;
// Sleep for a bit or the next msg to appear
::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS);
}
::CloseHandle(hFakeEvent);
// Set the result
hr = m_hrBindResult;
}
// Destroy the bind status callback & context
if (spBindStatusCallback)
{
RevokeBindStatusCallback(spBindContext, spBindStatusCallback);
spBindStatusCallback.Release();
spBindContext.Release();
}
}
//added to create control
if (SUCCEEDED(hr))
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
// Assume scripting via IDispatch
m_bSafeForScriptingObjectsOnly = m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch));
}
}
//EOF test code
}
if (spObject)
{
m_spObject = spObject;
CComQIPtr<IObjectWithSite> site = m_spObject;
if (site) {
site->SetSite(GetUnknown());
}
}
return hr;
}
// Attach the created control to a window and activate it
HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream)
{
TRACE_METHOD(CControlSite::Attach);
if (hwndParent == NULL)
{
NS_ASSERTION(0, "No parent hwnd");
return E_INVALIDARG;
}
m_hWndParent = hwndParent;
m_rcObjectPos = rcPos;
// Object must have been created
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
m_spIOleControl = m_spObject;
m_spIViewObject = m_spObject;
m_spIOleObject = m_spObject;
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
if (m_spIOleControl) {
m_spIOleControl->FreezeEvents(true);
}
DWORD dwMiscStatus;
m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus);
if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST)
{
m_bSetClientSiteFirst = TRUE;
}
if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME)
{
m_bVisibleAtRuntime = FALSE;
}
// Some objects like to have the client site as the first thing
// to be initialised (for ambient properties and so forth)
if (m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
// If there is a parameter list for the object and no init stream then
// create one here.
CPropertyBagInstance *pPropertyBag = NULL;
if (pInitStream == NULL && m_ParameterList.GetSize() > 0)
{
CPropertyBagInstance::CreateInstance(&pPropertyBag);
pPropertyBag->AddRef();
for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++)
{
pPropertyBag->Write(m_ParameterList.GetNameOf(i),
const_cast<VARIANT *>(m_ParameterList.GetValueOf(i)));
}
pInitStream = (IPersistPropertyBag *) pPropertyBag;
}
// Initialise the control from store if one is provided
if (pInitStream)
{
CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream;
CComQIPtr<IStream, &IID_IStream> spStream = pInitStream;
CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject;
CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject;
if (spIPersistPropertyBag && spPropertyBag)
{
spIPersistPropertyBag->Load(spPropertyBag, NULL);
}
else if (spIPersistStream && spStream)
{
spIPersistStream->Load(spStream);
}
}
else
{
// Initialise the object if possible
CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject;
if (spIPersistStreamInit)
{
spIPersistStreamInit->InitNew();
}
}
SIZEL size, sizein;
sizein.cx = m_rcObjectPos.right - m_rcObjectPos.left;
sizein.cy = m_rcObjectPos.bottom - m_rcObjectPos.top;
SetControlSize(&sizein, &size);
m_rcObjectPos.right = m_rcObjectPos.left + size.cx;
m_rcObjectPos.bottom = m_rcObjectPos.top + size.cy;
m_spIOleInPlaceObject = m_spObject;
if (m_spIOleControl) {
m_spIOleControl->FreezeEvents(false);
}
// In-place activate the object
if (m_bVisibleAtRuntime)
{
DoVerb(OLEIVERB_INPLACEACTIVATE);
}
m_spIOleInPlaceObjectWindowless = m_spObject;
// For those objects which haven't had their client site set yet,
// it's done here.
if (!m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
return S_OK;
}
// Set the control size, in pixels.
HRESULT CControlSite::SetControlSize(const LPSIZEL size, LPSIZEL out)
{
if (!size || !out) {
return E_POINTER;
}
if (!m_spIOleObject) {
return E_FAIL;
}
SIZEL szInitialHiMetric, szCustomHiMetric, szFinalHiMetric;
SIZEL szCustomPixel, szFinalPixel;
szFinalPixel = *size;
szCustomPixel = *size;
if (m_currentSize.cx == size->cx && m_currentSize.cy == size->cy) {
// Don't need to change.
return S_OK;
}
if (SUCCEEDED(m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szInitialHiMetric))) {
if (m_currentSize.cx == -1 && szCustomPixel.cx == 300 && szCustomPixel.cy == 150) {
szFinalHiMetric = szInitialHiMetric;
} else {
AtlPixelToHiMetric(&szCustomPixel, &szCustomHiMetric);
szFinalHiMetric = szCustomHiMetric;
}
}
if (SUCCEEDED(m_spIOleObject->SetExtent(DVASPECT_CONTENT, &szFinalHiMetric))) {
if (SUCCEEDED(m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szFinalHiMetric))) {
AtlHiMetricToPixel(&szFinalHiMetric, &szFinalPixel);
}
}
m_currentSize = szFinalPixel;
if (szCustomPixel.cx != szFinalPixel.cx && szCustomPixel.cy != szFinalPixel.cy) {
m_needUpdateContainerSize = true;
}
*out = szFinalPixel;
return S_OK;
}
// Unhook the control from the window and throw it all away
HRESULT CControlSite::Detach()
{
TRACE_METHOD(CControlSite::Detach);
if (m_spIOleInPlaceObjectWindowless)
{
m_spIOleInPlaceObjectWindowless.Release();
}
CComQIPtr<IObjectWithSite> site = m_spObject;
if (site) {
site->SetSite(NULL);
}
if (m_spIOleInPlaceObject)
{
m_spIOleInPlaceObject->InPlaceDeactivate();
m_spIOleInPlaceObject.Release();
}
if (m_spIOleObject)
{
m_spIOleObject->Close(OLECLOSE_NOSAVE);
m_spIOleObject->SetClientSite(NULL);
m_spIOleObject.Release();
}
m_spIViewObject.Release();
m_spObject.Release();
return S_OK;
}
// Return the IUnknown of the contained control
HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject)
{
*ppObject = NULL;
if (m_spObject)
{
m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject);
return S_OK;
} else {
return E_FAIL;
}
}
// Subscribe to an event sink on the control
HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
if (pIUnkSink == NULL || pdwCookie == NULL)
{
return E_INVALIDARG;
}
return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie);
}
// Unsubscribe event sink from the control
HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
return AtlUnadvise(m_spObject, iid, dwCookie);
}
// Draw the control
HRESULT CControlSite::Draw(HDC hdc)
{
TRACE_METHOD(CControlSite::Draw);
// Draw only when control is windowless or deactivated
if (m_spIViewObject)
{
if (m_bWindowless || !m_bInPlaceActive)
{
RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos;
m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0);
}
}
else
{
// Draw something to indicate no control is there
HBRUSH hbr = CreateSolidBrush(RGB(200,200,200));
FillRect(hdc, &m_rcObjectPos, hbr);
DeleteObject(hbr);
}
return S_OK;
}
// Execute the specified verb
HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg)
{
TRACE_METHOD(CControlSite::DoVerb);
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
// InstallAtlThunk();
return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos);
}
// Set the position on the control
HRESULT CControlSite::SetPosition(const RECT &rcPos)
{
HWND hwnd;
TRACE_METHOD(CControlSite::SetPosition);
m_rcObjectPos = rcPos;
if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd)))
{
m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos);
}
return S_OK;
}
HRESULT CControlSite::GetControlSize(LPSIZEL size){
if (m_spIOleObject) {
SIZEL szHiMetric;
HRESULT hr = m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szHiMetric);
AtlHiMetricToPixel(&szHiMetric, size);
return hr;
}
return E_FAIL;
}
void CControlSite::FireAmbientPropertyChange(DISPID id)
{
if (m_spObject)
{
CComQIPtr<IOleControl> spControl = m_spObject;
if (spControl)
{
spControl->OnAmbientPropertyChange(id);
}
}
}
void CControlSite::SetAmbientUserMode(BOOL bUserMode)
{
bool bNewMode = bUserMode ? true : false;
if (m_bAmbientUserMode != bNewMode)
{
m_bAmbientUserMode = bNewMode;
FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE);
}
}
///////////////////////////////////////////////////////////////////////////////
// CControlSiteSecurityPolicy implementation
CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy()
{
static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy;
return &defaultControlSecurityPolicy;
}
///////////////////////////////////////////////////////////////////////////////
// IDispatch implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr)
{
if (wFlags & DISPATCH_PROPERTYGET)
{
CComVariant vResult;
switch (dispIdMember)
{
case DISPID_AMBIENT_APPEARANCE:
vResult = CComVariant(m_bAmbientAppearance);
break;
case DISPID_AMBIENT_FORECOLOR:
vResult = CComVariant((long) m_clrAmbientForeColor);
break;
case DISPID_AMBIENT_BACKCOLOR:
vResult = CComVariant((long) m_clrAmbientBackColor);
break;
case DISPID_AMBIENT_LOCALEID:
vResult = CComVariant((long) m_nAmbientLocale);
break;
case DISPID_AMBIENT_USERMODE:
vResult = CComVariant(m_bAmbientUserMode);
break;
case DISPID_AMBIENT_SHOWGRABHANDLES:
vResult = CComVariant(m_bAmbientShowGrabHandles);
break;
case DISPID_AMBIENT_SHOWHATCHING:
vResult = CComVariant(m_bAmbientShowHatching);
break;
default:
return DISP_E_MEMBERNOTFOUND;
}
VariantCopy(pVarResult, &vResult);
return S_OK;
}
return E_FAIL;
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink implementation
void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed)
{
}
void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex)
{
// Redraw the control
InvalidateRect(NULL, FALSE);
}
void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk)
{
}
void STDMETHODCALLTYPE CControlSite::OnSave(void)
{
}
void STDMETHODCALLTYPE CControlSite::OnClose(void)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink2 implementation
void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSinkEx implementation
void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus)
{
}
///////////////////////////////////////////////////////////////////////////////
// IOleWindow implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd)
{
*phwnd = m_hWndParent;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleClientSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer)
{
if (!ppContainer) return E_INVALIDARG;
CComQIPtr<IOleContainer> container(this->GetUnknown());
*ppContainer = container;
if (*ppContainer)
{
(*ppContainer)->AddRef();
}
return (*ppContainer) ? S_OK : E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void)
{
m_bInPlaceActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void)
{
m_bUIActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
*lprcPosRect = m_rcObjectPos;
*lprcClipRect = m_rcObjectPos;
CControlSiteIPFrameInstance *pIPFrame = NULL;
CControlSiteIPFrameInstance::CreateInstance(&pIPFrame);
pIPFrame->AddRef();
*ppFrame = (IOleInPlaceFrame *) pIPFrame;
*ppDoc = NULL;
lpFrameInfo->fMDIApp = FALSE;
lpFrameInfo->hwndFrame = NULL;
lpFrameInfo->haccel = NULL;
lpFrameInfo->cAccelEntries = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable)
{
m_bUIActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect)
{
if (lprcPosRect == NULL)
{
return E_INVALIDARG;
}
SetPosition(m_rcObjectPos);
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteEx implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags)
{
m_bInPlaceActive = TRUE;
if (pfNoRedraw)
{
*pfNoRedraw = FALSE;
}
if (dwFlags & ACTIVATE_WINDOWLESS)
{
if (!m_bSupportWindowlessActivation)
{
return E_INVALIDARG;
}
m_bWindowless = TRUE;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void)
{
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteWindowless implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void)
{
// Allow windowless activation?
return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC)
{
if (phDC == NULL)
{
return E_INVALIDARG;
}
// Can't do nested painting
if (m_hDCBuffer != NULL)
{
return E_UNEXPECTED;
}
m_rcBuffer = m_rcObjectPos;
if (pRect != NULL)
{
m_rcBuffer = *pRect;
}
m_hBMBuffer = NULL;
m_dwBufferFlags = grfFlags;
// See if the control wants a DC that is onscreen or offscreen
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
m_hDCBuffer = CreateCompatibleDC(NULL);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy);
m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer);
SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL);
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
}
else
{
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
// Get the window DC
m_hDCBuffer = GetWindowDC(m_hWndParent);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
// Clip the control so it can't trash anywhere it isn't allowed to draw
if (!(m_dwBufferFlags & OLEDC_NODRAW))
{
m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer);
// TODO Clip out opaque areas of sites behind this one
SelectClipRgn(m_hDCBuffer, m_hRgnBuffer);
}
}
*phDC = m_hDCBuffer;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC)
{
// Release the DC
if (hDC == NULL || hDC != m_hDCBuffer)
{
return E_INVALIDARG;
}
// Test if the DC was offscreen or onscreen
if ((m_dwBufferFlags & OLEDC_OFFSCREEN) &&
!(m_dwBufferFlags & OLEDC_NODRAW))
{
// BitBlt the buffer into the control's object
SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL);
HDC hdc = GetWindowDC(m_hWndParent);
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY);
::ReleaseDC(m_hWndParent, hdc);
}
else
{
// TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one
}
// Clean up settings ready for next drawing
if (m_hRgnBuffer)
{
SelectClipRgn(m_hDCBuffer, NULL);
DeleteObject(m_hRgnBuffer);
m_hRgnBuffer = NULL;
}
SelectObject(m_hDCBuffer, m_hBMBufferOld);
if (m_hBMBuffer)
{
DeleteObject(m_hBMBuffer);
m_hBMBuffer = NULL;
}
// Delete the DC
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
::DeleteDC(m_hDCBuffer);
}
else
{
::ReleaseDC(m_hWndParent, m_hDCBuffer);
}
m_hDCBuffer = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase)
{
// Clip the rectangle against the object's size and invalidate it
RECT rcI = { 0, 0, 0, 0 };
if (pRect == NULL)
{
rcI = m_rcObjectPos;
}
else
{
IntersectRect(&rcI, &m_rcObjectPos, pRect);
}
::InvalidateRect(m_hWndParent, &rcI, fErase);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase)
{
if (hRGN == NULL)
{
::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase);
}
else
{
// Clip the region with the object's bounding area
HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos);
if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR)
{
::InvalidateRgn(m_hWndParent, hrgnClip, fErase);
}
DeleteObject(hrgnClip);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc)
{
if (prc == NULL)
{
return E_INVALIDARG;
}
// Clip the rectangle against the object position
RECT rcI = { 0, 0, 0, 0 };
IntersectRect(&rcI, &m_rcObjectPos, prc);
*prc = rcI;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult)
{
if (plResult == NULL)
{
return E_INVALIDARG;
}
// Pass the message to the windowless control
if (m_bWindowless && m_spIOleInPlaceObjectWindowless)
{
return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult);
}
else if (m_spIOleInPlaceObject) {
HWND wnd;
if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd)))
SendMessage(wnd, msg, wParam, lParam);
}
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleControlSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock)
{
m_bInPlaceLocked = fLock;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags)
{
HRESULT hr = S_OK;
if (pPtlHimetric == NULL)
{
return E_INVALIDARG;
}
if (pPtfContainer == NULL)
{
return E_INVALIDARG;
}
HDC hdc = ::GetDC(m_hWndParent);
::SetMapMode(hdc, MM_HIMETRIC);
POINT rgptConvert[2];
rgptConvert[0].x = 0;
rgptConvert[0].y = 0;
if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER)
{
rgptConvert[1].x = pPtlHimetric->x;
rgptConvert[1].y = pPtlHimetric->y;
::LPtoDP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x);
pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y);
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtfContainer->x = (float)rgptConvert[1].x;
pPtfContainer->y = (float)rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC)
{
rgptConvert[1].x = (int)(pPtfContainer->x);
rgptConvert[1].y = (int)(pPtfContainer->y);
::DPtoLP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x;
pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y;
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtlHimetric->x = rgptConvert[1].x;
pPtlHimetric->y = rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else
{
hr = E_INVALIDARG;
}
::ReleaseDC(m_hWndParent, hdc);
return hr;
}
HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IBindStatusCallback implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved,
IBinding __RPC_FAR *pib)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress,
ULONG ulProgressMax,
ULONG ulStatusCode,
LPCWSTR szStatusText)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError)
{
m_bBindingInProgress = FALSE;
m_hrBindResult = hresult;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF,
BINDINFO __RPC_FAR *pbindInfo)
{
*pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE |
BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE;
pbindInfo->cbSize = sizeof(BINDINFO);
pbindInfo->szExtraInfo = NULL;
memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM));
pbindInfo->grfBindInfoF = 0;
pbindInfo->dwBindVerb = 0;
pbindInfo->szCustomVerb = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF,
DWORD dwSize,
FORMATETC __RPC_FAR *pformatetc,
STGMEDIUM __RPC_FAR *pstgmed)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid,
IUnknown __RPC_FAR *punk)
{
return S_OK;
}
// IWindowForBindingUI
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(
/* [in] */ REFGUID rguidReason,
/* [out] */ HWND *phwnd)
{
*phwnd = NULL;
return S_OK;
}
| zzhongster-npactivex | ffactivex/common/ControlSite.cpp | C++ | mpl11 | 44,576 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef PROPERTYLIST_H
#define PROPERTYLIST_H
// A simple array class for managing name/value pairs typically fed to controls
// during initialization by IPersistPropertyBag
class PropertyList
{
struct Property {
BSTR bstrName;
VARIANT vValue;
} *mProperties;
unsigned long mListSize;
unsigned long mMaxListSize;
bool EnsureMoreSpace()
{
// Ensure enough space exists to accomodate a new item
const unsigned long kGrowBy = 10;
if (!mProperties)
{
mProperties = (Property *) malloc(sizeof(Property) * kGrowBy);
if (!mProperties)
return false;
mMaxListSize = kGrowBy;
}
else if (mListSize == mMaxListSize)
{
Property *pNewProperties;
pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy));
if (!pNewProperties)
return false;
mProperties = pNewProperties;
mMaxListSize += kGrowBy;
}
return true;
}
public:
PropertyList() :
mProperties(NULL),
mListSize(0),
mMaxListSize(0)
{
}
~PropertyList()
{
}
void Clear()
{
if (mProperties)
{
for (unsigned long i = 0; i < mListSize; i++)
{
SysFreeString(mProperties[i].bstrName); // Safe even if NULL
VariantClear(&mProperties[i].vValue);
}
free(mProperties);
mProperties = NULL;
}
mListSize = 0;
mMaxListSize = 0;
}
unsigned long GetSize() const
{
return mListSize;
}
const BSTR GetNameOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return mProperties[nIndex].bstrName;
}
const VARIANT *GetValueOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return &mProperties[nIndex].vValue;
}
bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName)
return false;
for (unsigned long i = 0; i < GetSize(); i++)
{
// Case insensitive
if (wcsicmp(mProperties[i].bstrName, bstrName) == 0)
{
return SUCCEEDED(
VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue)));
}
}
return AddNamedProperty(bstrName, vValue);
}
bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName || !EnsureMoreSpace())
return false;
Property *pProp = &mProperties[mListSize];
pProp->bstrName = ::SysAllocString(bstrName);
if (!pProp->bstrName)
{
return false;
}
VariantInit(&pProp->vValue);
if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue))))
{
SysFreeString(pProp->bstrName);
return false;
}
mListSize++;
return true;
}
};
#endif | zzhongster-npactivex | ffactivex/common/PropertyList.h | C++ | mpl11 | 5,004 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "../npactivex.h"
#include "ControlEventSink.h"
CControlEventSink::CControlEventSink() :
m_dwEventCookie(0),
m_bSubscribed(false),
m_EventIID(GUID_NULL),
events()
{
}
CControlEventSink::~CControlEventSink()
{
UnsubscribeFromEvents();
}
BOOL
CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo)
{
iid = GUID_NULL;
if (!pControl)
{
return FALSE;
}
// IProvideClassInfo2 way is easiest
// CComQIPtr<IProvideClassInfo2> classInfo2 = pControl;
// if (classInfo2)
// {
// classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid);
// if (!::IsEqualIID(iid, GUID_NULL))
// {
// return TRUE;
// }
// }
// Yuck, the hard way
CComQIPtr<IProvideClassInfo> classInfo = pControl;
if (!classInfo)
{
np_log(instance, 0, "no classInfo");
return FALSE;
}
// Search the class type information for the default source interface
// which is the outgoing event sink.
CComPtr<ITypeInfo> classTypeInfo;
classInfo->GetClassInfo(&classTypeInfo);
if (!classTypeInfo)
{
np_log(instance, 0, "noclassTypeinfo");
return FALSE;
}
TYPEATTR *classAttr = NULL;
if (FAILED(classTypeInfo->GetTypeAttr(&classAttr)))
{
np_log(instance, 0, "noclassTypeinfo->GetTypeAttr");
return FALSE;
}
INT implFlags = 0;
for (UINT i = 0; i < classAttr->cImplTypes; i++)
{
// Search for the interface with the [default, source] attr
if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) &&
implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE))
{
CComPtr<ITypeInfo> eventSinkTypeInfo;
HREFTYPE hRefType;
if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) &&
SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo)))
{
TYPEATTR *eventSinkAttr = NULL;
if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr)))
{
iid = eventSinkAttr->guid;
if (typeInfo)
{
*typeInfo = eventSinkTypeInfo.p;
(*typeInfo)->AddRef();
}
eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr);
}
}
break;
}
}
classTypeInfo->ReleaseTypeAttr(classAttr);
return (!::IsEqualIID(iid, GUID_NULL));
}
void CControlEventSink::UnsubscribeFromEvents()
{
if (m_bSubscribed)
{
DWORD tmpCookie = m_dwEventCookie;
m_dwEventCookie = 0;
m_bSubscribed = false;
// Unsubscribe and reset - This seems to complete release and destroy us...
m_spEventCP->Unadvise(tmpCookie);
// Unadvise handles the Release
m_spEventCP.Release();
} else {
m_spEventCP.Release();
}
}
HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl)
{
if (!pControl)
{
np_log(instance, 0, "not valid control");
return E_INVALIDARG;
}
// Throw away any existing connections
UnsubscribeFromEvents();
// Grab the outgoing event sink IID which will be used to subscribe
// to events via the connection point container.
IID iidEventSink;
CComPtr<ITypeInfo> typeInfo;
if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo))
{
np_log(instance, 0, "Can't get event sink iid");
return E_FAIL;
}
// Get the connection point
CComQIPtr<IConnectionPointContainer> ccp = pControl;
CComPtr<IConnectionPoint> cp;
if (!ccp)
{
np_log(instance, 0, "not valid ccp");
return E_FAIL;
}
// Custom IID
m_EventIID = iidEventSink;
DWORD dwCookie = 0;/*
CComPtr<IEnumConnectionPoints> e;
ccp->EnumConnectionPoints(&e);
e->Next(1, &cp, &dwCookie);*/
if (FAILED(ccp->FindConnectionPoint(m_EventIID, &cp)))
{
np_log(instance, 0, "failed to find connection point");
return E_FAIL;
}
if (FAILED(cp->Advise(this, &dwCookie)))
{
np_log(instance, 0, "failed to advise");
return E_FAIL;
}
m_bSubscribed = true;
m_spEventCP = cp;
m_dwEventCookie = dwCookie;
m_spEventSinkTypeInfo = typeInfo;
return S_OK;
}
HRESULT
CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
USES_CONVERSION;
if (DISPATCH_METHOD != wFlags) {
// any other reason to call us?!
return S_FALSE;
}
EventMap::iterator cur = events.find(dispIdMember);
if (events.end() != cur) {
// invoke this event handler
NPVariant result;
NPVariant *args = NULL;
if (pDispParams->cArgs > 0) {
args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant));
if (!args) {
return S_FALSE;
}
for (unsigned int i = 0; i < pDispParams->cArgs; ++i) {
// convert the arguments in reverse order
Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance);
}
}
NPObject *globalObj = NULL;
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second));
bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result);
NPNFuncs.releaseobject(globalObj);
for (unsigned int i = 0; i < pDispParams->cArgs; ++i) {
// convert the arguments
if (args[i].type == NPVariantType_String) {
// was allocated earlier by Variant2NPVar
NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters);
}
}
if (!success) {
return S_FALSE;
}
if (pVarResult) {
// set the result
NPVar2Variant(&result, pVarResult, instance);
}
NPNFuncs.releasevariantvalue(&result);
}
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IDispatch implementation
HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr)
{
return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
| zzhongster-npactivex | ffactivex/common/ControlEventSink.cpp | C++ | mpl11 | 9,136 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "stdafx.h"
#include "ControlSiteIPFrame.h"
CControlSiteIPFrame::CControlSiteIPFrame()
{
m_hwndFrame = NULL;
}
CControlSiteIPFrame::~CControlSiteIPFrame()
{
}
///////////////////////////////////////////////////////////////////////////////
// IOleWindow implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd)
{
if (phwnd == NULL)
{
return E_INVALIDARG;
}
*phwnd = m_hwndFrame;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceUIWindow implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder)
{
return INPLACE_E_NOTOOLSPACE;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths)
{
return INPLACE_E_NOTOOLSPACE;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceFrame implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID)
{
return E_NOTIMPL;
}
| zzhongster-npactivex | ffactivex/common/ControlSiteIPFrame.cpp | C++ | mpl11 | 4,105 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ITEMCONTAINER_H
#define ITEMCONTAINER_H
// typedef std::map<tstring, CIUnkPtr> CNamedObjectList;
// Class for managing a list of named objects.
class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>,
public IOleItemContainer
{
// CNamedObjectList m_cNamedObjectList;
public:
CItemContainer();
virtual ~CItemContainer();
BEGIN_COM_MAP(CItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer)
END_COM_MAP()
// IParseDisplayName implementation
virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut);
// IOleContainer implementation
virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum);
virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock);
// IOleItemContainer implementation
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage);
virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem);
};
typedef CComObject<CItemContainer> CItemContainerInstance;
#endif | zzhongster-npactivex | ffactivex/common/ItemContainer.h | C++ | mpl11 | 3,631 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLSITE_H
#define CONTROLSITE_H
#include "IOleCommandTargetImpl.h"
#include "PropertyList.h"
// Temoporarily removed by bug 200680. Stops controls misbehaving and calling
// windowless methods when they shouldn't.
// COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \
// Class that defines the control's security policy with regards to
// what controls it hosts etc.
class CControlSiteSecurityPolicy
{
public:
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0;
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0;
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0;
};
//
// Class for hosting an ActiveX control
//
// This class supports both windowed and windowless classes. The normal
// steps to hosting a control are this:
//
// CControlSiteInstance *pSite = NULL;
// CControlSiteInstance::CreateInstance(&pSite);
// pSite->AddRef();
// pSite->Create(clsidControlToCreate);
// pSite->Attach(hwndParentWindow, rcPosition);
//
// Where propertyList is a named list of values to initialise the new object
// with, hwndParentWindow is the window in which the control is being created,
// and rcPosition is the position in window coordinates where the control will
// be rendered.
//
// Destruction is this:
//
// pSite->Detach();
// pSite->Release();
// pSite = NULL;
class CControlSite : public CComObjectRootEx<CComSingleThreadModel>,
public IOleClientSite,
public IOleInPlaceSiteWindowless,
public IOleControlSite,
public IAdviseSinkEx,
public IDispatch,
public IOleCommandTargetImpl<CControlSite>,
public IBindStatusCallback,
public IWindowForBindingUI
{
private:
// Site management values
// Handle to parent window
HWND m_hWndParent;
// Position of the site and the contained object
RECT m_rcObjectPos;
// Flag indicating if client site should be set early or late
unsigned m_bSetClientSiteFirst:1;
// Flag indicating whether control is visible or not
unsigned m_bVisibleAtRuntime:1;
// Flag indicating if control is in-place active
unsigned m_bInPlaceActive:1;
// Flag indicating if control is UI active
unsigned m_bUIActive:1;
// Flag indicating if control is in-place locked and cannot be deactivated
unsigned m_bInPlaceLocked:1;
// Flag indicating if the site allows windowless controls
unsigned m_bSupportWindowlessActivation:1;
// Flag indicating if control is windowless (after being created)
unsigned m_bWindowless:1;
// Flag indicating if only safely scriptable controls are allowed
unsigned m_bSafeForScriptingObjectsOnly:1;
// Return the default security policy object
static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy();
friend class CAxHost;
protected:
// Pointers to object interfaces
// Raw pointer to the object
CComPtr<IUnknown> m_spObject;
// Pointer to objects IViewObject interface
CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject;
// Pointer to object's IOleObject interface
CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject;
// Pointer to object's IOleInPlaceObject interface
CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject;
// Pointer to object's IOleInPlaceObjectWindowless interface
CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless;
// CLSID of the control
CComQIPtr<IOleControl> m_spIOleControl;
CLSID m_CLSID;
// Parameter list
PropertyList m_ParameterList;
// Pointer to the security policy
CControlSiteSecurityPolicy *m_pSecurityPolicy;
// Document and Service provider
IUnknown *m_spInner;
void (*m_spInnerDeallocater)(IUnknown *m_spInner);
// Binding variables
// Flag indicating whether binding is in progress
unsigned m_bBindingInProgress;
// Result from the binding operation
HRESULT m_hrBindResult;
// Double buffer drawing variables used for windowless controls
// Area of buffer
RECT m_rcBuffer;
// Bitmap to buffer
HBITMAP m_hBMBuffer;
// Bitmap to buffer
HBITMAP m_hBMBufferOld;
// Device context
HDC m_hDCBuffer;
// Clipping area of site
HRGN m_hRgnBuffer;
// Flags indicating how the buffer was painted
DWORD m_dwBufferFlags;
// The last control size passed by GetExtent
SIZEL m_currentSize;
// Ambient properties
// Locale ID
LCID m_nAmbientLocale;
// Foreground colour
COLORREF m_clrAmbientForeColor;
// Background colour
COLORREF m_clrAmbientBackColor;
// Flag indicating if control should hatch itself
bool m_bAmbientShowHatching:1;
// Flag indicating if control should have grab handles
bool m_bAmbientShowGrabHandles:1;
// Flag indicating if control is in edit/user mode
bool m_bAmbientUserMode:1;
// Flag indicating if control has a 3d border or not
bool m_bAmbientAppearance:1;
// Flag indicating if the size passed in is different from the control.
bool m_needUpdateContainerSize:1;
protected:
// Notifies the attached control of a change to an ambient property
virtual void FireAmbientPropertyChange(DISPID id);
public:
// Construction and destruction
// Constructor
CControlSite();
// Destructor
virtual ~CControlSite();
BEGIN_COM_MAP(CControlSite)
COM_INTERFACE_ENTRY(IOleWindow)
COM_INTERFACE_ENTRY(IOleClientSite)
COM_INTERFACE_ENTRY(IOleInPlaceSite)
COM_INTERFACE_ENTRY(IOleInPlaceSiteWindowless)
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless)
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless)
COM_INTERFACE_ENTRY(IOleControlSite)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx)
COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx)
COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx)
COM_INTERFACE_ENTRY(IOleCommandTarget)
COM_INTERFACE_ENTRY(IBindStatusCallback)
COM_INTERFACE_ENTRY(IWindowForBindingUI)
COM_INTERFACE_ENTRY_AGGREGATE_BLIND(m_spInner)
END_COM_MAP()
BEGIN_OLECOMMAND_TABLE()
END_OLECOMMAND_TABLE()
// Returns the window used when processing ole commands
HWND GetCommandTargetWindow()
{
return NULL; // TODO
}
// Object creation and management functions
// Creates and initialises an object
virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(),
LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL);
// Attaches the object to the site
virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL);
// Detaches the object from the site
virtual HRESULT Detach();
// Returns the IUnknown pointer for the object
virtual HRESULT GetControlUnknown(IUnknown **ppObject);
// Sets the bounding rectangle for the object
virtual HRESULT SetPosition(const RECT &rcPos);
// Draws the object using the provided DC
virtual HRESULT Draw(HDC hdc);
// Performs the specified action on the object
virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL);
// Sets an advise sink up for changes to the object
virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie);
// Removes an advise sink
virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie);
// Get the control size, in pixels.
virtual HRESULT GetControlSize(LPSIZEL size);
// Set the control size, in pixels.
virtual HRESULT SetControlSize(const LPSIZEL size, LPSIZEL out);
void SetInnerWindow(IUnknown *unk, void (*Deleter)(IUnknown *unk)) {
m_spInner = unk;
m_spInnerDeallocater = Deleter;
}
// Set the security policy object. Ownership of this object remains with the caller and the security
// policy object is meant to exist for as long as it is set here.
virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy)
{
m_pSecurityPolicy = pSecurityPolicy;
}
virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const
{
return m_pSecurityPolicy;
}
// Methods to set ambient properties
virtual void SetAmbientUserMode(BOOL bUser);
// Inline helper methods
// Returns the object's CLSID
virtual const CLSID &GetObjectCLSID() const
{
return m_CLSID;
}
// Tests if the object is valid or not
virtual BOOL IsObjectValid() const
{
return (m_spObject) ? TRUE : FALSE;
}
// Returns the parent window to this one
virtual HWND GetParentWindow() const
{
return m_hWndParent;
}
// Returns the inplace active state of the object
virtual BOOL IsInPlaceActive() const
{
return m_bInPlaceActive;
}
// Returns the m_bVisibleAtRuntime
virtual BOOL IsVisibleAtRuntime() const
{
return m_bVisibleAtRuntime;
}
// Return and reset m_needUpdateContainerSize
virtual BOOL CheckAndResetNeedUpdateContainerSize() {
BOOL ret = m_needUpdateContainerSize;
m_needUpdateContainerSize = false;
return ret;
}
// IDispatch
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo);
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr);
// IAdviseSink implementation
virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed);
virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex);
virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk);
virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void);
virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void);
// IAdviseSink2
virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk);
// IAdviseSinkEx implementation
virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus);
// IOleWindow implementation
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd);
virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode);
// IOleClientSite implementation
virtual HRESULT STDMETHODCALLTYPE SaveObject(void);
virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk);
virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer);
virtual HRESULT STDMETHODCALLTYPE ShowObject(void);
virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow);
virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void);
// IOleInPlaceSite implementation
virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void);
virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void);
virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo);
virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant);
virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void);
virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void);
virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void);
virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect);
// IOleInPlaceSiteEx implementation
virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw);
virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void);
// IOleInPlaceSiteWindowless implementation
virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void);
virtual HRESULT STDMETHODCALLTYPE GetCapture(void);
virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture);
virtual HRESULT STDMETHODCALLTYPE GetFocus(void);
virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus);
virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC);
virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC);
virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase);
virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase);
virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip);
virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc);
virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult);
// IOleControlSite implementation
virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void);
virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock);
virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp);
virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags);
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers);
virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus);
virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void);
// IBindStatusCallback
virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib);
virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority);
virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved);
virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText);
virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed);
virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk);
// IWindowForBindingUI
virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd);
};
#endif | zzhongster-npactivex | ffactivex/common/ControlSite.h | C++ | mpl11 | 18,106 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "PropertyBag.h"
CPropertyBag::CPropertyBag()
{
}
CPropertyBag::~CPropertyBag()
{
}
///////////////////////////////////////////////////////////////////////////////
// IPropertyBag implementation
HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog)
{
if (pszPropName == NULL)
{
return E_INVALIDARG;
}
if (pVar == NULL)
{
return E_INVALIDARG;
}
VARTYPE vt = pVar->vt;
VariantInit(pVar);
for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++)
{
if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0)
{
const VARIANT *pvSrc = m_PropertyList.GetValueOf(i);
if (!pvSrc)
{
return E_FAIL;
}
CComVariant vNew;
HRESULT hr = (vt == VT_EMPTY) ?
vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc);
if (FAILED(hr))
{
return E_FAIL;
}
// Copy the new value
vNew.Detach(pVar);
return S_OK;
}
}
// Property does not exist in the bag
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar)
{
if (pszPropName == NULL)
{
return E_INVALIDARG;
}
if (pVar == NULL)
{
return E_INVALIDARG;
}
CComBSTR bstrName(pszPropName);
m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar);
return S_OK;
}
| zzhongster-npactivex | ffactivex/common/PropertyBag.cpp | C++ | mpl11 | 3,426 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLSITEIPFRAME_H
#define CONTROLSITEIPFRAME_H
class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>,
public IOleInPlaceFrame
{
public:
CControlSiteIPFrame();
virtual ~CControlSiteIPFrame();
HWND m_hwndFrame;
BEGIN_COM_MAP(CControlSiteIPFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY(IOleInPlaceFrame)
END_COM_MAP()
// IOleWindow
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd);
virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode);
// IOleInPlaceUIWindow implementation
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName);
// IOleInPlaceFrame implementation
virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject);
virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText);
virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable);
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID);
};
typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance;
#endif | zzhongster-npactivex | ffactivex/common/ControlSiteIPFrame.h | C++ | mpl11 | 3,891 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef PROPERTYBAG_H
#define PROPERTYBAG_H
#include "PropertyList.h"
// Object wrapper for property list. This class can be set up with a
// list of properties and used to initialise a control with them
class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>,
public IPropertyBag
{
// List of properties in the bag
PropertyList m_PropertyList;
public:
// Constructor
CPropertyBag();
// Destructor
virtual ~CPropertyBag();
BEGIN_COM_MAP(CPropertyBag)
COM_INTERFACE_ENTRY(IPropertyBag)
END_COM_MAP()
// IPropertyBag methods
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog);
virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar);
};
typedef CComObject<CPropertyBag> CPropertyBagInstance;
#endif | zzhongster-npactivex | ffactivex/common/PropertyBag.h | C++ | mpl11 | 2,769 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
#if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_)
#define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// under MSVC shut off copious warnings about debug symbol too long
#ifdef _MSC_VER
#pragma warning( disable: 4786 )
#endif
//#include "jstypes.h"
//#include "prtypes.h"
// Mozilla headers
//#include "jscompat.h"
//#include "prthread.h"
//#include "prprf.h"
//#include "nsID.h"
//#include "nsIComponentManager.h"
//#include "nsIServiceManager.h"
//#include "nsStringAPI.h"
//#include "nsCOMPtr.h"
//#include "nsComponentManagerUtils.h"
//#include "nsServiceManagerUtils.h"
//#include "nsIDocument.h"
//#include "nsIDocumentObserver.h"
//#include "nsVoidArray.h"
//#include "nsIDOMNode.h"
//#include "nsIDOMNodeList.h"
//#include "nsIDOMDocument.h"
//#include "nsIDOMDocumentType.h"
//#include "nsIDOMElement.h"
//#undef _WIN32_WINNT
//#define _WIN32_WINNT 0x0400
#define _ATL_APARTMENT_THREADED
//#define _ATL_STATIC_REGISTRY
// #define _ATL_DEBUG_INTERFACES
// ATL headers
// The ATL headers that come with the platform SDK have bad for scoping
#if _MSC_VER >= 1400
#pragma conform(forScope, push, atlhack, off)
#endif
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
extern CComModule _Module;
#include <atlcom.h>
#include <atlctl.h>
#if _MSC_VER >= 1400
#pragma conform(forScope, pop, atlhack)
#endif
#include <mshtml.h>
#include <mshtmhst.h>
#include <docobj.h>
//#include <winsock2.h>
#include <comdef.h>
#include <vector>
#include <list>
#include <string>
// New winsock2.h doesn't define this anymore
typedef long int32;
#define NS_SCRIPTABLE
#include "nscore.h"
#include "npapi.h"
//#include "npupp.h"
#include "npfunctions.h"
#include "nsID.h"
#include <npruntime.h>
#include "../variants.h"
#include "PropertyList.h"
#include "PropertyBag.h"
#include "ItemContainer.h"
#include "ControlSite.h"
#include "ControlSiteIPFrame.h"
#include "ControlEventSink.h"
extern NPNetscapeFuncs NPNFuncs;
// Turn off warnings about debug symbols for templates being too long
#pragma warning(disable : 4786)
#define TRACE_METHOD(fn) \
{ \
ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \
}
#define TRACE_METHOD_ARGS(fn, pattern, args) \
{ \
ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \
}
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#define NS_ASSERTION(x, y)
#endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
| zzhongster-npactivex | ffactivex/common/StdAfx.h | C++ | mpl11 | 4,966 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
// TODO: reference additional headers your program requires here
| zzhongster-npactivex | ffactivex/stdafx.h | C | mpl11 | 2,250 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <npapi.h>
#include <npruntime.h>
#include <map>
#include <vector>
#include "Host.h"
class CAxHost;
class ObjectManager : public CHost
{
public:
ObjectManager(NPP npp2);
~ObjectManager(void);
static NPClass npClass;
CHost* GetPreviousObject(NPP npp);
static ObjectManager* GetManager(NPP npp);
virtual ScriptBase *CreateScriptableObject();
void RetainOwnership(CAxHost *obj);
bool RequestObjectOwnership(NPP newNpp, CAxHost* obj);
private:
struct ScriptManager : public ScriptBase {
ScriptManager(NPP npp) : ScriptBase(npp) {
}
};
std::vector<CHost*> hosts;
std::vector<CHost*> dynamic_hosts;
static NPObject* _Allocate(NPP npp, NPClass *aClass) {
ScriptManager *obj = new ScriptManager(npp);
return obj;
}
static bool Invoke(NPObject *obj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result);
static bool HasMethod(NPObject *obj, NPIdentifier name);
static bool HasProperty(NPObject *obj, NPIdentifier name);
static bool GetProperty(NPObject *obj, NPIdentifier name, NPVariant *value);
static bool SetProperty(NPObject *obj, NPIdentifier name, const NPVariant *value);
static void Deallocate(NPObject *obj);
};
| zzhongster-npactivex | ffactivex/ObjectManager.h | C++ | mpl11 | 2,783 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <npruntime.h>
#include <npapi.h>
#include "npactivex.h"
class NPVariantProxy : public NPVariant
{
public:
NPVariantProxy() {
VOID_TO_NPVARIANT(*this);
}
~NPVariantProxy() {
NPNFuncs.releasevariantvalue(this);
}
};
class NPObjectProxy {
private:
NPObject *object;
public:
NPObjectProxy() {
object = NULL;
}
NPObjectProxy(NPObject *obj) {
object = obj;
}
void reset() {
if (object)
NPNFuncs.releaseobject(object);
object = NULL;
}
~NPObjectProxy() {
reset();
}
operator NPObject*&() {
return object;
}
NPObjectProxy& operator =(NPObject* obj) {
reset();
object = obj;
return *this;
}
}; | zzhongster-npactivex | ffactivex/objectProxy.h | C++ | mpl11 | 2,216 |
<html>
<head>
<script>
function stringHash(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
ch = str.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function compute() {
result.innerText = stringHash(text.value);
}
</script>
</head>
<body>
<textarea id="text" style="width: 700px; height:500px; margin:auto"></textarea>
<div id="result"></div>
<button onclick="compute()">Compute</button>
</body>
</html>
| zzhongster-npactivex | web/stringhash.html | HTML | mpl11 | 672 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta>
<style>
.line {
clear: both;
margin: 4px 0px;
}
.item {
margin: 4px 3px;
float: left;
}
</style>
<script>
var link = "https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn"
var text = '在Chrome中直接使用各类网银、快播等ActiveX控件,无需使用IE Tab等IE内核插件!数万用户的实践验证!点击链接下载';
</script>
</head>
<body>
<div id="header" style="height:100px">
</div>
<div class="line">
<!-- Place this tag where you want the +1 button to render -->
<g:plusone annotation="inline" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn"></g:plusone>
<!-- Place this render call where appropriate -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</div>
<div class="line">
<div class="item">
<script type="text/javascript" charset="utf-8">
(function(){
var _w = 106 , _h = 24;
var param = {
url:link,
type:'5',
count:'', /**是否显示分享数,1显示(可选)*/
appkey:'', /**您申请的应用appkey,显示分享来源(可选)*/
title:text,
pic:'', /**分享图片的路径(可选)*/
ralateUid:'2356524070', /**关联用户的UID,分享微博会@该用户(可选)*/
language:'zh_cn', /**设置语言,zh_cn|zh_tw(可选)*/
rnd:new Date().valueOf()
}
var temp = [];
for( var p in param ){
temp.push(p + '=' + encodeURIComponent( param[p] || '' ) )
}
document.write('<iframe allowTransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?' + temp.join('&') + '" width="'+ _w+'" height="'+_h+'"></iframe>')
})()
</script>
</div>
<div class="item">
<a name="xn_share" type="button_count_right" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn/">分享到人人</a><script src="http://static.connect.renren.com/js/share.js" type="text/javascript"></script></div>
<div class="item">
<a href="javascript:void(0)" onclick="postToWb();return false;" class="tmblog"><img src="http://v.t.qq.com/share/images/s/b24.png" border="0" alt="转播到腾讯微博" ></a><script type="text/javascript">
function postToWb(){
var _url = encodeURIComponent(link);
var _assname = encodeURI("");//你注册的帐号,不是昵称
var _appkey = encodeURI("");//你从腾讯获得的appkey
var _pic = encodeURI('');//(例如:var _pic='图片url1|图片url2|图片url3....)
var _t = '';//标题和描述信息
var metainfo = document.getElementsByTagName("meta");
for(var metai = 0;metai < metainfo.length;metai++){
if((new RegExp('description','gi')).test(metainfo[metai].getAttribute("name"))){
_t = metainfo[metai].attributes["content"].value;
}
}
_t = text;
if(_t.length > 120){
_t= _t.substr(0,117)+'...';
}
_t = encodeURI(_t);
var _u = 'http://share.v.t.qq.com/index.php?c=share&a=index&url='+_url+'&appkey='+_appkey+'&pic='+_pic+'&assname='+_assname+'&title='+_t;
window.open( _u,'', 'width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' );
}
</script>
</div>
</div>
<div id="footer" style="height:100px;clear:both">
</div>
</body>
</html>
| zzhongster-npactivex | web/share.html | HTML | mpl11 | 3,718 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html("");
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text)
this.input.append(o);
}
}
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
| zzhongster-npactivex | web/listtypes.js | JavaScript | mpl11 | 3,295 |
.itemline.newline:not(.editing) {
display:none;
}
.list {
width: 100%;
height: 520px;
}
div[property=title] {
width: 200px
}
div[property=type] {
width: 60px
}
div[property=value] {
width: 240px
}
div[property=enabled] {
width: 60px
}
div[property=userAgent] {
width: 70px
}
div[property=script] {
width: 200px
}
div[property=description] {
width: 300px
}
div[property=url] {
width: 300px
}
div[property=compute], div[property=compute] button{
width: 80px
}
div[property=checksum] {
width: 80px
}
[property=status] button {
width: 70px;
}
#scriptEditor {
display: block;
width: 100%;
height: 361px;
}
| zzhongster-npactivex | web/editor.css | CSS | mpl11 | 694 |
.list {
width: 800px;
height: 400px;
font-family: Arial, sans-serif;
overflow-x: hidden;
border: 3px solid #0D5995;
background-color: #0D5995;
padding: 1px;
padding-top: 10px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
.listscroll {
overflow-x: scroll;
overflow-y: scroll;
background-color: white;
}
.listitems {
display: inline-block;
}
.listvalue, .header {
display: inline-block;
width: 80px;
margin: 0px 6px;
}
.headers {
background-color: transparent;
position: relative;
white-space: nowrap;
display: inline-block;
color:white;
padding: 5px 0px;
}
.header{
white-space: normal;
}
.itemline {
height: 32px;
}
.itemline:nth-child(odd) {
background-color: white;
}
.itemline:nth-child(even) {
background-color: whitesmoke;
}
.itemline.selected {
background-color: #aaa;
}
.itemline:hover {
background-color: #bbcee9
}
.itemline.error,
.itemline.error:hover {
background-color: salmon;
}
.itemline > div {
white-space: nowrap;
padding: 4px 0px 0 0;
}
.itemline.editing > div{
padding: 3px 0px 0 0;
}
.valdisp, .valinput {
background-color: transparent;
width: 100%;
display: block;
}
.listvalue {
overflow-x: hidden;
}
.itemline.editing .listvalue:not(.readonly) .valdisp {
display: none;
}
.valdisp {
font-size: 13px;
}
.itemline:not(.editing) .valinput,
.listvalue.readonly .valinput {
display: none;
}
.itemline :focus {
outline: none;
}
.valinput {
border:1px solid #aaa;
background-color: white;
padding: 3px;
margin: 0;
}
.itemline .valinput:focus {
outline-color: rgba(0, 128, 256, 0.5);
outline: 5px auto rgba(0, 128, 256, 0.5);
}
| zzhongster-npactivex | web/list.css | CSS | mpl11 | 1,865 |
<html>
<head>
<link rel="stylesheet" type="text/css" href="list.css" />
<link rel="stylesheet" type="text/css" href="editor.css" />
<link type="text/css" href="jquery-ui-1.8.17.custom.css" rel="stylesheet" />
<script src="jquery-1.7.min.js"></script>
<script src="jquery-ui-1.8.17.custom.min.js"></script>
<script src="list.js"></script>
<script src="listtypes.js"></script>
<script src="editor.js"></script>
</head>
<body>
<div id="tabs">
<ul>
<li><a href="#rules">Rules</a></li>
<li><a href="#scripts">Scripts</a></li>
<li><a href="#issues">Issues</a></li>
</ul>
<div id="rules">
<div id="ruleTable">
</div>
<div>
<button id="addRule">Add</button>
<button id="deleteRule">Delete</button>
<button class="doSave">Save</button>
</div>
</div>
<div id="scripts">
<div id="scriptTable">
</div>
<div>
<button id="addScript">Add</button>
<button id="deleteScript">Delete</button>
<button id="compute_checkSum">Compute all checksums</button>
<button class="doSave">Save</button>
</div>
</div>
<div id="issues">
<div id="issueTable">
</div>
<div>
<button id="addIssue">Add</button>
<button id="deleteIssue">Delete</button>
<button class="doSave">Save</button>
</div>
</div>
</div>
<div id="scriptDialog">
<textarea id="scriptEditor"></textarea>
</div>
</body>
</html>
| zzhongster-npactivex | web/editor.html | HTML | mpl11 | 1,638 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var baseDir = '/setting/';
var rules = [];
var scripts = [];
var issues = [];
var dirty = false;
function stringHash(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
ch = str.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function setScriptAutoComplete(e) {
var last = /[^\s]*$/;
var obj = $('input', e.target);
$(obj).bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
scriptItems, last.exec(request.term)[0]));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
this.value = this.value.replace(last, ui.item.value);
return false;
}
});
}
var ruleProps = [ {
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Name",
property: "title",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Keyword",
property: "keyword",
type: "input"
}, {
header: "testURL",
property: "testUrl",
type: "input"
}, {
header: "UserAgent",
property: "userAgent",
type: "select",
option: "static",
options: [
{value: "", text: "Chrome"},
{value: "ie9", text: "MSIE9"},
{value: "ie8", text: "MSIE8"},
{value: "ie7", text: "MSIE7"},
{value: "ff7win", text: "Firefox 7 Windows"},
{value: "ff7mac", text: "Firefox 7 Mac"},
{value: "ip5", text: "iPhone"},
{value: "ipad5", text: "iPad"}
]
}, {
header: "Helper Script",
property: "script",
type: "input",
events: {
create: setScriptAutoComplete
}
}];
var currentScript = -1;
function showScript(id) {
var url = baseDir + scripts[id].url;
currentScript = id;
$(scriptEditor).val('');
$.ajax(url, {
success: function(value) {
origScript = value;
$(scriptEditor).val(value);
}
});
$('#scriptDialog').dialog('open');
}
function saveToFile(file, value) {
$.ajax(baseDir + 'upload.php', {
type: "POST",
data: {
file: file,
data: value
}
});
}
var checksumComputing = 0;
function computeScriptChecksum(id) {
scripts[id].checksum = "computing";
++checksumComputing;
scriptList.updateLine(scriptList.lines[id]);
$.ajax(baseDir + scripts[id].url, {
complete: function() {
--checksumComputing;
},
dataType: "text",
success: function(value, status, xhr) {
scripts[id].checksum = stringHash(value);
scriptList.updateLine(scriptList.lines[id]);
}
});
}
var origScript;
function saveScript(id) {
var value = $('#scriptEditor').val();
if (value == origScript) {
return;
}
var file = scripts[id].url;
++scripts[id].version;
scriptList.updateLine(scriptList.getLine(id));
saveToFile(file, value);
dirty = true;
}
var scriptProps = [{
property: "identifier",
header: "Identifier",
type: "input"
}, {
property: "url",
header: "URL",
type: "input"
}, {
property: "version",
header: "Version",
type: "input"
}, {
property: "context",
header: "Context",
type: "select",
option: "static",
options: [
{value: "page", text: "Page"},
{value: "extension", text: "Extension"}
]
}, {
property: "show",
header: "Show",
type: "button",
events: {
create: function(e) {
$('button', this).text('Show');
},
command: function(e) {
showScript(Number(e.data.line.attr('row')), true);
}
}
}, {
property: "checksum",
header: "checksum",
type: "input",
events: {
"create": function(e) {
$(this).addClass('readonly');
}
}
}, {
property: "compute",
header: "Checksum",
type: "button",
events: {
create: function(e) {
$('button', this).text('Recompute');
},
command: function(e) {
computeScriptChecksum(Number(e.data.line.attr('row')));
}
}
}];
var issueProps = [{
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Description",
property: "description",
type: "input"
}, {
header: "IssueId",
property: "issueId",
type: "input"
}, {
header: "url",
property: "url",
type: "input"
}];
// The JSON formatter is from http://joncom.be/code/javascript-json-formatter/
function FormatJSON(oData, sIndent) {
function RealTypeOf(v) {
if (typeof(v) == "object") {
if (v === null) return "null";
if (v.constructor == Array) return "array";
if (v.constructor == Date) return "date";
if (v.constructor == RegExp) return "regex";
return "object";
}
return typeof(v);
}
if (arguments.length < 2) {
var sIndent = "";
}
var sIndentStyle = " ";
var sDataType = RealTypeOf(oData);
// open object
if (sDataType == "array") {
if (oData.length == 0) {
return "[]";
}
var sHTML = "[";
} else {
var iCount = 0;
$.each(oData, function() {
iCount++;
return;
});
if (iCount == 0) { // object is empty
return "{}";
}
var sHTML = "{";
}
// loop through items
var iCount = 0;
$.each(oData, function(sKey, vValue) {
if (iCount > 0) {
sHTML += ",";
}
if (sDataType == "array") {
sHTML += ("\n" + sIndent + sIndentStyle);
} else {
sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": ");
}
// display relevant data type
switch (RealTypeOf(vValue)) {
case "array":
case "object":
sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
break;
case "boolean":
case "number":
sHTML += vValue.toString();
break;
case "null":
sHTML += "null";
break;
case "string":
sHTML += ("\"" + vValue + "\"");
break;
default:
sHTML += JSON.stringify(vValue);
}
// loop
iCount++;
});
// close object
if (sDataType == "array") {
sHTML += ("\n" + sIndent + "]");
} else {
sHTML += ("\n" + sIndent + "}");
}
// return
return sHTML;
}
function loadRules(value) {
rules = [];
for (var i in value) {
rules.push(value[i]);
}
ruleList.refresh();
freezeIdentifier(ruleList);
}
function loadIssues(value) {
issues = [];
for (var i in value) {
issues.push(value[i]);
}
issueList.refresh();
freezeIdentifier(issueList);
}
function loadScripts(value) {
scripts = [];
for (var i in value) {
scripts.push(value[i]);
}
scriptList.refresh();
freezeIdentifier(scriptList);
updateScriptItems();
}
function serialize(list) {
var obj = {};
for (var i = 0; i < list.length; ++i) {
obj[list[i].identifier] = list[i];
}
return FormatJSON(obj);
}
function save() {
saveToFile('setting.json', serialize(rules));
saveToFile('scripts.json', serialize(scripts));
saveToFile('issues.json', serialize(issues));
dirty= false;
freezeIdentifier(ruleList);
freezeIdentifier(scriptList);
}
function reload() {
$.ajax(baseDir + 'setting.json', {
success: loadRules
});
$.ajax(baseDir + 'scripts.json', {
success: loadScripts
});
$.ajax(baseDir + 'issues.json', {
success: loadIssues
});
dirty = false;
}
function freezeIdentifier(list) {
$('.itemline:not(.newline) div[property=identifier]', list.contents)
.addClass('readonly');
}
var scriptList, ruleList, issueList;
var scriptItems = [];
function updateScriptItems() {
scriptItems = [];
for (var i = 0; i < scripts.length; ++i) {
scriptItems.push(scripts[i].identifier);
}
}
$(document).ready(function() {
window.onbeforeunload=function() {
if (dirty) {
return 'Page not saved. Continue?';
}
}
$('#addRule').click(function() {
ruleList.editNewLine();
}).button();
$('#deleteRule').click(function() {
ruleList.remove(ruleList.selectedLine);
}).button();
$('#addScript').click(function() {
scriptList.editNewLine();
}).button();
$('#deleteScript').click(function() {
scriptList.remove(scriptList.selectedLine);
}).button();
$('#compute_checkSum').click(function() {
for (var i = 0; i < scripts.length; ++i) {
computeScriptChecksum(i);
}
}).button();
$('#addIssue').click(function() {
issueList.editNewLine();
}).button();
$('#deleteIssue').click(function() {
issueList.remove(issueList.selectedLine);
}).button();
$('.doSave').each(function() {
$(this).click(save).button();
});
$('#tabs').tabs();
$('#scriptDialog').dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
"Save": function() {
saveScript(currentScript);
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
$.ajaxSetup({
cache: false
});
scriptList = new List({
props: scriptProps,
main: $('#scriptTable'),
getItems: function() {return scripts;}
});
$(scriptList).bind('updated', function() {
dirty = true;
updateScriptItems();
});
scriptList.init();
ruleList = new List({
props: ruleProps,
main: $('#ruleTable'),
getItems: function() {return rules;}
});
ruleList.init();
$(ruleList).bind('updated', function() {
dirty = true;
});
issueList = new List({
props: issueProps,
main: $('#issueTable'),
getItems: function() {return issues;}
});
issueList.init();
$(issueList).bind('updated', function() {
dirty = true;
});
reload();
});
| zzhongster-npactivex | web/editor.js | JavaScript | mpl11 | 10,902 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
};
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1,
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay : function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with(list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if(!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with(this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == "number") {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
| zzhongster-npactivex | web/list.js | JavaScript | mpl11 | 11,700 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
/**
* A JDBC driver which is a facade that delegates to one or more real underlying
* JDBC drivers. The driver will spy on any other JDBC driver that is loaded,
* simply by prepending <code>jdbc:log4</code> to the normal jdbc driver URL
* used by any other JDBC driver. The driver, by default, also loads several
* well known drivers at class load time, so that this driver can be
* "dropped in" to any Java program that uses these drivers without making any
* code changes.
* <p/>
* The well known driver classes that are loaded are:
* <p/>
* <p/>
* <code>
* <ul>
* <li>oracle.jdbc.driver.OracleDriver</li>
* <li>com.sybase.jdbc2.jdbc.SybDriver</li>
* <li>net.sourceforge.jtds.jdbc.Driver</li>
* <li>com.microsoft.jdbc.sqlserver.SQLServerDriver</li>
* <li>com.microsoft.sqlserver.jdbc.SQLServerDriver</li>
* <li>weblogic.jdbc.sqlserver.SQLServerDriver</li>
* <li>com.informix.jdbc.IfxDriver</li>
* <li>org.apache.derby.jdbc.ClientDriver</li>
* <li>org.apache.derby.jdbc.EmbeddedDriver</li>
* <li>com.mysql.jdbc.Driver</li>
* <li>org.postgresql.Driver</li>
* <li>org.hsqldb.jdbcDriver</li>
* <li>org.h2.Driver</li>
* </ul>
* </code>
* <p/>
* <p/>
* Additional drivers can be set via a property: <b>log4jdbc.drivers</b>
* This can be either a single driver class name or a list of comma separated
* driver class names.
* <p/>
* The autoloading behavior can be disabled by setting a property:
* <b>log4jdbc.auto.load.popular.drivers</b> to false. If that is done, then
* the only drivers that log4jdbc will attempt to load are the ones specified
* in <b>log4jdbc.drivers</b>.
* <p/>
* If any of the above driver classes cannot be loaded, the driver continues on
* without failing.
* <p/>
* Note that the <code>getMajorVersion</code>, <code>getMinorVersion</code> and
* <code>jdbcCompliant</code> method calls attempt to delegate to the last
* underlying driver requested through any other call that accepts a JDBC URL.
* <p/>
* This can cause unexpected behavior in certain circumstances. For example,
* if one of these 3 methods is called before any underlying driver has been
* established, then they will return default values that might not be correct
* in all situations. Similarly, if this spy driver is used to spy on more than
* one underlying driver concurrently, the values returned by these 3 method
* calls may change depending on what the last underlying driver used was at the
* time. This will not usually be a problem, since the driver is retrieved by
* it's URL from the DriverManager in the first place (thus establishing an
* underlying real driver), and in most applications their is only one database.
*
* @author Arthur Blake
*/
public class DriverSpy implements Driver
{
/**
* The last actual, underlying driver that was requested via a URL.
*/
private Driver lastUnderlyingDriverRequested;
/**
* Maps driver class names to RdbmsSpecifics objects for each kind of
* database.
*/
private static Map rdbmsSpecifics;
static final SpyLogDelegator log = SpyLogFactory.getSpyLogDelegator();
/**
* Optional package prefix to use for finding application generating point of
* SQL.
*/
static String DebugStackPrefix;
/**
* Flag to indicate debug trace info should be from the calling application
* point of view (true if DebugStackPrefix is set.)
*/
static boolean TraceFromApplication;
/**
* Flag to indicate if a warning should be shown if SQL takes more than
* SqlTimingWarnThresholdMsec milliseconds to run. See below.
*/
static boolean SqlTimingWarnThresholdEnabled;
/**
* An amount of time in milliseconds for which SQL that executed taking this
* long or more to run shall cause a warning message to be generated on the
* SQL timing logger.
*
* This threshold will <i>ONLY</i> be used if SqlTimingWarnThresholdEnabled
* is true.
*/
static long SqlTimingWarnThresholdMsec;
/**
* Flag to indicate if an error should be shown if SQL takes more than
* SqlTimingErrorThresholdMsec milliseconds to run. See below.
*/
static boolean SqlTimingErrorThresholdEnabled;
/**
* An amount of time in milliseconds for which SQL that executed taking this
* long or more to run shall cause an error message to be generated on the
* SQL timing logger.
*
* This threshold will <i>ONLY</i> be used if SqlTimingErrorThresholdEnabled
* is true.
*/
static long SqlTimingErrorThresholdMsec;
/**
* When dumping boolean values, dump them as 'true' or 'false'.
* If this option is not set, they will be dumped as 1 or 0 as many
* databases do not have a boolean type, and this allows for more
* portable sql dumping.
*/
static boolean DumpBooleanAsTrueFalse;
/**
* When dumping SQL, if this is greater than 0, than the SQL will
* be broken up into lines that are no longer than this value.
*/
static int DumpSqlMaxLineLength;
/**
* If this is true, display a special warning in the log along with the SQL
* when the application uses a Statement (as opposed to a PreparedStatement.)
* Using Statements for frequently used SQL can sometimes result in
* performance and/or security problems.
*/
static boolean StatementUsageWarn;
/**
* Options to more finely control which types of SQL statements will
* be dumped, when dumping SQL.
* By default all 5 of the following will be true. If any one is set to
* false, then that particular type of SQL will not be dumped.
*/
static boolean DumpSqlSelect;
static boolean DumpSqlInsert;
static boolean DumpSqlUpdate;
static boolean DumpSqlDelete;
static boolean DumpSqlCreate;
// only true if one ore more of the above 4 flags are false.
static boolean DumpSqlFilteringOn;
/**
* If true, add a semilcolon to the end of each SQL dump.
*/
static boolean DumpSqlAddSemicolon;
/**
* If dumping in debug mode, dump the full stack trace.
* This will result in a VERY voluminous output, but can be very useful
* under some circumstances.
*/
static boolean DumpFullDebugStackTrace;
/**
* Attempt to Automatically load a set of popular JDBC drivers?
*/
static boolean AutoLoadPopularDrivers;
/**
* Trim SQL before logging it?
*/
static boolean TrimSql;
/**
* Remove extra Lines in the SQL that consist of only white space?
* Only when 2 or more lines in a row like this occur, will the extra lines (beyond 1)
* be removed.
*/
static boolean TrimExtraBlankLinesInSql;
/**
* Coldfusion typically calls PreparedStatement.getGeneratedKeys() after
* every SQL update call, even if it's not warranted. This typically produces
* an exception that is ignored by Coldfusion. If this flag is true, then
* any exception generated by this method is also ignored by log4jdbc.
*/
static boolean SuppressGetGeneratedKeysException;
/**
* Get a Long option from a property and
* log a debug message about this.
*
* @param props Properties to get option from.
* @param propName property key.
*
* @return the value of that property key, converted
* to a Long. Or null if not defined or is invalid.
*/
private static Long getLongOption(Properties props, String propName)
{
String propValue = props.getProperty(propName);
Long longPropValue = null;
if (propValue == null)
{
log.debug("x " + propName + " is not defined");
}
else
{
try
{
longPropValue = new Long(Long.parseLong(propValue));
log.debug(" " + propName + " = " + longPropValue);
}
catch (NumberFormatException n)
{
log.debug("x " + propName + " \"" + propValue +
"\" is not a valid number");
}
}
return longPropValue;
}
/**
* Get a Long option from a property and
* log a debug message about this.
*
* @param props Properties to get option from.
* @param propName property key.
*
* @return the value of that property key, converted
* to a Long. Or null if not defined or is invalid.
*/
private static Long getLongOption(Properties props, String propName,
long defaultValue)
{
String propValue = props.getProperty(propName);
Long longPropValue;
if (propValue == null)
{
log.debug("x " + propName + " is not defined (using default of " +
defaultValue +")");
longPropValue = new Long(defaultValue);
}
else
{
try
{
longPropValue = new Long(Long.parseLong(propValue));
log.debug(" " + propName + " = " + longPropValue);
}
catch (NumberFormatException n)
{
log.debug("x " + propName + " \"" + propValue +
"\" is not a valid number (using default of " + defaultValue +")");
longPropValue = new Long(defaultValue);
}
}
return longPropValue;
}
/**
* Get a String option from a property and
* log a debug message about this.
*
* @param props Properties to get option from.
* @param propName property key.
* @return the value of that property key.
*/
private static String getStringOption(Properties props, String propName)
{
String propValue = props.getProperty(propName);
if (propValue == null || propValue.length()==0)
{
log.debug("x " + propName + " is not defined");
propValue = null; // force to null, even if empty String
}
else
{
log.debug(" " + propName + " = " + propValue);
}
return propValue;
}
/**
* Get a boolean option from a property and
* log a debug message about this.
*
* @param props Properties to get option from.
* @param propName property name to get.
* @param defaultValue default value to use if undefined.
*
* @return boolean value found in property, or defaultValue if no property
* found.
*/
private static boolean getBooleanOption(Properties props, String propName,
boolean defaultValue)
{
String propValue = props.getProperty(propName);
boolean val;
if (propValue == null)
{
log.debug("x " + propName + " is not defined (using default value " +
defaultValue + ")");
return defaultValue;
}
else
{
propValue = propValue.trim().toLowerCase();
if (propValue.length() == 0)
{
val = defaultValue;
}
else
{
val= "true".equals(propValue) ||
"yes".equals(propValue) || "on".equals(propValue);
}
}
log.debug(" " + propName + " = " + val);
return val;
}
static
{
log.debug("... log4jdbc initializing ...");
InputStream propStream =
DriverSpy.class.getResourceAsStream("/log4jdbc.properties");
Properties props = new Properties(System.getProperties());
if (propStream != null)
{
try
{
props.load(propStream);
}
catch (IOException e)
{
log.debug("ERROR! io exception loading " +
"log4jdbc.properties from classpath: " + e.getMessage());
}
finally
{
try
{
propStream.close();
}
catch (IOException e)
{
log.debug("ERROR! io exception closing property file stream: " +
e.getMessage());
}
}
log.debug(" log4jdbc.properties loaded from classpath");
}
else
{
log.debug(" log4jdbc.properties not found on classpath");
}
// look for additional driver specified in properties
DebugStackPrefix = getStringOption(props, "log4jdbc.debug.stack.prefix");
TraceFromApplication = DebugStackPrefix != null;
Long thresh = getLongOption(props, "log4jdbc.sqltiming.warn.threshold");
SqlTimingWarnThresholdEnabled = (thresh != null);
if (SqlTimingWarnThresholdEnabled)
{
SqlTimingWarnThresholdMsec = thresh.longValue();
}
thresh = getLongOption(props, "log4jdbc.sqltiming.error.threshold");
SqlTimingErrorThresholdEnabled = (thresh != null);
if (SqlTimingErrorThresholdEnabled)
{
SqlTimingErrorThresholdMsec = thresh.longValue();
}
DumpBooleanAsTrueFalse =
getBooleanOption(props, "log4jdbc.dump.booleanastruefalse",false);
DumpSqlMaxLineLength = getLongOption(props,
"log4jdbc.dump.sql.maxlinelength", 90L).intValue();
DumpFullDebugStackTrace =
getBooleanOption(props, "log4jdbc.dump.fulldebugstacktrace",false);
StatementUsageWarn =
getBooleanOption(props, "log4jdbc.statement.warn",false);
DumpSqlSelect = getBooleanOption(props, "log4jdbc.dump.sql.select",true);
DumpSqlInsert = getBooleanOption(props, "log4jdbc.dump.sql.insert",true);
DumpSqlUpdate = getBooleanOption(props, "log4jdbc.dump.sql.update",true);
DumpSqlDelete = getBooleanOption(props, "log4jdbc.dump.sql.delete",true);
DumpSqlCreate = getBooleanOption(props, "log4jdbc.dump.sql.create",true);
DumpSqlFilteringOn = !(DumpSqlSelect && DumpSqlInsert && DumpSqlUpdate &&
DumpSqlDelete && DumpSqlCreate);
DumpSqlAddSemicolon = getBooleanOption(props,
"log4jdbc.dump.sql.addsemicolon", false);
AutoLoadPopularDrivers = getBooleanOption(props,
"log4jdbc.auto.load.popular.drivers", true);
TrimSql = getBooleanOption(props, "log4jdbc.trim.sql", true);
TrimExtraBlankLinesInSql = getBooleanOption(props, "log4jdbc.trim.sql.extrablanklines", true);
SuppressGetGeneratedKeysException =
getBooleanOption(props, "log4jdbc.suppress.generated.keys.exception",
false);
// The Set of drivers that the log4jdbc driver will preload at instantiation
// time. The driver can spy on any driver type, it's just a little bit
// easier to configure log4jdbc if it's one of these types!
Set subDrivers = new TreeSet();
if (AutoLoadPopularDrivers)
{
subDrivers.add("oracle.jdbc.driver.OracleDriver");
subDrivers.add("oracle.jdbc.OracleDriver");
subDrivers.add("com.sybase.jdbc2.jdbc.SybDriver");
subDrivers.add("net.sourceforge.jtds.jdbc.Driver");
// MS driver for Sql Server 2000
subDrivers.add("com.microsoft.jdbc.sqlserver.SQLServerDriver");
// MS driver for Sql Server 2005
subDrivers.add("com.microsoft.sqlserver.jdbc.SQLServerDriver");
subDrivers.add("weblogic.jdbc.sqlserver.SQLServerDriver");
subDrivers.add("com.informix.jdbc.IfxDriver");
subDrivers.add("org.apache.derby.jdbc.ClientDriver");
subDrivers.add("org.apache.derby.jdbc.EmbeddedDriver");
subDrivers.add("com.mysql.jdbc.Driver");
subDrivers.add("org.postgresql.Driver");
subDrivers.add("org.hsqldb.jdbcDriver");
subDrivers.add("org.h2.Driver");
}
// look for additional driver specified in properties
String moreDrivers = getStringOption(props, "log4jdbc.drivers");
if (moreDrivers != null)
{
String[] moreDriversArr = moreDrivers.split(",");
for (int i = 0; i < moreDriversArr.length; i++)
{
subDrivers.add(moreDriversArr[i]);
log.debug (" will look for specific driver " + moreDriversArr[i]);
}
}
try
{
DriverManager.registerDriver(new DriverSpy());
}
catch (SQLException s)
{
// this exception should never be thrown, JDBC just defines it
// for completeness
throw (RuntimeException) new RuntimeException
("could not register log4jdbc driver!").initCause(s);
}
// instantiate all the supported drivers and remove
// those not found
String driverClass;
for (Iterator i = subDrivers.iterator(); i.hasNext();)
{
driverClass = (String) i.next();
try
{
Class.forName(driverClass);
log.debug(" FOUND DRIVER " + driverClass);
}
catch (Throwable c)
{
i.remove();
}
}
if (subDrivers.size() == 0)
{
log.debug("WARNING! " +
"log4jdbc couldn't find any underlying jdbc drivers.");
}
SqlServerRdbmsSpecifics sqlServer = new SqlServerRdbmsSpecifics();
OracleRdbmsSpecifics oracle = new OracleRdbmsSpecifics();
MySqlRdbmsSpecifics mySql = new MySqlRdbmsSpecifics();
/** create lookup Map for specific rdbms formatters */
rdbmsSpecifics = new HashMap();
rdbmsSpecifics.put("oracle.jdbc.driver.OracleDriver", oracle);
rdbmsSpecifics.put("oracle.jdbc.OracleDriver", oracle);
rdbmsSpecifics.put("net.sourceforge.jtds.jdbc.Driver", sqlServer);
rdbmsSpecifics.put("com.microsoft.jdbc.sqlserver.SQLServerDriver",
sqlServer);
rdbmsSpecifics.put("weblogic.jdbc.sqlserver.SQLServerDriver", sqlServer);
rdbmsSpecifics.put("com.mysql.jdbc.Driver", mySql);
log.debug("... log4jdbc initialized! ...");
}
static RdbmsSpecifics defaultRdbmsSpecifics = new RdbmsSpecifics();
/**
* Get the RdbmsSpecifics object for a given Connection.
*
* @param conn JDBC connection to get RdbmsSpecifics for.
* @return RdbmsSpecifics for the given connection.
*/
static RdbmsSpecifics getRdbmsSpecifics(Connection conn)
{
String driverName = "";
try
{
DatabaseMetaData dbm = conn.getMetaData();
driverName = dbm.getDriverName();
}
catch (SQLException s)
{
// silently fail
}
log.debug("driver name is " + driverName);
RdbmsSpecifics r = (RdbmsSpecifics) rdbmsSpecifics.get(driverName);
if (r == null)
{
return defaultRdbmsSpecifics;
}
else
{
return r;
}
}
/**
* Default constructor.
*/
public DriverSpy()
{
}
/**
* Get the major version of the driver. This call will be delegated to the
* underlying driver that is being spied upon (if there is no underlying
* driver found, then 1 will be returned.)
*
* @return the major version of the JDBC driver.
*/
public int getMajorVersion()
{
if (lastUnderlyingDriverRequested == null)
{
return 1;
}
else
{
return lastUnderlyingDriverRequested.getMajorVersion();
}
}
/**
* Get the minor version of the driver. This call will be delegated to the
* underlying driver that is being spied upon (if there is no underlying
* driver found, then 0 will be returned.)
*
* @return the minor version of the JDBC driver.
*/
public int getMinorVersion()
{
if (lastUnderlyingDriverRequested == null)
{
return 0;
}
else
{
return lastUnderlyingDriverRequested.getMinorVersion();
}
}
/**
* Report whether the underlying driver is JDBC compliant. If there is no
* underlying driver, false will be returned, because the driver cannot
* actually do any work without an underlying driver.
*
* @return <code>true</code> if the underlying driver is JDBC Compliant;
* <code>false</code> otherwise.
*/
public boolean jdbcCompliant()
{
return lastUnderlyingDriverRequested != null &&
lastUnderlyingDriverRequested.jdbcCompliant();
}
/**
* Returns true if this is a <code>jdbc:log4</code> URL and if the URL is for
* an underlying driver that this DriverSpy can spy on.
*
* @param url JDBC URL.
*
* @return true if this Driver can handle the URL.
*
* @throws SQLException if a database access error occurs
*/
public boolean acceptsURL(String url) throws SQLException
{
Driver d = getUnderlyingDriver(url);
if (d != null)
{
lastUnderlyingDriverRequested = d;
return true;
}
else
{
return false;
}
}
/**
* Given a <code>jdbc:log4</code> type URL, find the underlying real driver
* that accepts the URL.
*
* @param url JDBC connection URL.
*
* @return Underlying driver for the given URL. Null is returned if the URL is
* not a <code>jdbc:log4</code> type URL or there is no underlying
* driver that accepts the URL.
*
* @throws SQLException if a database access error occurs.
*/
private Driver getUnderlyingDriver(String url) throws SQLException
{
if (url.startsWith("jdbc:log4"))
{
url = url.substring(9);
Enumeration e = DriverManager.getDrivers();
Driver d;
while (e.hasMoreElements())
{
d = (Driver) e.nextElement();
if (d.acceptsURL(url))
{
return d;
}
}
}
return null;
}
/**
* Get a Connection to the database from the underlying driver that this
* DriverSpy is spying on. If logging is not enabled, an actual Connection to
* the database returned. If logging is enabled, a ConnectionSpy object which
* wraps the real Connection is returned.
*
* @param url JDBC connection URL
* .
* @param info a list of arbitrary string tag/value pairs as
* connection arguments. Normally at least a "user" and
* "password" property should be included.
*
* @return a <code>Connection</code> object that represents a
* connection to the URL.
*
* @throws SQLException if a database access error occurs
*/
public Connection connect(String url, Properties info) throws SQLException
{
Driver d = getUnderlyingDriver(url);
if (d == null)
{
return null;
}
// get actual URL that the real driver expects
// (strip off "jdbc:log4" from url)
url = url.substring(9);
lastUnderlyingDriverRequested = d;
Connection c = d.connect(url, info);
if (c == null)
{
throw new SQLException("invalid or unknown driver url: " + url);
}
if (log.isJdbcLoggingEnabled())
{
ConnectionSpy cspy = new ConnectionSpy(c);
RdbmsSpecifics r = null;
String dclass = d.getClass().getName();
if (dclass != null && dclass.length() > 0)
{
r = (RdbmsSpecifics) rdbmsSpecifics.get(dclass);
}
if (r == null)
{
r = defaultRdbmsSpecifics;
}
cspy.setRdbmsSpecifics(r);
return cspy;
}
else
{
return c;
}
}
/**
* Gets information about the possible properties for the underlying driver.
*
* @param url the URL of the database to which to connect
*
* @param info a proposed list of tag/value pairs that will be sent on
* connect open
* @return an array of <code>DriverPropertyInfo</code> objects describing
* possible properties. This array may be an empty array if no
* properties are required.
*
* @throws SQLException if a database access error occurs
*/
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
throws SQLException
{
Driver d = getUnderlyingDriver(url);
if (d == null)
{
return new DriverPropertyInfo[0];
}
lastUnderlyingDriverRequested = d;
return d.getPropertyInfo(url, info);
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/DriverSpy.java | Java | asf20 | 24,684 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.sql.SQLClientInfoException;
import java.sql.SQLXML;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Wraps a JDBC Connection and reports method calls, returns and exceptions.
*
* This version is for jdbc 4.
*
* @author Arthur Blake
*/
public class ConnectionSpy implements Connection, Spy
{
private Connection realConnection;
/**
* Get the real underlying Connection that this ConnectionSpy wraps.
*
* @return the real underlying Connection.
*/
public Connection getRealConnection()
{
return realConnection;
}
private SpyLogDelegator log;
private final Integer connectionNumber;
private static int lastConnectionNumber = 0;
/**
* Contains a Mapping of connectionNumber to currently open ConnectionSpy
* objects.
*/
private static final Map connectionTracker = new HashMap();
/**
* Get a dump of how many connections are open, and which connection numbers
* are open.
*
* @return an open connection dump.
*/
public static String getOpenConnectionsDump()
{
StringBuffer dump = new StringBuffer();
int size;
Integer[] keysArr;
synchronized (connectionTracker)
{
size = connectionTracker.size();
if (size==0)
{
return "open connections: none";
}
Set keys = connectionTracker.keySet();
keysArr = (Integer[]) keys.toArray(new Integer[keys.size()]);
}
Arrays.sort(keysArr);
dump.append("open connections: ");
for (int i=0; i < keysArr.length; i++)
{
dump.append(keysArr[i]);
dump.append(" ");
}
dump.append("(");
dump.append(size);
dump.append(")");
return dump.toString();
}
/**
* Create a new ConnectionSpy that wraps a given Connection.
*
* @param realConnection "real" Connection that this ConnectionSpy wraps.
*/
public ConnectionSpy(Connection realConnection)
{
this(realConnection, DriverSpy.defaultRdbmsSpecifics);
}
/**
* Create a new ConnectionSpy that wraps a given Connection.
*
* @param realConnection "real" Connection that this ConnectionSpy wraps.
* @param rdbmsSpecifics the RdbmsSpecifics object for formatting logging appropriate for the Rdbms used.
*/
public ConnectionSpy(Connection realConnection, RdbmsSpecifics rdbmsSpecifics)
{
if (rdbmsSpecifics == null)
{
rdbmsSpecifics = DriverSpy.defaultRdbmsSpecifics;
}
setRdbmsSpecifics(rdbmsSpecifics);
if (realConnection == null)
{
throw new IllegalArgumentException("Must pass in a non null real Connection");
}
this.realConnection = realConnection;
log = SpyLogFactory.getSpyLogDelegator();
synchronized (connectionTracker)
{
connectionNumber = new Integer(++lastConnectionNumber);
connectionTracker.put(connectionNumber, this);
}
log.connectionOpened(this);
reportReturn("new Connection");
}
private RdbmsSpecifics rdbmsSpecifics;
/**
* Set the RdbmsSpecifics object for formatting logging appropriate for the Rdbms used on this connection.
*
* @param rdbmsSpecifics the RdbmsSpecifics object for formatting logging appropriate for the Rdbms used.
*/
void setRdbmsSpecifics(RdbmsSpecifics rdbmsSpecifics)
{
this.rdbmsSpecifics = rdbmsSpecifics;
}
/**
* Get the RdbmsSpecifics object for formatting logging appropriate for the Rdbms used on this connection.
*
* @return the RdbmsSpecifics object for formatting logging appropriate for the Rdbms used.
*/
RdbmsSpecifics getRdbmsSpecifics()
{
return rdbmsSpecifics;
}
public Integer getConnectionNumber()
{
return connectionNumber;
}
public String getClassType()
{
return "Connection";
}
protected void reportException(String methodCall, SQLException exception, String sql)
{
log.exceptionOccured(this, methodCall, exception, sql, -1L);
}
protected void reportException(String methodCall, SQLException exception)
{
log.exceptionOccured(this, methodCall, exception, null, -1L);
}
protected void reportAllReturns(String methodCall, String returnValue)
{
log.methodReturned(this, methodCall, returnValue);
}
private boolean reportReturn(String methodCall, boolean value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
private int reportReturn(String methodCall, int value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
private Object reportReturn(String methodCall, Object value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
private void reportReturn(String methodCall)
{
reportAllReturns(methodCall, "");
}
// forwarding methods
public boolean isClosed() throws SQLException
{
String methodCall = "isClosed()";
try
{
return reportReturn(methodCall, (realConnection.isClosed()));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public SQLWarning getWarnings() throws SQLException
{
String methodCall = "getWarnings()";
try
{
return (SQLWarning) reportReturn(methodCall, realConnection.getWarnings());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Savepoint setSavepoint() throws SQLException
{
String methodCall = "setSavepoint()";
try
{
return (Savepoint) reportReturn(methodCall, realConnection.setSavepoint());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
String methodCall = "releaseSavepoint(" + savepoint + ")";
try
{
realConnection.releaseSavepoint(savepoint);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void rollback(Savepoint savepoint) throws SQLException
{
String methodCall = "rollback(" + savepoint + ")";
try
{
realConnection.rollback(savepoint);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public DatabaseMetaData getMetaData() throws SQLException
{
String methodCall = "getMetaData()";
try
{
return (DatabaseMetaData) reportReturn(methodCall, realConnection.getMetaData());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void clearWarnings() throws SQLException
{
String methodCall = "clearWarnings()";
try
{
realConnection.clearWarnings();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Statement createStatement() throws SQLException
{
String methodCall = "createStatement()";
try
{
Statement statement = realConnection.createStatement();
return (Statement) reportReturn(methodCall, new StatementSpy(this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
String methodCall = "createStatement(" + resultSetType + ", " + resultSetConcurrency + ")";
try
{
Statement statement = realConnection.createStatement(resultSetType, resultSetConcurrency);
return (Statement) reportReturn(methodCall, new StatementSpy(this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
String methodCall = "createStatement(" + resultSetType + ", " + resultSetConcurrency + ", " + resultSetHoldability + ")";
try
{
Statement statement = realConnection.createStatement(resultSetType, resultSetConcurrency,
resultSetHoldability);
return (Statement) reportReturn(methodCall, new StatementSpy(this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setReadOnly(boolean readOnly) throws SQLException
{
String methodCall = "setReadOnly(" + readOnly + ")";
try
{
realConnection.setReadOnly(readOnly);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public PreparedStatement prepareStatement(String sql) throws SQLException
{
String methodCall = "prepareStatement(" + sql + ")";
try
{
PreparedStatement statement = realConnection.prepareStatement(sql);
return (PreparedStatement) reportReturn(methodCall, new PreparedStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{
String methodCall = "prepareStatement(" + sql + ", " + autoGeneratedKeys + ")";
try
{
PreparedStatement statement = realConnection.prepareStatement(sql, autoGeneratedKeys);
return (PreparedStatement) reportReturn(methodCall, new PreparedStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
String methodCall = "prepareStatement(" + sql + ", " + resultSetType + ", " + resultSetConcurrency + ")";
try
{
PreparedStatement statement = realConnection.prepareStatement(sql, resultSetType, resultSetConcurrency);
return (PreparedStatement) reportReturn(methodCall, new PreparedStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
String methodCall = "prepareStatement(" + sql + ", " + resultSetType + ", " + resultSetConcurrency + ", " + resultSetHoldability + ")";
try
{
PreparedStatement statement = realConnection.prepareStatement(sql, resultSetType, resultSetConcurrency,
resultSetHoldability);
return (PreparedStatement) reportReturn(methodCall, new PreparedStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public PreparedStatement prepareStatement(String sql, int columnIndexes[]) throws SQLException
{
//todo: dump the array here?
String methodCall = "prepareStatement(" + sql + ", " + columnIndexes + ")";
try
{
PreparedStatement statement = realConnection.prepareStatement(sql, columnIndexes);
return (PreparedStatement) reportReturn(methodCall, new PreparedStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public Savepoint setSavepoint(String name) throws SQLException
{
String methodCall = "setSavepoint(" + name + ")";
try
{
return (Savepoint) reportReturn(methodCall, realConnection.setSavepoint(name));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public PreparedStatement prepareStatement(String sql, String columnNames[]) throws SQLException
{
//todo: dump the array here?
String methodCall = "prepareStatement(" + sql + ", " + columnNames + ")";
try
{
PreparedStatement statement = realConnection.prepareStatement(sql, columnNames);
return (PreparedStatement) reportReturn(methodCall, new PreparedStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public Clob createClob() throws SQLException {
String methodCall = "createClob()";
try
{
return (Clob) reportReturn(methodCall, realConnection.createClob());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Blob createBlob() throws SQLException {
String methodCall = "createBlob()";
try
{
return (Blob) reportReturn(methodCall, realConnection.createBlob());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public NClob createNClob() throws SQLException {
String methodCall = "createNClob()";
try
{
return (NClob) reportReturn(methodCall, realConnection.createNClob());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public SQLXML createSQLXML() throws SQLException {
String methodCall = "createSQLXML()";
try
{
return (SQLXML) reportReturn(methodCall, realConnection.createSQLXML());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean isValid(int timeout) throws SQLException {
String methodCall = "isValid(" + timeout + ")";
try
{
return reportReturn(methodCall,realConnection.isValid(timeout));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setClientInfo(String name, String value) throws SQLClientInfoException {
String methodCall = "setClientInfo(" + name + ", " + value + ")";
try
{
realConnection.setClientInfo(name,value);
}
catch (SQLClientInfoException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setClientInfo(Properties properties) throws SQLClientInfoException {
// todo: dump properties?
String methodCall = "setClientInfo(" + properties + ")";
try
{
realConnection.setClientInfo(properties);
}
catch (SQLClientInfoException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public String getClientInfo(String name) throws SQLException {
String methodCall = "getClientInfo(" + name + ")";
try
{
return (String) reportReturn(methodCall,realConnection.getClientInfo(name));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Properties getClientInfo() throws SQLException {
String methodCall = "getClientInfo()";
try
{
return (Properties) reportReturn(methodCall,realConnection.getClientInfo());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
//todo: dump elements?
String methodCall = "createArrayOf(" + typeName + ", " + elements +")";
try
{
return (Array) reportReturn(methodCall,realConnection.createArrayOf(typeName,elements));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
//todo: dump attributes?
String methodCall = "createStruct(" + typeName + ", " + attributes +")";
try
{
return (Struct) reportReturn(methodCall,realConnection.createStruct(typeName, attributes));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean isReadOnly() throws SQLException
{
String methodCall = "isReadOnly()";
try
{
return reportReturn(methodCall,realConnection.isReadOnly());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setHoldability(int holdability) throws SQLException
{
String methodCall = "setHoldability(" + holdability + ")";
try
{
realConnection.setHoldability(holdability);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public CallableStatement prepareCall(String sql) throws SQLException
{
String methodCall = "prepareCall(" + sql + ")";
try
{
CallableStatement statement = realConnection.prepareCall(sql);
return (CallableStatement) reportReturn(methodCall, new CallableStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
String methodCall = "prepareCall(" + sql + ", " + resultSetType + ", " + resultSetConcurrency + ")";
try
{
CallableStatement statement = realConnection.prepareCall(sql, resultSetType, resultSetConcurrency);
return (CallableStatement) reportReturn(methodCall, new CallableStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
String methodCall = "prepareCall(" + sql + ", " + resultSetType + ", " + resultSetConcurrency + ", " + resultSetHoldability + ")";
try
{
CallableStatement statement = realConnection.prepareCall(sql, resultSetType, resultSetConcurrency,
resultSetHoldability);
return (CallableStatement) reportReturn(methodCall, new CallableStatementSpy(sql, this, statement));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public void setCatalog(String catalog) throws SQLException
{
String methodCall = "setCatalog(" + catalog + ")";
try
{
realConnection.setCatalog(catalog);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public String nativeSQL(String sql) throws SQLException
{
String methodCall = "nativeSQL(" + sql + ")";
try
{
return (String) reportReturn(methodCall, realConnection.nativeSQL(sql));
}
catch (SQLException s)
{
reportException(methodCall, s, sql);
throw s;
}
}
public Map<String,Class<?>> getTypeMap() throws SQLException
{
String methodCall = "getTypeMap()";
try
{
return (Map<String,Class<?>>) reportReturn(methodCall, realConnection.getTypeMap());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setAutoCommit(boolean autoCommit) throws SQLException
{
String methodCall = "setAutoCommit(" + autoCommit + ")";
try
{
realConnection.setAutoCommit(autoCommit);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public String getCatalog() throws SQLException
{
String methodCall = "getCatalog()";
try
{
return (String) reportReturn(methodCall, realConnection.getCatalog());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setTypeMap(java.util.Map<String,Class<?>> map) throws SQLException
{
//todo: dump map??
String methodCall = "setTypeMap(" + map + ")";
try
{
realConnection.setTypeMap(map);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setTransactionIsolation(int level) throws SQLException
{
String methodCall = "setTransactionIsolation(" + level + ")";
try
{
realConnection.setTransactionIsolation(level);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean getAutoCommit() throws SQLException
{
String methodCall = "getAutoCommit()";
try
{
return reportReturn(methodCall, realConnection.getAutoCommit());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getHoldability() throws SQLException
{
String methodCall = "getHoldability()";
try
{
return reportReturn(methodCall, realConnection.getHoldability());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getTransactionIsolation() throws SQLException
{
String methodCall = "getTransactionIsolation()";
try
{
return reportReturn(methodCall, realConnection.getTransactionIsolation());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void commit() throws SQLException
{
String methodCall = "commit()";
try
{
realConnection.commit();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void rollback() throws SQLException
{
String methodCall = "rollback()";
try
{
realConnection.rollback();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void close() throws SQLException
{
String methodCall = "close()";
try
{
realConnection.close();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
finally
{
synchronized (connectionTracker)
{
connectionTracker.remove(connectionNumber);
}
log.connectionClosed(this);
}
reportReturn(methodCall);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
String methodCall = "unwrap(" + (iface==null?"null":iface.getName()) + ")";
try
{
//todo: double check this logic
return (T)reportReturn(methodCall, (iface != null && (iface == Connection.class || iface == Spy.class))?(T)this:realConnection.unwrap(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
String methodCall = "isWrapperFor(" + (iface==null?"null":iface.getName()) + ")";
try
{
return reportReturn(methodCall, (iface != null && (iface == Connection.class || iface == Spy.class)) ||
realConnection.isWrapperFor(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
} | zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/ConnectionSpy.java | Java | asf20 | 25,084 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
-->
</head>
<body bgcolor="white">
<b>log4jdbc</b> is a Java JDBC driver that can log SQL and/or JDBC calls (and optionally SQL timing information)
for other JDBC drivers using the <a target="slf4j" href="http://www.slf4j.org/">Simple Logging Facade For Java</a> (SLF4J) logging system.
<p/>
This is Open Source software:
<p/>
Copyright © 2007-2008 Arthur Blake
<p/>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this log4jdbc except in compliance with the License.
You may obtain a copy of the License at
<p/>
<a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
<p/>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<!-- Put @see and @since tags down here. -->
</body>
</html> | zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/package.html | HTML | asf20 | 1,129 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* RDBMS specifics for the Oracle DB.
*
* @author Arthur Blake
*/
class OracleRdbmsSpecifics extends RdbmsSpecifics
{
OracleRdbmsSpecifics()
{
super();
}
String formatParameterObject(Object object)
{
if (object instanceof Timestamp)
{
return "to_timestamp('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS").
format(object) + "', 'mm/dd/yyyy hh24:mi:ss.ff3')";
}
else if (object instanceof Date)
{
return "to_date('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").
format(object) + "', 'mm/dd/yyyy hh24:mi:ss')";
}
else
{
return super.formatParameterObject(object);
}
}
} | zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/OracleRdbmsSpecifics.java | Java | asf20 | 1,428 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
/**
* A provider for a SpyLogDelegator. This allows a single switch point to abstract
* away which logging system to use for spying on JDBC calls.
*
* The SLF4J logging facade is used, which is a very good general purpose facade for plugging into
* numerous java logging systems, simply and easily.
*
* @author Arthur Blake
*/
public class SpyLogFactory
{
/**
* Do not allow instantiation. Access is through static method.
*/
private SpyLogFactory() {}
/**
* The logging system of choice.
*/
private static final SpyLogDelegator logger = new Slf4jSpyLogDelegator();
//new Log4jSpyLogDelegator();
/**
* Get the default SpyLogDelegator for logging to the logger.
*
* @return the default SpyLogDelegator for logging to the logger.
*/
public static SpyLogDelegator getSpyLogDelegator()
{
return logger;
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/SpyLogFactory.java | Java | asf20 | 1,539 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.StringTokenizer;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* Delegates JDBC spy logging events to the the Simple Logging Facade for Java (slf4j).
*
* @author Arthur Blake
*/
public class Slf4jSpyLogDelegator implements SpyLogDelegator
{
/**
* Create a SpyLogDelegator specific to the Simple Logging Facade for Java (slf4j).
*/
public Slf4jSpyLogDelegator()
{
}
// logs for sql and jdbc
/**
* Logger that shows all JDBC calls on INFO level (exception ResultSet calls)
*/
private final Logger jdbcLogger = LoggerFactory.getLogger("jdbc.audit");
/**
* Logger that shows JDBC calls for ResultSet operations
*/
private final Logger resultSetLogger = LoggerFactory.getLogger("jdbc.resultset");
/**
* Logger that shows only the SQL that is occuring
*/
private final Logger sqlOnlyLogger = LoggerFactory.getLogger("jdbc.sqlonly");
/**
* Logger that shows the SQL timing, post execution
*/
private final Logger sqlTimingLogger = LoggerFactory.getLogger("jdbc.sqltiming");
/**
* Logger that shows connection open and close events as well as current number
* of open connections.
*/
private final Logger connectionLogger = LoggerFactory.getLogger("jdbc.connection");
// admin/setup logging for log4jdbc.
/**
* Logger just for debugging things within log4jdbc itself (admin, setup, etc.)
*/
private final Logger debugLogger = LoggerFactory.getLogger("log4jdbc.debug");
/**
* Determine if any of the 5 log4jdbc spy loggers are turned on (jdbc.audit | jdbc.resultset |
* jdbc.sqlonly | jdbc.sqltiming | jdbc.connection)
*
* @return true if any of the 5 spy jdbc/sql loggers are enabled at debug info or error level.
*/
public boolean isJdbcLoggingEnabled()
{
return jdbcLogger.isErrorEnabled() || resultSetLogger.isErrorEnabled() || sqlOnlyLogger.isErrorEnabled() ||
sqlTimingLogger.isErrorEnabled() || connectionLogger.isErrorEnabled();
}
/**
* Called when a jdbc method throws an Exception.
*
* @param spy the Spy wrapping the class that threw an Exception.
* @param methodCall a description of the name and call parameters of the method generated the Exception.
* @param e the Exception that was thrown.
* @param sql optional sql that occured just before the exception occured.
* @param execTime optional amount of time that passed before an exception was thrown when sql was being executed.
* caller should pass -1 if not used
*/
public void exceptionOccured(Spy spy, String methodCall, Exception e, String sql, long execTime)
{
String classType = spy.getClassType();
Integer spyNo = spy.getConnectionNumber();
String header = spyNo + ". " + classType + "." + methodCall;
if (sql == null)
{
jdbcLogger.error(header, e);
sqlOnlyLogger.error(header, e);
sqlTimingLogger.error(header, e);
}
else
{
sql = processSql(sql);
jdbcLogger.error(header + " " + sql, e);
// if at debug level, display debug info to error log
if (sqlOnlyLogger.isDebugEnabled())
{
sqlOnlyLogger.error(getDebugInfo() + nl + spyNo + ". " + sql, e);
}
else
{
sqlOnlyLogger.error(header + " " + sql, e);
}
// if at debug level, display debug info to error log
if (sqlTimingLogger.isDebugEnabled())
{
sqlTimingLogger.error(getDebugInfo() + nl + spyNo + ". " + sql + " {FAILED after " + execTime + " msec}", e);
}
else
{
sqlTimingLogger.error(header + " FAILED! " + sql + " {FAILED after " + execTime + " msec}", e);
}
}
}
/**
* Called when a JDBC method from a Connection, Statement, PreparedStatement,
* CallableStatement or ResultSet returns.
*
* @param spy the Spy wrapping the class that called the method that
* returned.
* @param methodCall a description of the name and call parameters of the
* method that returned.
* @param returnMsg return value converted to a String for integral types, or
* String representation for Object. Return types this will
* be null for void return types.
*/
public void methodReturned(Spy spy, String methodCall, String returnMsg)
{
String classType = spy.getClassType();
Logger logger=ResultSetSpy.classTypeDescription.equals(classType)?
resultSetLogger:jdbcLogger;
if (logger.isInfoEnabled())
{
String header = spy.getConnectionNumber() + ". " + classType + "." +
methodCall + " returned " + returnMsg;
if (logger.isDebugEnabled())
{
logger.debug(header + " " + getDebugInfo());
}
else
{
logger.info(header);
}
}
}
/**
* Called when a spied upon object is constructed.
*
* @param spy the Spy wrapping the class that called the method that returned.
* @param constructionInfo information about the object construction
*/
public void constructorReturned(Spy spy, String constructionInfo)
{
// not used in this implementation -- yet
}
private static String nl = System.getProperty("line.separator");
/**
* Determine if the given sql should be logged or not
* based on the various DumpSqlXXXXXX flags.
*
* @param sql SQL to test.
* @return true if the SQL should be logged, false if not.
*/
private boolean shouldSqlBeLogged(String sql)
{
if (sql == null)
{
return false;
}
sql = sql.trim();
if (sql.length()<6)
{
return false;
}
sql = sql.substring(0,6).toLowerCase();
return
(DriverSpy.DumpSqlSelect && "select".equals(sql)) ||
(DriverSpy.DumpSqlInsert && "insert".equals(sql)) ||
(DriverSpy.DumpSqlUpdate && "update".equals(sql)) ||
(DriverSpy.DumpSqlDelete && "delete".equals(sql)) ||
(DriverSpy.DumpSqlCreate && "create".equals(sql));
}
/**
* Special call that is called only for JDBC method calls that contain SQL.
*
* @param spy the Spy wrapping the class where the SQL occured.
* @param methodCall a description of the name and call parameters of the method that generated the SQL.
* @param sql sql that occured.
*/
public void sqlOccured(Spy spy, String methodCall, String sql)
{
if (!DriverSpy.DumpSqlFilteringOn || shouldSqlBeLogged(sql))
{
if (sqlOnlyLogger.isDebugEnabled())
{
sqlOnlyLogger.debug(getDebugInfo() + nl + spy.getConnectionNumber() +
". " + processSql(sql));
}
else if (sqlOnlyLogger.isInfoEnabled())
{
sqlOnlyLogger.info(processSql(sql));
}
}
}
/**
* Break an SQL statement up into multiple lines in an attempt to make it
* more readable
*
* @param sql SQL to break up.
* @return SQL broken up into multiple lines
*/
private String processSql(String sql)
{
if (sql==null)
{
return null;
}
if (DriverSpy.TrimSql)
{
sql = sql.trim();
}
StringBuilder output = new StringBuilder();
if (DriverSpy.DumpSqlMaxLineLength <= 0)
{
output.append(sql);
}
else
{
// insert line breaks into sql to make it more readable
StringTokenizer st = new StringTokenizer(sql);
String token;
int linelength = 0;
while (st.hasMoreElements())
{
token = (String) st.nextElement();
output.append(token);
linelength += token.length();
output.append(" ");
linelength++;
if (linelength > DriverSpy.DumpSqlMaxLineLength)
{
output.append("\n");
linelength = 0;
}
}
}
if (DriverSpy.DumpSqlAddSemicolon)
{
output.append(";");
}
String stringOutput = output.toString();
if (DriverSpy.TrimExtraBlankLinesInSql)
{
LineNumberReader lineReader = new LineNumberReader(new StringReader(stringOutput));
output = new StringBuilder();
int contiguousBlankLines = 0;
try
{
while (true)
{
String line = lineReader.readLine();
if (line==null)
{
break;
}
// is this line blank?
if (line.trim().length() == 0)
{
contiguousBlankLines ++;
// skip contiguous blank lines
if (contiguousBlankLines > 1)
{
continue;
}
}
else
{
contiguousBlankLines = 0;
output.append(line);
}
output.append("\n");
}
}
catch (IOException e)
{
// since we are reading from a buffer, this isn't likely to happen,
// but if it does we just ignore it and treat it like its the end of the stream
}
stringOutput = output.toString();
}
return stringOutput;
}
/**
* Special call that is called only for JDBC method calls that contain SQL.
*
* @param spy the Spy wrapping the class where the SQL occurred.
*
* @param execTime how long it took the SQL to run, in milliseconds.
*
* @param methodCall a description of the name and call parameters of the
* method that generated the SQL.
*
* @param sql SQL that occurred.
*/
public void sqlTimingOccured(Spy spy, long execTime, String methodCall, String sql)
{
if (sqlTimingLogger.isErrorEnabled() &&
(!DriverSpy.DumpSqlFilteringOn || shouldSqlBeLogged(sql)))
{
if (DriverSpy.SqlTimingErrorThresholdEnabled &&
execTime >= DriverSpy.SqlTimingErrorThresholdMsec)
{
sqlTimingLogger.error(
buildSqlTimingDump(spy, execTime, methodCall, sql, sqlTimingLogger.isDebugEnabled()));
}
else if (sqlTimingLogger.isWarnEnabled())
{
if (DriverSpy.SqlTimingWarnThresholdEnabled &&
execTime >= DriverSpy.SqlTimingWarnThresholdMsec)
{
sqlTimingLogger.warn(
buildSqlTimingDump(spy, execTime, methodCall, sql, sqlTimingLogger.isDebugEnabled()));
}
else if (sqlTimingLogger.isDebugEnabled())
{
sqlTimingLogger.debug(
buildSqlTimingDump(spy, execTime, methodCall, sql, true));
}
else if (sqlTimingLogger.isInfoEnabled())
{
sqlTimingLogger.info(
buildSqlTimingDump(spy, execTime, methodCall, sql, false));
}
}
}
}
/**
* Helper method to quickly build a SQL timing dump output String for
* logging.
*
* @param spy the Spy wrapping the class where the SQL occurred.
*
* @param execTime how long it took the SQL to run, in milliseconds.
*
* @param methodCall a description of the name and call parameters of the
* method that generated the SQL.
*
* @param sql SQL that occurred.
*
* @param debugInfo if true, include debug info at the front of the output.
*
* @return a SQL timing dump String for logging.
*/
private String buildSqlTimingDump(Spy spy, long execTime, String methodCall,
String sql, boolean debugInfo)
{
StringBuffer out = new StringBuffer();
if (debugInfo)
{
out.append(getDebugInfo());
out.append(nl);
out.append(spy.getConnectionNumber());
out.append(". ");
}
// NOTE: if both sql dump and sql timing dump are on, the processSql
// algorithm will run TWICE once at the beginning and once at the end
// this is not very efficient but usually
// only one or the other dump should be on and not both.
sql = processSql(sql);
out.append(sql);
out.append(" {executed in ");
out.append(execTime);
out.append(" msec}");
return out.toString();
}
/**
* Get debugging info - the module and line number that called the logger
* version that prints the stack trace information from the point just before
* we got it (net.sf.log4jdbc)
*
* if the optional log4jdbc.debug.stack.prefix system property is defined then
* the last call point from an application is shown in the debug
* trace output, instead of the last direct caller into log4jdbc
*
* @return debugging info for whoever called into JDBC from within the application.
*/
private static String getDebugInfo()
{
Throwable t = new Throwable();
t.fillInStackTrace();
StackTraceElement[] stackTrace = t.getStackTrace();
if (stackTrace != null)
{
String className;
StringBuffer dump = new StringBuffer();
/**
* The DumpFullDebugStackTrace option is useful in some situations when
* we want to see the full stack trace in the debug info- watch out
* though as this will make the logs HUGE!
*/
if (DriverSpy.DumpFullDebugStackTrace)
{
boolean first=true;
for (int i = 0; i < stackTrace.length; i++)
{
className = stackTrace[i].getClassName();
if (!className.startsWith("net.sf.log4jdbc"))
{
if (first)
{
first = false;
}
else
{
dump.append(" ");
}
dump.append("at ");
dump.append(stackTrace[i]);
dump.append(nl);
}
}
}
else
{
dump.append(" ");
int firstLog4jdbcCall = 0;
int lastApplicationCall = 0;
for (int i = 0; i < stackTrace.length; i++)
{
className = stackTrace[i].getClassName();
if (className.startsWith("net.sf.log4jdbc"))
{
firstLog4jdbcCall = i;
}
else if (DriverSpy.TraceFromApplication &&
className.startsWith(DriverSpy.DebugStackPrefix))
{
lastApplicationCall = i;
break;
}
}
int j = lastApplicationCall;
if (j == 0) // if app not found, then use whoever was the last guy that called a log4jdbc class.
{
j = 1 + firstLog4jdbcCall;
}
dump.append(stackTrace[j].getClassName()).append(".").append(stackTrace[j].getMethodName()).append("(").
append(stackTrace[j].getFileName()).append(":").append(stackTrace[j].getLineNumber()).append(")");
}
return dump.toString();
}
else
{
return null;
}
}
/**
* Log a Setup and/or administrative log message for log4jdbc.
*
* @param msg message to log.
*/
public void debug(String msg)
{
debugLogger.debug(msg);
}
/**
* Called whenever a new connection spy is created.
*
* @param spy ConnectionSpy that was created.
*/
public void connectionOpened(Spy spy)
{
if (connectionLogger.isDebugEnabled())
{
connectionLogger.info(spy.getConnectionNumber() + ". Connection opened " +
getDebugInfo());
connectionLogger.debug(ConnectionSpy.getOpenConnectionsDump());
}
else
{
connectionLogger.info(spy.getConnectionNumber() + ". Connection opened");
}
}
/**
* Called whenever a connection spy is closed.
*
* @param spy ConnectionSpy that was closed.
*/
public void connectionClosed(Spy spy)
{
if (connectionLogger.isDebugEnabled())
{
connectionLogger.info(spy.getConnectionNumber() + ". Connection closed " +
getDebugInfo());
connectionLogger.debug(ConnectionSpy.getOpenConnectionsDump());
}
else
{
connectionLogger.info(spy.getConnectionNumber() + ". Connection closed");
}
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/Slf4jSpyLogDelegator.java | Java | asf20 | 16,978 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.List;
import java.util.ArrayList;
/**
* Wraps a Statement and reports method calls, returns and exceptions.
*
* jdbc 4 version
*
* @author Arthur Blake
*/
public class StatementSpy implements Statement, Spy
{
protected final SpyLogDelegator log;
/**
* The Connection that created this Statement.
*/
protected ConnectionSpy connectionSpy;
/**
* The real statement that this StatementSpy wraps.
*/
protected Statement realStatement;
/**
* Get the real Statement that this StatementSpy wraps.
*
* @return the real Statement that this StatementSpy wraps.
*/
public Statement getRealStatement()
{
return realStatement;
}
/**
* Create a StatementSpy that wraps another Statement
* for the purpose of logging all method calls, sql, exceptions and return values.
*
* @param connectionSpy Connection that created this Statement.
* @param realStatement real underlying Statement that this StatementSpy wraps.
*/
public StatementSpy(ConnectionSpy connectionSpy, Statement realStatement)
{
if (realStatement == null)
{
throw new IllegalArgumentException("Must pass in a non null real Statement");
}
if (connectionSpy == null)
{
throw new IllegalArgumentException("Must pass in a non null ConnectionSpy");
}
this.realStatement = realStatement;
this.connectionSpy = connectionSpy;
log = SpyLogFactory.getSpyLogDelegator();
if (realStatement instanceof CallableStatement)
{
reportReturn("new CallableStatement");
}
else if (realStatement instanceof PreparedStatement)
{
reportReturn("new PreparedStatement");
}
else
{
reportReturn("new Statement");
}
}
public String getClassType()
{
return "Statement";
}
public Integer getConnectionNumber()
{
return connectionSpy.getConnectionNumber();
}
/**
* Report an exception to be logged which includes timing data on a sql failure.
* @param methodCall description of method call and arguments passed to it that generated the exception.
* @param exception exception that was generated
* @param sql SQL associated with the call.
* @param execTime amount of time that the jdbc driver was chugging on the SQL before it threw an exception.
*/
protected void reportException(String methodCall, SQLException exception, String sql, long execTime)
{
log.exceptionOccured(this, methodCall, exception, sql, execTime);
}
/**
* Report an exception to be logged.
* @param methodCall description of method call and arguments passed to it that generated the exception.
* @param exception exception that was generated
* @param sql SQL associated with the call.
*/
protected void reportException(String methodCall, SQLException exception, String sql)
{
log.exceptionOccured(this, methodCall, exception, sql, -1L);
}
/**
* Report an exception to be logged.
*
* @param methodCall description of method call and arguments passed to it that generated the exception.
* @param exception exception that was generated
*/
protected void reportException(String methodCall, SQLException exception)
{
log.exceptionOccured(this, methodCall, exception, null, -1L);
}
/**
* Report (for logging) that a method returned. All the other reportReturn methods are conveniance methods that call this method.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param msg description of what the return value that was returned. may be an empty String for void return types.
*/
protected void reportAllReturns(String methodCall, String msg)
{
log.methodReturned(this, methodCall, msg);
}
/**
* Conveniance method to report (for logging) that a method returned a boolean value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value boolean return value.
* @return the boolean return value as passed in.
*/
protected boolean reportReturn(String methodCall, boolean value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a byte value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value byte return value.
* @return the byte return value as passed in.
*/
protected byte reportReturn(String methodCall, byte value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a int value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value int return value.
* @return the int return value as passed in.
*/
protected int reportReturn(String methodCall, int value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a double value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value double return value.
* @return the double return value as passed in.
*/
protected double reportReturn(String methodCall, double value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a short value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value short return value.
* @return the short return value as passed in.
*/
protected short reportReturn(String methodCall, short value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a long value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value long return value.
* @return the long return value as passed in.
*/
protected long reportReturn(String methodCall, long value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a float value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value float return value.
* @return the float return value as passed in.
*/
protected float reportReturn(String methodCall, float value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned an Object.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value return Object.
* @return the return Object as passed in.
*/
protected Object reportReturn(String methodCall, Object value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned (void return type).
*
* @param methodCall description of method call and arguments passed to it that returned.
*/
protected void reportReturn(String methodCall)
{
reportAllReturns(methodCall, "");
}
/**
* Running one-off statement sql is generally inefficient and a bad idea for various reasons,
* so give a warning when this is done.
*/
private static final String StatementSqlWarning = "{WARNING: Statement used to run SQL} ";
/**
* Report SQL for logging with a warning that it was generated from a statement.
*
* @param sql the SQL being run
* @param methodCall the name of the method that was running the SQL
*/
protected void reportStatementSql(String sql, String methodCall)
{
// redirect to one more method call ONLY so that stack trace search is consistent
// with the reportReturn calls
_reportSql((DriverSpy.StatementUsageWarn?StatementSqlWarning:"") +
sql, methodCall);
}
/**
* Report SQL for logging with a warning that it was generated from a statement.
*
* @param execTime execution time in msec.
* @param sql the SQL being run
* @param methodCall the name of the method that was running the SQL
*/
protected void reportStatementSqlTiming(long execTime, String sql, String methodCall)
{
// redirect to one more method call ONLY so that stack trace search is consistent
// with the reportReturn calls
_reportSqlTiming(execTime, (DriverSpy.StatementUsageWarn?StatementSqlWarning:"") +
sql, methodCall);
}
/**
* Report SQL for logging.
*
* @param execTime execution time in msec.
* @param sql the SQL being run
* @param methodCall the name of the method that was running the SQL
*/
protected void reportSqlTiming(long execTime, String sql, String methodCall)
{
// redirect to one more method call ONLY so that stack trace search is consistent
// with the reportReturn calls
_reportSqlTiming(execTime, sql, methodCall);
}
/**
* Report SQL for logging.
*
* @param sql the SQL being run
* @param methodCall the name of the method that was running the SQL
*/
protected void reportSql(String sql, String methodCall)
{
// redirect to one more method call ONLY so that stack trace search is consistent
// with the reportReturn calls
_reportSql(sql, methodCall);
}
private void _reportSql(String sql, String methodCall)
{
log.sqlOccured(this, methodCall, sql);
}
private void _reportSqlTiming(long execTime, String sql, String methodCall)
{
log.sqlTimingOccured(this, execTime, methodCall, sql);
}
// implementation of interface methods
public SQLWarning getWarnings() throws SQLException
{
String methodCall = "getWarnings()";
try
{
return (SQLWarning) reportReturn(methodCall, realStatement.getWarnings());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int executeUpdate(String sql, String[] columnNames) throws SQLException
{
String methodCall = "executeUpdate(" + sql + ", " + columnNames + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
int result = realStatement.executeUpdate(sql, columnNames);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public boolean execute(String sql, String[] columnNames) throws SQLException
{
String methodCall = "execute(" + sql + ", " + columnNames + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
boolean result = realStatement.execute(sql, columnNames);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public void setMaxRows(int max) throws SQLException
{
String methodCall = "setMaxRows(" + max + ")";
try
{
realStatement.setMaxRows(max);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean getMoreResults() throws SQLException
{
String methodCall = "getMoreResults()";
try
{
return reportReturn(methodCall, realStatement.getMoreResults());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void clearWarnings() throws SQLException
{
String methodCall = "clearWarnings()";
try
{
realStatement.clearWarnings();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
/**
* Tracking of current batch (see addBatch, clearBatch and executeBatch)
* //todo: should access to this List be synchronized?
*/
protected List currentBatch = new ArrayList();
public void addBatch(String sql) throws SQLException
{
String methodCall = "addBatch(" + sql + ")";
currentBatch.add(StatementSqlWarning + sql);
try
{
realStatement.addBatch(sql);
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
reportReturn(methodCall);
}
public int getResultSetType() throws SQLException
{
String methodCall = "getResultSetType()";
try
{
return reportReturn(methodCall, realStatement.getResultSetType());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void clearBatch() throws SQLException
{
String methodCall = "clearBatch()";
try
{
realStatement.clearBatch();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
currentBatch.clear();
reportReturn(methodCall);
}
public void setFetchDirection(int direction) throws SQLException
{
String methodCall = "setFetchDirection(" + direction + ")";
try
{
realStatement.setFetchDirection(direction);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int[] executeBatch() throws SQLException
{
String methodCall = "executeBatch()";
int j=currentBatch.size();
StringBuffer batchReport = new StringBuffer("batching " + j + " statements:");
int fieldSize = (""+j).length();
String sql;
for (int i=0; i < j;)
{
sql = (String) currentBatch.get(i);
batchReport.append("\n");
batchReport.append(Utilities.rightJustify(fieldSize,""+(++i)));
batchReport.append(": ");
batchReport.append(sql);
}
sql = batchReport.toString();
reportSql(sql, methodCall);
long tstart = System.currentTimeMillis();
int[] updateResults;
try
{
updateResults = realStatement.executeBatch();
reportSqlTiming(System.currentTimeMillis()-tstart, sql, methodCall);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis()-tstart);
throw s;
}
currentBatch.clear();
return (int[])reportReturn(methodCall,updateResults);
}
public void setFetchSize(int rows) throws SQLException
{
String methodCall = "setFetchSize(" + rows + ")";
try
{
realStatement.setFetchSize(rows);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getQueryTimeout() throws SQLException
{
String methodCall = "getQueryTimeout()";
try
{
return reportReturn(methodCall, realStatement.getQueryTimeout());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Connection getConnection() throws SQLException
{
String methodCall = "getConnection()";
return (Connection) reportReturn(methodCall, connectionSpy);
}
public ResultSet getGeneratedKeys() throws SQLException
{
String methodCall = "getGeneratedKeys()";
try
{
ResultSet r = realStatement.getGeneratedKeys();
if (r == null)
{
return (ResultSet) reportReturn(methodCall, r);
}
else
{
return (ResultSet) reportReturn(methodCall, new ResultSetSpy(this, r));
}
}
catch (SQLException s)
{
if (!DriverSpy.SuppressGetGeneratedKeysException)
{
reportException(methodCall, s);
}
throw s;
}
}
public void setEscapeProcessing(boolean enable) throws SQLException
{
String methodCall = "setEscapeProcessing(" + enable + ")";
try
{
realStatement.setEscapeProcessing(enable);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getFetchDirection() throws SQLException
{
String methodCall = "getFetchDirection()";
try
{
return reportReturn(methodCall, realStatement.getFetchDirection());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setQueryTimeout(int seconds) throws SQLException
{
String methodCall = "setQueryTimeout(" + seconds + ")";
try
{
realStatement.setQueryTimeout(seconds);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean getMoreResults(int current) throws SQLException
{
String methodCall = "getMoreResults(" + current + ")";
try
{
return reportReturn(methodCall, realStatement.getMoreResults(current));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public ResultSet executeQuery(String sql) throws SQLException
{
String methodCall = "executeQuery(" + sql + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
ResultSet result = realStatement.executeQuery(sql);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
ResultSetSpy r = new ResultSetSpy(this, result);
return (ResultSet) reportReturn(methodCall, r);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public int getMaxFieldSize() throws SQLException
{
String methodCall = "getMaxFieldSize()";
try
{
return reportReturn(methodCall, realStatement.getMaxFieldSize());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int executeUpdate(String sql) throws SQLException
{
String methodCall = "executeUpdate(" + sql + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
int result = realStatement.executeUpdate(sql);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public void cancel() throws SQLException
{
String methodCall = "cancel()";
try
{
realStatement.cancel();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setCursorName(String name) throws SQLException
{
String methodCall = "setCursorName(" + name + ")";
try
{
realStatement.setCursorName(name);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getFetchSize() throws SQLException
{
String methodCall = "getFetchSize()";
try
{
return reportReturn(methodCall, realStatement.getFetchSize());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getResultSetConcurrency() throws SQLException
{
String methodCall = "getResultSetConcurrency()";
try
{
return reportReturn(methodCall, realStatement.getResultSetConcurrency());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getResultSetHoldability() throws SQLException
{
String methodCall = "getResultSetHoldability()";
try
{
return reportReturn(methodCall, realStatement.getResultSetHoldability());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean isClosed() throws SQLException {
String methodCall = "isClosed()";
try
{
return reportReturn(methodCall, realStatement.isClosed());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setPoolable(boolean poolable) throws SQLException {
String methodCall = "setPoolable(" + poolable + ")";
try
{
realStatement.setPoolable(poolable);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean isPoolable() throws SQLException {
String methodCall = "isPoolable()";
try
{
return reportReturn(methodCall, realStatement.isPoolable());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setMaxFieldSize(int max) throws SQLException
{
String methodCall = "setMaxFieldSize(" + max + ")";
try
{
realStatement.setMaxFieldSize(max);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean execute(String sql) throws SQLException
{
String methodCall = "execute(" + sql + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
boolean result = realStatement.execute(sql);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException
{
String methodCall = "executeUpdate(" + sql + ", " + autoGeneratedKeys + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
int result = realStatement.executeUpdate(sql, autoGeneratedKeys);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException
{
String methodCall = "execute(" + sql + ", " + autoGeneratedKeys + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
boolean result = realStatement.execute(sql, autoGeneratedKeys);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException
{
String methodCall = "executeUpdate(" + sql + ", " + columnIndexes + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
int result = realStatement.executeUpdate(sql, columnIndexes);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public boolean execute(String sql, int[] columnIndexes) throws SQLException
{
String methodCall = "execute(" + sql + ", " + columnIndexes + ")";
reportStatementSql(sql, methodCall);
long tstart = System.currentTimeMillis();
try
{
boolean result = realStatement.execute(sql, columnIndexes);
reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall);
return reportReturn(methodCall, result);
}
catch (SQLException s)
{
reportException(methodCall, s, sql, System.currentTimeMillis() - tstart);
throw s;
}
}
public ResultSet getResultSet() throws SQLException
{
String methodCall = "getResultSet()";
try
{
ResultSet r = realStatement.getResultSet();
if (r == null)
{
return (ResultSet) reportReturn(methodCall, r);
}
else
{
return (ResultSet) reportReturn(methodCall, new ResultSetSpy(this, r));
}
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getMaxRows() throws SQLException
{
String methodCall = "getMaxRows()";
try
{
return reportReturn(methodCall, realStatement.getMaxRows());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void close() throws SQLException
{
String methodCall = "close()";
try
{
realStatement.close();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getUpdateCount() throws SQLException
{
String methodCall = "getUpdateCount()";
try
{
return reportReturn(methodCall, realStatement.getUpdateCount());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public <T> T unwrap(Class<T> iface) throws SQLException {
String methodCall = "unwrap(" + (iface==null?"null":iface.getName()) + ")";
try
{
//todo: double check this logic
return (T)reportReturn(methodCall, (iface != null && (iface == Connection.class || iface == Spy.class))?(T)this:realStatement.unwrap(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
String methodCall = "isWrapperFor(" + (iface==null?"null":iface.getName()) + ")";
try
{
return reportReturn(methodCall, (iface != null && (iface == Statement.class || iface == Spy.class)) ||
realStatement.isWrapperFor(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/StatementSpy.java | Java | asf20 | 28,370 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.io.PrintStream;
import java.util.List;
import java.util.LinkedList;
import java.util.Arrays;
/**
* Post processes an existing sqltiming log, and creates a profiling report from it.
* Name of log file is passed in on the command line as the only argument.
*
* Assumptions:
*
* 1. Each sql statement in the log is separated by a blank line.
* 2. Each sql statement is terminated with the timing string "{executed in N msec}" where N is the number of
* milliseconds that the sql executed in.
*
*/
public class PostLogProfilerProcessor {
//todo: needs to be able to gracefully handle sql exceptions in log output
/**
* Post Process log4jdbc sqltiming log data.
*
* @param args command line arguments. Expects one argument, the name of the file to post process.
* @throws Exception if something goes wrong during processing.
*/
public static void main(String[] args) throws Exception
{
if (args.length < 1)
{
System.out.println("usage: java PostLogProfilerProcessor <log-file>");
System.exit(1);
}
new PostLogProfilerProcessor(args[0], System.out);
}
/**
* Total number of sql statements processed.
*/
private long totalSql = 0L;
/**
* Number of lines processed.
*/
private long lineNo = 0L;
/**
* Total number of milliseconds that all processed sql took to run.
*/
private long totalMsec = 0L;
/**
* Milliseconds of the worst single offending sql statement.
*/
private long maxMsec = 0L;
/**
* Total combined milliseconds of all flagged sql statements.
*/
private long flaggedSqlTotalMsec = 0L;
/**
* Threshold at which sql is deemed to be running slow enough to be flagged.
*/
private long threshold = 100L;
/**
* How many top offender sql statements to display in final report
*/
private long topOffenderCount = 1000L;
/**
* Collection of all sql that took longer than "threshold" msec to run.
*/
private List flaggedSql = new LinkedList();
/**
* Process given filename, and produce sql profiling report to given PrintStream.
*
* @param filename sqltiming log to process.
* @param out PrintStream to write profiling report to.
* @throws Exception if reading error occurs.
*/
public PostLogProfilerProcessor (String filename, PrintStream out) throws Exception
{
FileReader f= new FileReader(filename);
LineNumberReader l = new LineNumberReader(f);
String line;
boolean blankLine;
StringBuffer sql = new StringBuffer();
do
{
line = l.readLine();
if (line != null)
{
blankLine = line.length()==0;
lineNo++;
/*
if (lineNo%100000L==0L)
{
out.println("" + lineNo + " lines...");
}
*/
if (blankLine)
{
processSql(sql);
sql = new StringBuffer();
}
else
{
sql.append(line);
}
}
} while (line != null);
out.println("processed " + lineNo + " lines.");
f.close();
// display report to stdout
out.println("Number of sql statements: " + totalSql);
out.println("Total number of msec : " + totalMsec);
if (totalMsec>0)
{
out.println("Average msec/statement : " + totalSql/totalMsec);
}
int flaggedSqlStmts = flaggedSql.size();
if (flaggedSqlStmts>0)
{
out.println("Sql statements that took more than "+ threshold + " msec were flagged.");
out.println("Flagged sql statements : " + flaggedSqlStmts);
out.println("Flagged sql Total number of msec : " + flaggedSqlTotalMsec);
out.println("Flagged sql Average msec/statement : " + flaggedSqlTotalMsec/flaggedSqlStmts);
out.println("sorting...");
Object[] flaggedSqlArray = flaggedSql.toArray();
Arrays.sort(flaggedSqlArray);
int execTimeSize = ("" + maxMsec).length();
if (topOffenderCount > flaggedSqlArray.length)
{
topOffenderCount = flaggedSqlArray.length;
}
out.println("top " + topOffenderCount + " offender"+ (topOffenderCount==1?"":"s") + ":");
ProfiledSql p;
for (int i=0; i < topOffenderCount; i++)
{
p = (ProfiledSql) flaggedSqlArray[i];
out.println(Utilities.rightJustify(execTimeSize,""+p.getExecTime()) + " " + p.getSql());
}
}
}
private void processSql(StringBuffer sql)
{
if (sql.length()>0)
{
totalSql++;
String sqlStr = sql.toString();
if (sqlStr.endsWith("msec}"))
{
int executedIn = sqlStr.indexOf("{executed in ");
if (executedIn == -1)
{
System.err.println("WARNING: sql w/o timing info found at line " + lineNo);
return;
}
//todo: proper error handling for parse
String msecStr = sqlStr.substring(executedIn+13, sqlStr.length()-6);
long msec = Long.parseLong(msecStr);
totalMsec +=msec;
if (msec > maxMsec)
{
maxMsec = msec;
}
if (msec >threshold)
{
flagSql(msec,sqlStr);
flaggedSqlTotalMsec += msec;
}
}
else
{
System.err.println("WARNING: sql w/o timing info found at line " + lineNo);
}
}
}
private void flagSql(long msec, String sql)
{
flaggedSql.add(new ProfiledSql(msec,sql));
}
private class ProfiledSql implements Comparable {
private Long execTime;
private String sql;
public ProfiledSql (long msec, String sql)
{
this.execTime= new Long(msec);
this.sql = sql;
}
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.<p>
*
* In this case the comparison is used to sort flagged sql in descending order.
* @param o ProfiledSql Object to compare to this ProfiledSql. Must not be null.
*/
public int compareTo(Object o) {
return ((ProfiledSql)o).execTime.compareTo(execTime);
}
public Long getExecTime() {
return execTime;
}
public String getSql() {
return sql;
}
public String toString()
{
return this.execTime + " msec: " + this.sql;
}
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/PostLogProfilerProcessor.java | Java | asf20 | 7,295 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.RowId;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
/**
* Wraps a ResultSet and reports method calls, returns and exceptions.
*
* JDBC 4 version.
*
* @author Arthur Blake
*/
public class ResultSetSpy implements ResultSet, Spy
{
private final SpyLogDelegator log;
/**
* Report an exception to be logged.
*
* @param methodCall description of method call and arguments passed to it that generated the exception.
* @param exception exception that was generated
*/
protected void reportException(String methodCall, SQLException exception)
{
log.exceptionOccured(this, methodCall, exception, null, -1L);
}
/**
* Report (for logging) that a method returned. All the other reportReturn methods are conveniance methods that call
* this method.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param msg description of what the return value that was returned. may be an empty String for void return types.
*/
protected void reportAllReturns(String methodCall, String msg)
{
log.methodReturned(this, methodCall, msg);
}
private ResultSet realResultSet;
/**
* Get the real ResultSet that this ResultSetSpy wraps.
*
* @return the real ResultSet that this ResultSetSpy wraps.
*/
public ResultSet getRealResultSet()
{
return realResultSet;
}
private StatementSpy parent;
/**
* Create a new ResultSetSpy that wraps another ResultSet object, that logs all method calls, expceptions, etc.
*
* @param parent Statement that generated this ResultSet.
* @param realResultSet real underlying ResultSet that is being wrapped.
*/
public ResultSetSpy(StatementSpy parent, ResultSet realResultSet)
{
if (realResultSet == null)
{
throw new IllegalArgumentException("Must provide a non null real ResultSet");
}
this.realResultSet = realResultSet;
this.parent = parent;
log = SpyLogFactory.getSpyLogDelegator();
reportReturn("new ResultSet");
}
/**
* Description for ResultSet class type.
*/
public static final String classTypeDescription = "ResultSet";
public String getClassType()
{
return classTypeDescription;
}
public Integer getConnectionNumber()
{
return parent.getConnectionNumber();
}
/**
* Conveniance method to report (for logging) that a method returned a boolean value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value boolean return value.
* @return the boolean return value as passed in.
*/
protected boolean reportReturn(String methodCall, boolean value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a byte value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value byte return value.
* @return the byte return value as passed in.
*/
protected byte reportReturn(String methodCall, byte value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a int value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value int return value.
* @return the int return value as passed in.
*/
protected int reportReturn(String methodCall, int value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a double value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value double return value.
* @return the double return value as passed in.
*/
protected double reportReturn(String methodCall, double value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a short value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value short return value.
* @return the short return value as passed in.
*/
protected short reportReturn(String methodCall, short value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a long value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value long return value.
* @return the long return value as passed in.
*/
protected long reportReturn(String methodCall, long value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned a float value.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value float return value.
* @return the float return value as passed in.
*/
protected float reportReturn(String methodCall, float value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned an Object.
*
* @param methodCall description of method call and arguments passed to it that returned.
* @param value return Object.
* @return the return Object as passed in.
*/
protected Object reportReturn(String methodCall, Object value)
{
reportAllReturns(methodCall, "" + value);
return value;
}
/**
* Conveniance method to report (for logging) that a method returned (void return type).
*
* @param methodCall description of method call and arguments passed to it that returned.
*/
protected void reportReturn(String methodCall)
{
reportAllReturns(methodCall, "");
}
// forwarding methods
public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException
{
String methodCall = "updateAsciiStream(" + columnIndex + ", " + x + ", " + length + ")";
try
{
realResultSet.updateAsciiStream(columnIndex, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException
{
String methodCall = "updateAsciiStream(" + columnName + ", " + x + ", " + length + ")";
try
{
realResultSet.updateAsciiStream(columnName, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getRow() throws SQLException
{
String methodCall = "getRow()";
try
{
return reportReturn(methodCall, realResultSet.getRow());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void cancelRowUpdates() throws SQLException
{
String methodCall = "cancelRowUpdates()";
try
{
realResultSet.cancelRowUpdates();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Time getTime(int columnIndex) throws SQLException
{
String methodCall = "getTime(" + columnIndex + ")";
try
{
return (Time) reportReturn(methodCall, realResultSet.getTime(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Time getTime(String columnName) throws SQLException
{
String methodCall = "getTime(" + columnName + ")";
try
{
return (Time) reportReturn(methodCall, realResultSet.getTime(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Time getTime(int columnIndex, Calendar cal) throws SQLException
{
String methodCall = "getTime(" + columnIndex + ", " + cal + ")";
try
{
return (Time) reportReturn(methodCall, realResultSet.getTime(columnIndex, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Time getTime(String columnName, Calendar cal) throws SQLException
{
String methodCall = "getTime(" + columnName + ", " + cal + ")";
try
{
return (Time) reportReturn(methodCall, realResultSet.getTime(columnName, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean absolute(int row) throws SQLException
{
String methodCall = "absolute(" + row + ")";
try
{
return reportReturn(methodCall, realResultSet.absolute(row));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Timestamp getTimestamp(int columnIndex) throws SQLException
{
String methodCall = "getTimestamp(" + columnIndex + ")";
try
{
return (Timestamp) reportReturn(methodCall, realResultSet.getTimestamp(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Timestamp getTimestamp(String columnName) throws SQLException
{
String methodCall = "getTimestamp(" + columnName + ")";
try
{
return (Timestamp) reportReturn(methodCall, realResultSet.getTimestamp(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException
{
String methodCall = "getTimestamp(" + columnIndex + ", " + cal + ")";
try
{
return (Timestamp) reportReturn(methodCall, realResultSet.getTimestamp(columnIndex, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException
{
String methodCall = "getTimestamp(" + columnName + ", " + cal + ")";
try
{
return (Timestamp) reportReturn(methodCall, realResultSet.getTimestamp(columnName, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void moveToInsertRow() throws SQLException
{
String methodCall = "moveToInsertRow()";
try
{
realResultSet.moveToInsertRow();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean relative(int rows) throws SQLException
{
String methodCall = "relative(" + rows + ")";
try
{
return reportReturn(methodCall, realResultSet.relative(rows));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean previous() throws SQLException
{
String methodCall = "previous()";
try
{
return reportReturn(methodCall, realResultSet.previous());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void moveToCurrentRow() throws SQLException
{
String methodCall = "moveToCurrentRow()";
try
{
realResultSet.moveToCurrentRow();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Ref getRef(int i) throws SQLException
{
String methodCall = "getRef(" + i + ")";
try
{
return (Ref) reportReturn(methodCall, realResultSet.getRef(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateRef(int columnIndex, Ref x) throws SQLException
{
String methodCall = "updateRef(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateRef(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Ref getRef(String colName) throws SQLException
{
String methodCall = "getRef(" + colName + ")";
try
{
return (Ref) reportReturn(methodCall, realResultSet.getRef(colName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateRef(String columnName, Ref x) throws SQLException
{
String methodCall = "updateRef(" + columnName + ", " + x + ")";
try
{
realResultSet.updateRef(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Blob getBlob(int i) throws SQLException
{
String methodCall = "getBlob(" + i + ")";
try
{
return (Blob) reportReturn(methodCall, realResultSet.getBlob(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateBlob(int columnIndex, Blob x) throws SQLException
{
String methodCall = "updateBlob(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateBlob(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Blob getBlob(String colName) throws SQLException
{
String methodCall = "getBlob(" + colName + ")";
try
{
return (Blob) reportReturn(methodCall, realResultSet.getBlob(colName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateBlob(String columnName, Blob x) throws SQLException
{
String methodCall = "updateBlob(" + columnName + ", " + x + ")";
try
{
realResultSet.updateBlob(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Clob getClob(int i) throws SQLException
{
String methodCall = "getClob(" + i + ")";
try
{
return (Clob) reportReturn(methodCall, realResultSet.getClob(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateClob(int columnIndex, Clob x) throws SQLException
{
String methodCall = "updateClob(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateClob(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Clob getClob(String colName) throws SQLException
{
String methodCall = "getClob(" + colName + ")";
try
{
return (Clob) reportReturn(methodCall, realResultSet.getClob(colName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateClob(String columnName, Clob x) throws SQLException
{
String methodCall = "updateClob(" + columnName + ", " + x + ")";
try
{
realResultSet.updateClob(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean getBoolean(int columnIndex) throws SQLException
{
String methodCall = "getBoolean(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getBoolean(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean getBoolean(String columnName) throws SQLException
{
String methodCall = "getBoolean(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getBoolean(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Array getArray(int i) throws SQLException
{
String methodCall = "getArray(" + i + ")";
try
{
return (Array) reportReturn(methodCall, realResultSet.getArray(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateArray(int columnIndex, Array x) throws SQLException
{
String methodCall = "updateArray(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateArray(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Array getArray(String colName) throws SQLException
{
String methodCall = "getArray(" + colName + ")";
try
{
return (Array) reportReturn(methodCall, realResultSet.getArray(colName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateArray(String columnName, Array x) throws SQLException
{
String methodCall = "updateArray(" + columnName + ", " + x + ")";
try
{
realResultSet.updateArray(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public RowId getRowId(int columnIndex) throws SQLException {
String methodCall = "getRowId(" + columnIndex + ")";
try
{
return (RowId) reportReturn(methodCall, realResultSet.getRowId(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public RowId getRowId(String columnLabel) throws SQLException {
String methodCall = "getRowId(" + columnLabel + ")";
try
{
return (RowId) reportReturn(methodCall, realResultSet.getRowId(columnLabel));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateRowId(int columnIndex, RowId x) throws SQLException {
String methodCall = "updateRowId(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateRowId(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateRowId(String columnLabel, RowId x) throws SQLException {
String methodCall = "updateRowId(" + columnLabel + ", " + x + ")";
try
{
realResultSet.updateRowId(columnLabel, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getHoldability() throws SQLException {
String methodCall = "getHoldability()";
try
{
return reportReturn(methodCall, realResultSet.getHoldability());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean isClosed() throws SQLException {
String methodCall = "isClosed()";
try
{
return reportReturn(methodCall, realResultSet.isClosed());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateNString(int columnIndex, String nString) throws SQLException {
String methodCall = "updateNString(" + columnIndex + ", " + nString + ")";
try
{
realResultSet.updateNString(columnIndex, nString);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNString(String columnLabel, String nString) throws SQLException {
String methodCall = "updateNString(" + columnLabel + ", " + nString + ")";
try
{
realResultSet.updateNString(columnLabel, nString);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNClob(int columnIndex, NClob nClob) throws SQLException {
String methodCall = "updateNClob(" + columnIndex + ", " + nClob + ")";
try
{
realResultSet.updateNClob(columnIndex, nClob);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNClob(String columnLabel, NClob nClob) throws SQLException {
String methodCall = "updateNClob(" + columnLabel + ", " + nClob + ")";
try
{
realResultSet.updateNClob(columnLabel, nClob);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public NClob getNClob(int columnIndex) throws SQLException {
String methodCall = "getNClob(" + columnIndex + ")";
try
{
return (NClob) reportReturn(methodCall, realResultSet.getNClob(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public NClob getNClob(String columnLabel) throws SQLException {
String methodCall = "getNClob(" + columnLabel + ")";
try
{
return (NClob) reportReturn(methodCall, realResultSet.getNClob(columnLabel));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public SQLXML getSQLXML(int columnIndex) throws SQLException {
String methodCall = "getSQLXML(" + columnIndex + ")";
try
{
return (SQLXML) reportReturn(methodCall, realResultSet.getSQLXML(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public SQLXML getSQLXML(String columnLabel) throws SQLException {
String methodCall = "getSQLXML(" + columnLabel + ")";
try
{
return (SQLXML) reportReturn(methodCall, realResultSet.getSQLXML(columnLabel));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException {
String methodCall = "updateSQLXML(" + columnIndex + ", " + xmlObject + ")";
try
{
realResultSet.updateSQLXML(columnIndex, xmlObject);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException {
String methodCall = "updateSQLXML(" + columnLabel + ", " + xmlObject + ")";
try
{
realResultSet.updateSQLXML(columnLabel, xmlObject);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public String getNString(int columnIndex) throws SQLException {
String methodCall = "getNString(" + columnIndex + ")";
try
{
return (String) reportReturn(methodCall, realResultSet.getNString(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public String getNString(String columnLabel) throws SQLException {
String methodCall = "getNString(" + columnLabel + ")";
try
{
return (String) reportReturn(methodCall, realResultSet.getNString(columnLabel));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getNCharacterStream(int columnIndex) throws SQLException {
String methodCall = "getNCharacterStream(" + columnIndex + ")";
try
{
return (Reader) reportReturn(methodCall, realResultSet.getNCharacterStream(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getNCharacterStream(String columnLabel) throws SQLException {
String methodCall = "getNCharacterStream(" + columnLabel + ")";
try
{
return (Reader) reportReturn(methodCall, realResultSet.getNCharacterStream(columnLabel));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
String methodCall = "updateNCharacterStream(" + columnIndex + ", " + x + ", " + length + ")";
try
{
realResultSet.updateNCharacterStream(columnIndex, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
String methodCall = "updateNCharacterStream(" + columnLabel + ", " + reader + ", " + length + ")";
try
{
realResultSet.updateNCharacterStream(columnLabel, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException {
String methodCall = "updateAsciiStream(" + columnIndex + ", " + x + ", " + length + ")";
try
{
realResultSet.updateAsciiStream(columnIndex, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException {
String methodCall = "updateBinaryStream(" + columnIndex + ", " + x + ", " + length + ")";
try
{
realResultSet.updateBinaryStream(columnIndex, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
String methodCall = "updateCharacterStream(" + columnIndex + ", " + x + ", " + length + ")";
try
{
realResultSet.updateCharacterStream(columnIndex, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException {
String methodCall = "updateAsciiStream(" + columnLabel + ", " + x + ", " + length + ")";
try
{
realResultSet.updateAsciiStream(columnLabel, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException {
String methodCall = "updateBinaryStream(" + columnLabel + ", " + x + ", " + length + ")";
try
{
realResultSet.updateBinaryStream(columnLabel, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
String methodCall = "updateCharacterStream(" + columnLabel + ", " + reader + ", " + length + ")";
try
{
realResultSet.updateCharacterStream(columnLabel, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException {
String methodCall = "updateBlob(" + columnIndex + ", " + inputStream + ", " + length + ")";
try
{
realResultSet.updateBlob(columnIndex, inputStream, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException {
String methodCall = "updateBlob(" + columnLabel + ", " + inputStream + ", " + length + ")";
try
{
realResultSet.updateBlob(columnLabel, inputStream, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateClob(int columnIndex, Reader reader, long length) throws SQLException {
String methodCall = "updateClob(" + columnIndex + ", " + reader + ", " + length + ")";
try
{
realResultSet.updateClob(columnIndex, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateClob(String columnLabel, Reader reader, long length) throws SQLException {
String methodCall = "updateClob(" + columnLabel + ", " + reader + ", " + length + ")";
try
{
realResultSet.updateClob(columnLabel, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException {
String methodCall = "updateNClob(" + columnIndex + ", " + reader + ", " + length + ")";
try
{
realResultSet.updateNClob(columnIndex, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException {
String methodCall = "updateNClob(" + columnLabel + ", " + reader + ", " + length + ")";
try
{
realResultSet.updateNClob(columnLabel, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNCharacterStream(int columnIndex, Reader reader) throws SQLException {
String methodCall = "updateNCharacterStream(" + columnIndex + ", " + reader + ")";
try
{
realResultSet.updateNCharacterStream(columnIndex, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException {
String methodCall = "updateNCharacterStream(" + columnLabel + ", " + reader + ")";
try
{
realResultSet.updateNCharacterStream(columnLabel, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException {
String methodCall = "updateAsciiStream(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateAsciiStream(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException {
String methodCall = "updateBinaryStream(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateBinaryStream(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateCharacterStream(int columnIndex, Reader x) throws SQLException {
String methodCall = "updateCharacterStream(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateCharacterStream(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException {
String methodCall = "updateAsciiStream(" + columnLabel + ", " + x + ")";
try
{
realResultSet.updateAsciiStream(columnLabel, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException {
String methodCall = "updateBinaryStream(" + columnLabel + ", " + x + ")";
try
{
realResultSet.updateBinaryStream(columnLabel, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException {
String methodCall = "updateCharacterStream(" + columnLabel + ", " + reader + ")";
try
{
realResultSet.updateCharacterStream(columnLabel, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException {
String methodCall = "updateBlob(" + columnIndex + ", " + inputStream + ")";
try
{
realResultSet.updateBlob(columnIndex, inputStream);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException {
String methodCall = "updateBlob(" + columnLabel + ", " + inputStream + ")";
try
{
realResultSet.updateBlob(columnLabel, inputStream);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateClob(int columnIndex, Reader reader) throws SQLException {
String methodCall = "updateClob(" + columnIndex + ", " + reader + ")";
try
{
realResultSet.updateClob(columnIndex, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateClob(String columnLabel, Reader reader) throws SQLException {
String methodCall = "updateClob(" + columnLabel + ", " + reader + ")";
try
{
realResultSet.updateClob(columnLabel, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNClob(int columnIndex, Reader reader) throws SQLException {
String methodCall = "updateNClob(" + columnIndex + ", " + reader + ")";
try
{
realResultSet.updateNClob(columnIndex, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNClob(String columnLabel, Reader reader) throws SQLException {
String methodCall = "updateNClob(" + columnLabel + ", " + reader + ")";
try
{
realResultSet.updateNClob(columnLabel, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean isBeforeFirst() throws SQLException
{
String methodCall = "isBeforeFirst()";
try
{
return reportReturn(methodCall, realResultSet.isBeforeFirst());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public short getShort(int columnIndex) throws SQLException
{
String methodCall = "getShort(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getShort(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public short getShort(String columnName) throws SQLException
{
String methodCall = "getShort(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getShort(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getInt(int columnIndex) throws SQLException
{
String methodCall = "getInt(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getInt(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getInt(String columnName) throws SQLException
{
String methodCall = "getInt(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getInt(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void close() throws SQLException
{
String methodCall = "close()";
try
{
realResultSet.close();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public ResultSetMetaData getMetaData() throws SQLException
{
String methodCall = "getMetaData()";
try
{
return (ResultSetMetaData) reportReturn(methodCall, realResultSet.getMetaData());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getType() throws SQLException
{
String methodCall = "getType()";
try
{
return reportReturn(methodCall, realResultSet.getType());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public double getDouble(int columnIndex) throws SQLException
{
String methodCall = "getDouble(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getDouble(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public double getDouble(String columnName) throws SQLException
{
String methodCall = "getDouble(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getDouble(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void deleteRow() throws SQLException
{
String methodCall = "deleteRow()";
try
{
realResultSet.deleteRow();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getConcurrency() throws SQLException
{
String methodCall = "getConcurrency()";
try
{
return reportReturn(methodCall, realResultSet.getConcurrency());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean rowUpdated() throws SQLException
{
String methodCall = "rowUpdated()";
try
{
return reportReturn(methodCall, realResultSet.rowUpdated());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Date getDate(int columnIndex) throws SQLException
{
String methodCall = "getDate(" + columnIndex + ")";
try
{
return (Date) reportReturn(methodCall, realResultSet.getDate(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Date getDate(String columnName) throws SQLException
{
String methodCall = "getDate(" + columnName + ")";
try
{
return (Date) reportReturn(methodCall, realResultSet.getDate(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Date getDate(int columnIndex, Calendar cal) throws SQLException
{
String methodCall = "getDate(" + columnIndex + ", " + cal + ")";
try
{
return (Date) reportReturn(methodCall, realResultSet.getDate(columnIndex, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Date getDate(String columnName, Calendar cal) throws SQLException
{
String methodCall = "getDate(" + columnName + ", " + cal + ")";
try
{
return (Date) reportReturn(methodCall, realResultSet.getDate(columnName, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean last() throws SQLException
{
String methodCall = "last()";
try
{
return reportReturn(methodCall, realResultSet.last());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean rowInserted() throws SQLException
{
String methodCall = "rowInserted()";
try
{
return reportReturn(methodCall, realResultSet.rowInserted());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean rowDeleted() throws SQLException
{
String methodCall = "rowDeleted()";
try
{
return reportReturn(methodCall, realResultSet.rowDeleted());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateNull(int columnIndex) throws SQLException
{
String methodCall = "updateNull(" + columnIndex + ")";
try
{
realResultSet.updateNull(columnIndex);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateNull(String columnName) throws SQLException
{
String methodCall = "updateNull(" + columnName + ")";
try
{
realResultSet.updateNull(columnName);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateShort(int columnIndex, short x) throws SQLException
{
String methodCall = "updateShort(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateShort(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateShort(String columnName, short x) throws SQLException
{
String methodCall = "updateShort(" + columnName + ", " + x + ")";
try
{
realResultSet.updateShort(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBoolean(int columnIndex, boolean x) throws SQLException
{
String methodCall = "updateBoolean(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateBoolean(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBoolean(String columnName, boolean x) throws SQLException
{
String methodCall = "updateBoolean(" + columnName + ", " + x + ")";
try
{
realResultSet.updateBoolean(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateByte(int columnIndex, byte x) throws SQLException
{
String methodCall = "updateByte(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateByte(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateByte(String columnName, byte x) throws SQLException
{
String methodCall = "updateByte(" + columnName + ", " + x + ")";
try
{
realResultSet.updateByte(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateInt(int columnIndex, int x) throws SQLException
{
String methodCall = "updateInt(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateInt(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateInt(String columnName, int x) throws SQLException
{
String methodCall = "updateInt(" + columnName + ", " + x + ")";
try
{
realResultSet.updateInt(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Object getObject(int columnIndex) throws SQLException
{
String methodCall = "getObject(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getObject(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Object getObject(String columnName) throws SQLException
{
String methodCall = "getObject(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getObject(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Object getObject(String colName, Map map) throws SQLException
{
String methodCall = "getObject(" + colName + ", " + map + ")";
try
{
return reportReturn(methodCall, realResultSet.getObject(colName, map));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean next() throws SQLException
{
String methodCall = "next()";
try
{
return reportReturn(methodCall, realResultSet.next());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateLong(int columnIndex, long x) throws SQLException
{
String methodCall = "updateLong(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateLong(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateLong(String columnName, long x) throws SQLException
{
String methodCall = "updateLong(" + columnName + ", " + x + ")";
try
{
realResultSet.updateLong(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateFloat(int columnIndex, float x) throws SQLException
{
String methodCall = "updateFloat(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateFloat(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateFloat(String columnName, float x) throws SQLException
{
String methodCall = "updateFloat(" + columnName + ", " + x + ")";
try
{
realResultSet.updateFloat(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateDouble(int columnIndex, double x) throws SQLException
{
String methodCall = "updateDouble(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateDouble(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateDouble(String columnName, double x) throws SQLException
{
String methodCall = "updateDouble(" + columnName + ", " + x + ")";
try
{
realResultSet.updateDouble(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Statement getStatement() throws SQLException
{
String methodCall = "getStatement()";
return (Statement) reportReturn(methodCall, parent);
}
public Object getObject(int columnIndex, Map<String, Class<?>> map) throws SQLException
{
String methodCall = "getObject(" + columnIndex + ", " + map + ")";
try
{
return reportReturn(methodCall, realResultSet.getObject(columnIndex, map));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateString(int columnIndex, String x) throws SQLException
{
String methodCall = "updateString(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateString(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateString(String columnName, String x) throws SQLException
{
String methodCall = "updateString(" + columnName + ", " + x + ")";
try
{
realResultSet.updateString(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public InputStream getAsciiStream(int columnIndex) throws SQLException
{
String methodCall = "getAsciiStream(" + columnIndex + ")";
try
{
return (InputStream) reportReturn(methodCall, realResultSet.getAsciiStream(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public InputStream getAsciiStream(String columnName) throws SQLException
{
String methodCall = "getAsciiStream(" + columnName + ")";
try
{
return (InputStream) reportReturn(methodCall, realResultSet.getAsciiStream(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException
{
String methodCall = "updateBigDecimal(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateBigDecimal(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public URL getURL(int columnIndex) throws SQLException
{
String methodCall = "getURL(" + columnIndex + ")";
try
{
return (URL) reportReturn(methodCall, realResultSet.getURL(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException
{
String methodCall = "updateBigDecimal(" + columnName + ", " + x + ")";
try
{
realResultSet.updateBigDecimal(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public URL getURL(String columnName) throws SQLException
{
String methodCall = "getURL(" + columnName + ")";
try
{
return (URL) reportReturn(methodCall, realResultSet.getURL(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateBytes(int columnIndex, byte[] x) throws SQLException
{
// todo: dump array?
String methodCall = "updateBytes(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateBytes(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBytes(String columnName, byte[] x) throws SQLException
{
// todo: dump array?
String methodCall = "updateBytes(" + columnName + ", " + x + ")";
try
{
realResultSet.updateBytes(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
/**
* @deprecated
*/
public InputStream getUnicodeStream(int columnIndex) throws SQLException
{
String methodCall = "getUnicodeStream(" + columnIndex + ")";
try
{
return (InputStream) reportReturn(methodCall, realResultSet.getUnicodeStream(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
/**
* @deprecated
*/
public InputStream getUnicodeStream(String columnName) throws SQLException
{
String methodCall = "getUnicodeStream(" + columnName + ")";
try
{
return (InputStream) reportReturn(methodCall, realResultSet.getUnicodeStream(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateDate(int columnIndex, Date x) throws SQLException
{
String methodCall = "updateDate(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateDate(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateDate(String columnName, Date x) throws SQLException
{
String methodCall = "updateDate(" + columnName + ", " + x + ")";
try
{
realResultSet.updateDate(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getFetchSize() throws SQLException
{
String methodCall = "getFetchSize()";
try
{
return reportReturn(methodCall, realResultSet.getFetchSize());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public SQLWarning getWarnings() throws SQLException
{
String methodCall = "getWarnings()";
try
{
return (SQLWarning) reportReturn(methodCall, realResultSet.getWarnings());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public InputStream getBinaryStream(int columnIndex) throws SQLException
{
String methodCall = "getBinaryStream(" + columnIndex + ")";
try
{
return (InputStream) reportReturn(methodCall, realResultSet.getBinaryStream(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public InputStream getBinaryStream(String columnName) throws SQLException
{
String methodCall = "getBinaryStream(" + columnName + ")";
try
{
return (InputStream) reportReturn(methodCall, realResultSet.getBinaryStream(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void clearWarnings() throws SQLException
{
String methodCall = "clearWarnings()";
try
{
realResultSet.clearWarnings();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException
{
String methodCall = "updateTimestamp(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateTimestamp(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateTimestamp(String columnName, Timestamp x) throws SQLException
{
String methodCall = "updateTimestamp(" + columnName + ", " + x + ")";
try
{
realResultSet.updateTimestamp(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean first() throws SQLException
{
String methodCall = "first()";
try
{
return reportReturn(methodCall, realResultSet.first());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public String getCursorName() throws SQLException
{
String methodCall = "getCursorName()";
try
{
return (String) reportReturn(methodCall, realResultSet.getCursorName());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int findColumn(String columnName) throws SQLException
{
String methodCall = "findColumn(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.findColumn(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean wasNull() throws SQLException
{
String methodCall = "wasNull()";
try
{
return reportReturn(methodCall, realResultSet.wasNull());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException
{
String methodCall = "updateBinaryStream(" + columnIndex + ", " + x + ", " + length + ")";
try
{
realResultSet.updateBinaryStream(columnIndex, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException
{
String methodCall = "updateBinaryStream(" + columnName + ", " + x + ", " + length + ")";
try
{
realResultSet.updateBinaryStream(columnName, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public String getString(int columnIndex) throws SQLException
{
String methodCall = "getString(" + columnIndex + ")";
try
{
return (String) reportReturn(methodCall, realResultSet.getString(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public String getString(String columnName) throws SQLException
{
String methodCall = "getString(" + columnName + ")";
try
{
return (String) reportReturn(methodCall, realResultSet.getString(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getCharacterStream(int columnIndex) throws SQLException
{
String methodCall = "getCharacterStream(" + columnIndex + ")";
try
{
return (Reader) reportReturn(methodCall, realResultSet.getCharacterStream(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getCharacterStream(String columnName) throws SQLException
{
String methodCall = "getCharacterStream(" + columnName + ")";
try
{
return (Reader) reportReturn(methodCall, realResultSet.getCharacterStream(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setFetchDirection(int direction) throws SQLException
{
String methodCall = "setFetchDirection(" + direction + ")";
try
{
realResultSet.setFetchDirection(direction);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException
{
String methodCall = "updateCharacterStream(" + columnIndex + ", " + x + ", " + length + ")";
try
{
realResultSet.updateCharacterStream(columnIndex, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException
{
String methodCall = "updateCharacterStream(" + columnName + ", " + reader + ", " + length + ")";
try
{
realResultSet.updateCharacterStream(columnName, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public byte getByte(int columnIndex) throws SQLException
{
String methodCall = "getByte(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getByte(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public byte getByte(String columnName) throws SQLException
{
String methodCall = "getByte(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getByte(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateTime(int columnIndex, Time x) throws SQLException
{
String methodCall = "updateTime(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateTime(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateTime(String columnName, Time x) throws SQLException
{
String methodCall = "updateTime(" + columnName + ", " + x + ")";
try
{
realResultSet.updateTime(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public byte[] getBytes(int columnIndex) throws SQLException
{
String methodCall = "getBytes(" + columnIndex + ")";
try
{
return (byte[]) reportReturn(methodCall, realResultSet.getBytes(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public byte[] getBytes(String columnName) throws SQLException
{
String methodCall = "getBytes(" + columnName + ")";
try
{
return (byte[]) reportReturn(methodCall, realResultSet.getBytes(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean isAfterLast() throws SQLException
{
String methodCall = "isAfterLast()";
try
{
return reportReturn(methodCall, realResultSet.isAfterLast());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void updateObject(int columnIndex, Object x, int scale) throws SQLException
{
String methodCall = "updateObject(" + columnIndex + ", " + x + ", " + scale + ")";
try
{
realResultSet.updateObject(columnIndex, x, scale);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateObject(int columnIndex, Object x) throws SQLException
{
String methodCall = "updateObject(" + columnIndex + ", " + x + ")";
try
{
realResultSet.updateObject(columnIndex, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateObject(String columnName, Object x, int scale) throws SQLException
{
String methodCall = "updateObject(" + columnName + ", " + x + ", " + scale + ")";
try
{
realResultSet.updateObject(columnName, x, scale);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateObject(String columnName, Object x) throws SQLException
{
String methodCall = "updateObject(" + columnName + ", " + x + ")";
try
{
realResultSet.updateObject(columnName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public int getFetchDirection() throws SQLException
{
String methodCall = "getFetchDirection()";
try
{
return reportReturn(methodCall, realResultSet.getFetchDirection());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public long getLong(int columnIndex) throws SQLException
{
String methodCall = "getLong(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getLong(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public long getLong(String columnName) throws SQLException
{
String methodCall = "getLong(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getLong(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean isFirst() throws SQLException
{
String methodCall = "isFirst()";
try
{
return reportReturn(methodCall, realResultSet.isFirst());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void insertRow() throws SQLException
{
String methodCall = "insertRow()";
try
{
realResultSet.insertRow();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public float getFloat(int columnIndex) throws SQLException
{
String methodCall = "getFloat(" + columnIndex + ")";
try
{
return reportReturn(methodCall, realResultSet.getFloat(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public float getFloat(String columnName) throws SQLException
{
String methodCall = "getFloat(" + columnName + ")";
try
{
return reportReturn(methodCall, realResultSet.getFloat(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean isLast() throws SQLException
{
String methodCall = "isLast()";
try
{
return reportReturn(methodCall, realResultSet.isLast());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setFetchSize(int rows) throws SQLException
{
String methodCall = "setFetchSize(" + rows + ")";
try
{
realResultSet.setFetchSize(rows);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void updateRow() throws SQLException
{
String methodCall = "updateRow()";
try
{
realResultSet.updateRow();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void beforeFirst() throws SQLException
{
String methodCall = "beforeFirst()";
try
{
realResultSet.beforeFirst();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
/**
* @deprecated
*/
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException
{
String methodCall = "getBigDecimal(" + columnIndex + ", " + scale + ")";
try
{
return (BigDecimal) reportReturn(methodCall, realResultSet.getBigDecimal(columnIndex, scale));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
/**
* @deprecated
*/
public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException
{
String methodCall = "getBigDecimal(" + columnName + ", " + scale + ")";
try
{
return (BigDecimal) reportReturn(methodCall, realResultSet.getBigDecimal(columnName, scale));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public BigDecimal getBigDecimal(int columnIndex) throws SQLException
{
String methodCall = "getBigDecimal(" + columnIndex + ")";
try
{
return (BigDecimal) reportReturn(methodCall, realResultSet.getBigDecimal(columnIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public BigDecimal getBigDecimal(String columnName) throws SQLException
{
String methodCall = "getBigDecimal(" + columnName + ")";
try
{
return (BigDecimal) reportReturn(methodCall, realResultSet.getBigDecimal(columnName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void afterLast() throws SQLException
{
String methodCall = "afterLast()";
try
{
realResultSet.afterLast();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void refreshRow() throws SQLException
{
String methodCall = "refreshRow()";
try
{
realResultSet.refreshRow();
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public <T> T unwrap(Class<T> iface) throws SQLException {
String methodCall = "unwrap(" + (iface==null?"null":iface.getName()) + ")";
try
{
//todo: double check this logic
return (T)reportReturn(methodCall, (iface != null && (iface == ResultSet.class || iface == Spy.class))?(T)this:realResultSet.unwrap(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
String methodCall = "isWrapperFor(" + (iface==null?"null":iface.getName()) + ")";
try
{
return reportReturn(methodCall, (iface != null && (iface == ResultSet.class || iface == Spy.class)) ||
realResultSet.isWrapperFor(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
} | zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/ResultSetSpy.java | Java | asf20 | 73,573 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
/**
* RDBMS specifics for the Sql Server DB.
*
* @author Arthur Blake
*/
class SqlServerRdbmsSpecifics extends RdbmsSpecifics
{
SqlServerRdbmsSpecifics()
{
super();
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/SqlServerRdbmsSpecifics.java | Java | asf20 | 839 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.sf.log4jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
/**
* Wraps a CallableStatement and reports method calls, returns and exceptions.
*
* @author Arthur Blake
*/
public class CallableStatementSpy extends PreparedStatementSpy implements CallableStatement
{
protected void reportAllReturns(String methodCall, String msg)
{
log.methodReturned(this, methodCall, msg);
}
/**
* The real underlying CallableStatement that this CallableStatementSpy wraps.
*/
private CallableStatement realCallableStatement;
/**
* Get the real underlying CallableStatement that this CallableStatementSpy wraps.
*
* @return the real underlying CallableStatement.
*/
public CallableStatement getRealCallableStatement()
{
return realCallableStatement;
}
/**
* Create a CallableStatementSpy (JDBC 4 version) to spy upon a CallableStatement.
*
* @param sql The SQL used for this CallableStatement
* @param connectionSpy The ConnectionSpy which produced this CallableStatementSpy
* @param realCallableStatement The real CallableStatement that is being spied upon
*/
public CallableStatementSpy(String sql, ConnectionSpy connectionSpy, CallableStatement realCallableStatement)
{
super(sql, connectionSpy, realCallableStatement);
this.realCallableStatement = realCallableStatement;
}
public String getClassType()
{
return "CallableStatement";
}
// forwarding methods
public Date getDate(int parameterIndex) throws SQLException
{
String methodCall = "getDate(" + parameterIndex + ")";
try
{
return (Date) reportReturn(methodCall, realCallableStatement.getDate(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Date getDate(int parameterIndex, Calendar cal) throws SQLException
{
String methodCall = "getDate(" + parameterIndex + ", " + cal + ")";
try
{
return (Date) reportReturn(methodCall, realCallableStatement.getDate(parameterIndex, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Ref getRef(String parameterName) throws SQLException
{
String methodCall = "getRef(" + parameterName + ")";
try
{
return (Ref) reportReturn(methodCall, realCallableStatement.getRef(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Time getTime(String parameterName) throws SQLException
{
String methodCall = "getTime(" + parameterName + ")";
try
{
return (Time) reportReturn(methodCall, realCallableStatement.getTime(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setTime(String parameterName, Time x) throws SQLException
{
String methodCall = "setTime(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setTime(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Blob getBlob(int i) throws SQLException
{
String methodCall = "getBlob(" + i + ")";
try
{
return (Blob) reportReturn(methodCall, realCallableStatement.getBlob(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Clob getClob(int i) throws SQLException
{
String methodCall = "getClob(" + i + ")";
try
{
return (Clob) reportReturn(methodCall, realCallableStatement.getClob(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Array getArray(int i) throws SQLException
{
String methodCall = "getArray(" + i + ")";
try
{
return (Array) reportReturn(methodCall, realCallableStatement.getArray(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public byte[] getBytes(int parameterIndex) throws SQLException
{
String methodCall = "getBytes(" + parameterIndex + ")";
try
{
return (byte[]) reportReturn(methodCall, realCallableStatement.getBytes(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public double getDouble(int parameterIndex) throws SQLException
{
String methodCall = "getDouble(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getDouble(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getInt(int parameterIndex) throws SQLException
{
String methodCall = "getInt(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getInt(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean wasNull() throws SQLException
{
String methodCall = "wasNull()";
try
{
return reportReturn(methodCall, realCallableStatement.wasNull());
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Time getTime(int parameterIndex) throws SQLException
{
String methodCall = "getTime(" + parameterIndex + ")";
try
{
return (Time) reportReturn(methodCall, realCallableStatement.getTime(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Time getTime(int parameterIndex, Calendar cal) throws SQLException
{
String methodCall = "getTime(" + parameterIndex + ", " + cal + ")";
try
{
return (Time) reportReturn(methodCall, realCallableStatement.getTime(parameterIndex, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Timestamp getTimestamp(String parameterName) throws SQLException
{
String methodCall = "getTimestamp(" + parameterName + ")";
try
{
return (Timestamp) reportReturn(methodCall, realCallableStatement.getTimestamp(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setTimestamp(String parameterName, Timestamp x) throws SQLException
{
String methodCall = "setTimestamp(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setTimestamp(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public String getString(int parameterIndex) throws SQLException
{
String methodCall = "getString(" + parameterIndex + ")";
try
{
return (String) reportReturn(methodCall, realCallableStatement.getString(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException
{
String methodCall = "registerOutParameter(" + parameterIndex + ", " + sqlType + ")";
argTraceSet(parameterIndex, null, "<OUT>");
try
{
realCallableStatement.registerOutParameter(parameterIndex, sqlType);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException
{
String methodCall = "registerOutParameter(" + parameterIndex + ", " + sqlType + ", " + scale + ")";
argTraceSet(parameterIndex, null, "<OUT>");
try
{
realCallableStatement.registerOutParameter(parameterIndex, sqlType, scale);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void registerOutParameter(int paramIndex, int sqlType, String typeName) throws SQLException
{
String methodCall = "registerOutParameter(" + paramIndex + ", " + sqlType + ", " + typeName + ")";
argTraceSet(paramIndex, null, "<OUT>");
try
{
realCallableStatement.registerOutParameter(paramIndex, sqlType, typeName);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public byte getByte(String parameterName) throws SQLException
{
String methodCall = "getByte(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getByte(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public double getDouble(String parameterName) throws SQLException
{
String methodCall = "getDouble(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getDouble(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public float getFloat(String parameterName) throws SQLException
{
String methodCall = "getFloat(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getFloat(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public int getInt(String parameterName) throws SQLException
{
String methodCall = "getInt(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getInt(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public long getLong(String parameterName) throws SQLException
{
String methodCall = "getLong(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getLong(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public short getShort(String parameterName) throws SQLException
{
String methodCall = "getShort(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getShort(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public boolean getBoolean(String parameterName) throws SQLException
{
String methodCall = "getBoolean(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getBoolean(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public byte[] getBytes(String parameterName) throws SQLException
{
String methodCall = "getBytes(" + parameterName + ")";
try
{
return (byte[]) reportReturn(methodCall, realCallableStatement.getBytes(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setByte(String parameterName, byte x) throws SQLException
{
String methodCall = "setByte(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setByte(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setDouble(String parameterName, double x) throws SQLException
{
String methodCall = "setDouble(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setDouble(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setFloat(String parameterName, float x) throws SQLException
{
String methodCall = "setFloat(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setFloat(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void registerOutParameter(String parameterName, int sqlType) throws SQLException
{
String methodCall = "registerOutParameter(" + parameterName + ", " + sqlType + ")";
try
{
realCallableStatement.registerOutParameter(parameterName, sqlType);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setInt(String parameterName, int x) throws SQLException
{
String methodCall = "setInt(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setInt(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNull(String parameterName, int sqlType) throws SQLException
{
String methodCall = "setNull(" + parameterName + ", " + sqlType + ")";
try
{
realCallableStatement.setNull(parameterName, sqlType);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException
{
String methodCall = "registerOutParameter(" + parameterName + ", " + sqlType + ", " + scale + ")";
try
{
realCallableStatement.registerOutParameter(parameterName, sqlType, scale);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setLong(String parameterName, long x) throws SQLException
{
String methodCall = "setLong(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setLong(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setShort(String parameterName, short x) throws SQLException
{
String methodCall = "setShort(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setShort(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setBoolean(String parameterName, boolean x) throws SQLException
{
String methodCall = "setBoolean(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setBoolean(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setBytes(String parameterName, byte[] x) throws SQLException
{
//todo: dump byte array?
String methodCall = "setBytes(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setBytes(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public boolean getBoolean(int parameterIndex) throws SQLException
{
String methodCall = "getBoolean(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getBoolean(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Timestamp getTimestamp(int parameterIndex) throws SQLException
{
String methodCall = "getTimestamp(" + parameterIndex + ")";
try
{
return (Timestamp) reportReturn(methodCall, realCallableStatement.getTimestamp(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException
{
String methodCall = "setAsciiStream(" + parameterName + ", " + x + ", " + length + ")";
try
{
realCallableStatement.setAsciiStream(parameterName, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException
{
String methodCall = "setBinaryStream(" + parameterName + ", " + x + ", " + length + ")";
try
{
realCallableStatement.setBinaryStream(parameterName, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException
{
String methodCall = "setCharacterStream(" + parameterName + ", " + reader + ", " + length + ")";
try
{
realCallableStatement.setCharacterStream(parameterName, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Object getObject(String parameterName) throws SQLException
{
String methodCall = "getObject(" + parameterName + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getObject(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setObject(String parameterName, Object x) throws SQLException
{
String methodCall = "setObject(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setObject(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException
{
String methodCall = "setObject(" + parameterName + ", " + x + ", " + targetSqlType + ")";
try
{
realCallableStatement.setObject(parameterName, x, targetSqlType);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException
{
String methodCall = "setObject(" + parameterName + ", " + x + ", " + targetSqlType + ", " + scale + ")";
try
{
realCallableStatement.setObject(parameterName, x, targetSqlType, scale);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException
{
String methodCall = "getTimestamp(" + parameterIndex + ", " + cal + ")";
try
{
return (Timestamp) reportReturn(methodCall, realCallableStatement.getTimestamp(parameterIndex, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Date getDate(String parameterName, Calendar cal) throws SQLException
{
String methodCall = "getDate(" + parameterName + ", " + cal + ")";
try
{
return (Date) reportReturn(methodCall, realCallableStatement.getDate(parameterName, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Time getTime(String parameterName, Calendar cal) throws SQLException
{
String methodCall = "getTime(" + parameterName + ", " + cal + ")";
try
{
return (Time) reportReturn(methodCall, realCallableStatement.getTime(parameterName, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException
{
String methodCall = "getTimestamp(" + parameterName + ", " + cal + ")";
try
{
return (Timestamp) reportReturn(methodCall, realCallableStatement.getTimestamp(parameterName, cal));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setDate(String parameterName, Date x, Calendar cal) throws SQLException
{
String methodCall = "setDate(" + parameterName + ", " + x + ", " + cal + ")";
try
{
realCallableStatement.setDate(parameterName, x, cal);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setTime(String parameterName, Time x, Calendar cal) throws SQLException
{
String methodCall = "setTime(" + parameterName + ", " + x + ", " + cal + ")";
try
{
realCallableStatement.setTime(parameterName, x, cal);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException
{
String methodCall = "setTimestamp(" + parameterName + ", " + x + ", " + cal + ")";
try
{
realCallableStatement.setTimestamp(parameterName, x, cal);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public short getShort(int parameterIndex) throws SQLException
{
String methodCall = "getShort(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getShort(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public long getLong(int parameterIndex) throws SQLException
{
String methodCall = "getLong(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getLong(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public float getFloat(int parameterIndex) throws SQLException
{
String methodCall = "getFloat(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getFloat(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Ref getRef(int i) throws SQLException
{
String methodCall = "getRef(" + i + ")";
try
{
return (Ref) reportReturn(methodCall, realCallableStatement.getRef(i));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
/**
* @deprecated
*/
public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException
{
String methodCall = "getBigDecimal(" + parameterIndex + ", " + scale + ")";
try
{
return (BigDecimal) reportReturn(methodCall, realCallableStatement.getBigDecimal(parameterIndex, scale));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public URL getURL(int parameterIndex) throws SQLException
{
String methodCall = "getURL(" + parameterIndex + ")";
try
{
return (URL) reportReturn(methodCall, realCallableStatement.getURL(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public BigDecimal getBigDecimal(int parameterIndex) throws SQLException
{
String methodCall = "getBigDecimal(" + parameterIndex + ")";
try
{
return (BigDecimal) reportReturn(methodCall, realCallableStatement.getBigDecimal(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public byte getByte(int parameterIndex) throws SQLException
{
String methodCall = "getByte(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getByte(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Object getObject(int parameterIndex) throws SQLException
{
String methodCall = "getObject(" + parameterIndex + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getObject(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Object getObject(int i, Map map) throws SQLException
{
String methodCall = "getObject(" + i + ", " + map + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getObject(i, map));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public String getString(String parameterName) throws SQLException
{
String methodCall = "getString(" + parameterName + ")";
try
{
return (String) reportReturn(methodCall, realCallableStatement.getString(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException
{
String methodCall = "registerOutParameter(" + parameterName + ", " + sqlType + ", " + typeName + ")";
try
{
realCallableStatement.registerOutParameter(parameterName, sqlType, typeName);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNull(String parameterName, int sqlType, String typeName) throws SQLException
{
String methodCall = "setNull(" + parameterName + ", " + sqlType + ", " + typeName + ")";
try
{
realCallableStatement.setNull(parameterName, sqlType, typeName);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setString(String parameterName, String x) throws SQLException
{
String methodCall = "setString(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setString(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public BigDecimal getBigDecimal(String parameterName) throws SQLException
{
String methodCall = "getBigDecimal(" + parameterName + ")";
try
{
return (BigDecimal) reportReturn(methodCall, realCallableStatement.getBigDecimal(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Object getObject(String parameterName, Map<String, Class<?>> map) throws SQLException {
String methodCall = "getObject(" + parameterName + ", " + map + ")";
try
{
return reportReturn(methodCall, realCallableStatement.getObject(parameterName, map));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException
{
String methodCall = "setBigDecimal(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setBigDecimal(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public URL getURL(String parameterName) throws SQLException
{
String methodCall = "getURL(" + parameterName + ")";
try
{
return (URL) reportReturn(methodCall, realCallableStatement.getURL(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public RowId getRowId(int parameterIndex) throws SQLException {
String methodCall = "getRowId(" + parameterIndex + ")";
try
{
return (RowId) reportReturn(methodCall, realCallableStatement.getRowId(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public RowId getRowId(String parameterName) throws SQLException {
String methodCall = "getRowId(" + parameterName + ")";
try
{
return (RowId) reportReturn(methodCall, realCallableStatement.getRowId(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setRowId(String parameterName, RowId x) throws SQLException {
String methodCall = "setRowId(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setRowId(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNString(String parameterName, String value) throws SQLException {
String methodCall = "setNString(" + parameterName + ", " + value + ")";
try
{
realCallableStatement.setNString(parameterName, value);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNCharacterStream(String parameterName, Reader reader, long length) throws SQLException {
String methodCall = "setNCharacterStream(" + parameterName + ", " + reader + ", " + length + ")";
try
{
realCallableStatement.setNCharacterStream(parameterName, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNClob(String parameterName, NClob value) throws SQLException {
String methodCall = "setNClob(" + parameterName + ", " + value + ")";
try
{
realCallableStatement.setNClob(parameterName, value);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setClob(String parameterName, Reader reader, long length) throws SQLException {
String methodCall = "setClob(" + parameterName + ", " + reader + ", " + length + ")";
try
{
realCallableStatement.setClob(parameterName, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException {
String methodCall = "setBlob(" + parameterName + ", " + inputStream + ", " + length + ")";
try
{
realCallableStatement.setBlob(parameterName, inputStream, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNClob(String parameterName, Reader reader, long length) throws SQLException {
String methodCall = "setNClob(" + parameterName + ", " + reader + ", " + length + ")";
try
{
realCallableStatement.setNClob(parameterName, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public NClob getNClob(int parameterIndex) throws SQLException {
String methodCall = "getNClob(" + parameterIndex + ")";
try
{
return (NClob) reportReturn(methodCall, realCallableStatement.getNClob(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public NClob getNClob(String parameterName) throws SQLException {
String methodCall = "getNClob(" + parameterName + ")";
try
{
return (NClob) reportReturn(methodCall, realCallableStatement.getNClob(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException {
String methodCall = "setSQLXML(" + parameterName + ", " + xmlObject + ")";
try
{
realCallableStatement.setSQLXML(parameterName, xmlObject);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public SQLXML getSQLXML(int parameterIndex) throws SQLException {
String methodCall = "getSQLXML(" + parameterIndex + ")";
try
{
return (SQLXML) reportReturn(methodCall, realCallableStatement.getSQLXML(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public SQLXML getSQLXML(String parameterName) throws SQLException {
String methodCall = "getSQLXML(" + parameterName + ")";
try
{
return (SQLXML) reportReturn(methodCall, realCallableStatement.getSQLXML(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public String getNString(int parameterIndex) throws SQLException {
String methodCall = "getNString(" + parameterIndex + ")";
try
{
return (String) reportReturn(methodCall, realCallableStatement.getNString(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public String getNString(String parameterName) throws SQLException {
String methodCall = "getNString(" + parameterName + ")";
try
{
return (String) reportReturn(methodCall, realCallableStatement.getNString(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getNCharacterStream(int parameterIndex) throws SQLException {
String methodCall = "getNCharacterStream(" + parameterIndex + ")";
try
{
return (Reader) reportReturn(methodCall, realCallableStatement.getNCharacterStream(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getNCharacterStream(String parameterName) throws SQLException {
String methodCall = "getNCharacterStream(" + parameterName + ")";
try
{
return (Reader) reportReturn(methodCall, realCallableStatement.getNCharacterStream(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getCharacterStream(int parameterIndex) throws SQLException {
String methodCall = "getCharacterStream(" + parameterIndex + ")";
try
{
return (Reader) reportReturn(methodCall, realCallableStatement.getCharacterStream(parameterIndex));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Reader getCharacterStream(String parameterName) throws SQLException {
String methodCall = "getCharacterStream(" + parameterName + ")";
try
{
return (Reader) reportReturn(methodCall, realCallableStatement.getCharacterStream(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setBlob(String parameterName, Blob x) throws SQLException {
String methodCall = "setBlob(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setBlob(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setClob(String parameterName, Clob x) throws SQLException {
String methodCall = "setClob(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setClob(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException {
String methodCall = "setAsciiStream(" + parameterName + ", " + x + ", " + length + ")";
try
{
realCallableStatement.setAsciiStream(parameterName, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException {
String methodCall = "setBinaryStream(" + parameterName + ", " + x + ", " + length + ")";
try
{
realCallableStatement.setBinaryStream(parameterName, x, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException {
String methodCall = "setCharacterStream(" + parameterName + ", " + reader + ", " + length + ")";
try
{
realCallableStatement.setCharacterStream(parameterName, reader, length);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setAsciiStream(String parameterName, InputStream x) throws SQLException {
String methodCall = "setAsciiStream(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setAsciiStream(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setBinaryStream(String parameterName, InputStream x) throws SQLException {
String methodCall = "setBinaryStream(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setBinaryStream(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setCharacterStream(String parameterName, Reader reader) throws SQLException {
String methodCall = "setCharacterStream(" + parameterName + ", " + reader + ")";
try
{
realCallableStatement.setCharacterStream(parameterName, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNCharacterStream(String parameterName, Reader reader) throws SQLException {
String methodCall = "setNCharacterStream(" + parameterName + ", " + reader + ")";
try
{
realCallableStatement.setNCharacterStream(parameterName, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setClob(String parameterName, Reader reader) throws SQLException {
String methodCall = "setClob(" + parameterName + ", " + reader + ")";
try
{
realCallableStatement.setClob(parameterName, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setBlob(String parameterName, InputStream inputStream) throws SQLException {
String methodCall = "setBlob(" + parameterName + ", " + inputStream + ")";
try
{
realCallableStatement.setBlob(parameterName, inputStream);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setNClob(String parameterName, Reader reader) throws SQLException {
String methodCall = "setNClob(" + parameterName + ", " + reader + ")";
try
{
realCallableStatement.setNClob(parameterName, reader);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public void setURL(String parameterName, URL val) throws SQLException
{
String methodCall = "setURL(" + parameterName + ", " + val + ")";
try
{
realCallableStatement.setURL(parameterName, val);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public Array getArray(String parameterName) throws SQLException
{
String methodCall = "getArray(" + parameterName + ")";
try
{
return (Array) reportReturn(methodCall, realCallableStatement.getArray(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Blob getBlob(String parameterName) throws SQLException
{
String methodCall = "getBlob(" + parameterName + ")";
try
{
return (Blob) reportReturn(methodCall, realCallableStatement.getBlob(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Clob getClob(String parameterName) throws SQLException
{
String methodCall = "getClob(" + parameterName + ")";
try
{
return (Clob) reportReturn(methodCall, realCallableStatement.getClob(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public Date getDate(String parameterName) throws SQLException
{
String methodCall = "getDate(" + parameterName + ")";
try
{
return (Date) reportReturn(methodCall, realCallableStatement.getDate(parameterName));
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
}
public void setDate(String parameterName, Date x) throws SQLException
{
String methodCall = "setDate(" + parameterName + ", " + x + ")";
try
{
realCallableStatement.setDate(parameterName, x);
}
catch (SQLException s)
{
reportException(methodCall, s);
throw s;
}
reportReturn(methodCall);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
String methodCall = "unwrap(" + (iface==null?"null":iface.getName()) + ")";
try
{
//todo: double check this logic
//NOTE: could call super.isWrapperFor to simplify this logic, but it would result in extra log output
//because the super classes would be invoked, thus executing their logging methods too...
return (T)reportReturn(methodCall,
(iface != null && (iface == CallableStatement.class||iface==PreparedStatement.class||
iface==Statement.class||iface==Spy.class))?
(T)this:
realCallableStatement.unwrap(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
String methodCall = "isWrapperFor(" + (iface==null?"null":iface.getName()) + ")";
try
{
//NOTE: could call super.isWrapperFor to simplify this logic, but it would result in extra log output
//when the super classes would be invoked..
return reportReturn(methodCall,
(iface != null && (iface == CallableStatement.class||iface==PreparedStatement.class||iface==Statement.class||iface==Spy.class)) ||
realCallableStatement.isWrapperFor(iface));
}
catch (SQLException s)
{
reportException(methodCall,s);
throw s;
}
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/CallableStatementSpy.java | Java | asf20 | 45,983 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
* Encapsulate sql formatting details about a particular relational database management system so that
* accurate, useable SQL can be composed for that RDMBS.
*
* @author Arthur Blake
*/
class RdbmsSpecifics
{
/**
* Default constructor.
*/
RdbmsSpecifics()
{
}
protected static final String dateFormat = "MM/dd/yyyy HH:mm:ss.SSS";
/**
* Format an Object that is being bound to a PreparedStatement parameter, for display. The goal is to reformat the
* object in a format that can be re-run against the native SQL client of the particular Rdbms being used. This
* class should be extended to provide formatting instances that format objects correctly for different RDBMS
* types.
*
* @param object jdbc object to be formatted.
* @return formatted dump of the object.
*/
String formatParameterObject(Object object)
{
if (object == null)
{
return "NULL";
}
else
{
if (object instanceof String)
{
return "'" + escapeString((String)object) + "'";
}
else if (object instanceof Date)
{
return "'" + new SimpleDateFormat(dateFormat).format(object) + "'";
}
else if (object instanceof Boolean)
{
return DriverSpy.DumpBooleanAsTrueFalse?
((Boolean)object).booleanValue()?"true":"false"
:((Boolean)object).booleanValue()?"1":"0";
}
else
{
return object.toString();
}
}
}
/**
* Make sure string is escaped properly so that it will run in a SQL query analyzer tool.
* At this time all we do is double any single tick marks.
* Do not call this with a null string or else an exception will occur.
*
* @return the input String, escaped.
*/
String escapeString(String in)
{
StringBuilder out = new StringBuilder();
for (int i=0, j=in.length(); i < j; i++)
{
char c = in.charAt(i);
if (c == '\'')
{
out.append(c);
}
out.append(c);
}
return out.toString();
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/RdbmsSpecifics.java | Java | asf20 | 2,829 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
import java.text.SimpleDateFormat;
/**
* RDBMS specifics for the MySql db.
*
* @author Arthur Blake
*/
class MySqlRdbmsSpecifics extends RdbmsSpecifics
{
MySqlRdbmsSpecifics()
{
super();
}
String formatParameterObject(Object object)
{
if (object instanceof java.sql.Time)
{
return "'" + new SimpleDateFormat("HH:mm:ss").format(object) + "'";
}
else if (object instanceof java.sql.Date)
{
return "'" + new SimpleDateFormat("yyyy-MM-dd").format(object) + "'";
}
else if (object instanceof java.util.Date) // (includes java.sql.Timestamp)
{
return "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object) + "'";
}
else
{
return super.formatParameterObject(object);
}
}
} | zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/MySqlRdbmsSpecifics.java | Java | asf20 | 1,447 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
/**
* Delegates Spy events to a logger.
* This interface is used for all logging activity used by log4jdbc and hides the specific implementation
* of any given logging system from log4jdbc.
*
* @author Arthur Blake
*/
public interface SpyLogDelegator
{
/**
* Determine if any of the jdbc or sql loggers are turned on.
*
* @return true if any of the jdbc or sql loggers are enabled at error level or higher.
*/
public boolean isJdbcLoggingEnabled();
/**
* Called when a spied upon method throws an Exception.
*
* @param spy the Spy wrapping the class that threw an Exception.
* @param methodCall a description of the name and call parameters of the method generated the Exception.
* @param e the Exception that was thrown.
* @param sql optional sql that occured just before the exception occured.
* @param execTime optional amount of time that passed before an exception was thrown when sql was being executed.
* caller should pass -1 if not used
*/
public void exceptionOccured(Spy spy, String methodCall, Exception e, String sql, long execTime);
/**
* Called when spied upon method call returns.
*
* @param spy the Spy wrapping the class that called the method that returned.
* @param methodCall a description of the name and call parameters of the method that returned.
* @param returnMsg return value converted to a String for integral types, or String representation for Object
* return types this will be null for void return types.
*/
public void methodReturned(Spy spy, String methodCall, String returnMsg);
/**
* Called when a spied upon object is constructed.
*
* @param spy the Spy wrapping the class that called the method that returned.
* @param constructionInfo information about the object construction
*/
public void constructorReturned(Spy spy, String constructionInfo);
/**
* Special call that is called only for JDBC method calls that contain SQL.
*
* @param spy the Spy wrapping the class where the SQL occured.
* @param methodCall a description of the name and call parameters of the method that generated the SQL.
* @param sql sql that occured.
*/
public void sqlOccured(Spy spy, String methodCall, String sql);
/**
* Similar to sqlOccured, but reported after SQL executes and used to report timing stats on the SQL
*
* @param spy the Spy wrapping the class where the SQL occured.
* @param execTime how long it took the sql to run, in msec.
* @param methodCall a description of the name and call parameters of the method that generated the SQL.
* @param sql sql that occured.
*/
public void sqlTimingOccured(Spy spy, long execTime, String methodCall, String sql);
/**
* Called whenever a new connection spy is created.
*
* @param spy ConnectionSpy that was created.
*/
public void connectionOpened(Spy spy);
/**
* Called whenever a connection spy is closed.
*
* @param spy ConnectionSpy that was closed.
*/
public void connectionClosed(Spy spy);
/**
* Log a Setup and/or administrative log message for log4jdbc.
*
* @param msg message to log.
*/
public void debug(String msg);
} | zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/SpyLogDelegator.java | Java | asf20 | 4,040 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
/**
* Common interface that all Spy classes can implement.
* This is used so that any class that is being spied upon can transmit generic information about
* itself to the whoever is doing the spying.
*
* @author Arthur Blake
*/
public interface Spy
{
/**
* Get the type of class being spied upon. For example, "Statement", "ResultSet", etc.
*
* @return a description of the type of class being spied upon.
*/
public String getClassType();
/**
* Get the connection number. In general, this is used to track which underlying connection is being
* used from the database. The number will be incremented each time a new Connection is retrieved from the
* real underlying jdbc driver. This is useful for debugging and tracking down problems with connection pooling.
*
* @return the connection instance number.
*/
public Integer getConnectionNumber();
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/Spy.java | Java | asf20 | 1,569 |
/**
* Copyright 2007-2012 Arthur Blake
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.log4jdbc;
/**
* Static utility methods for use throughout the project.
*/
public class Utilities {
/**
* Right justify a field within a certain number of spaces.
* @param fieldSize field size to right justify field within.
* @param field contents to right justify within field.
* @return the field, right justified within the requested size.
*/
public static String rightJustify(int fieldSize, String field)
{
if (field==null)
{
field="";
}
StringBuffer output = new StringBuffer();
for (int i=0, j = fieldSize-field.length(); i < j; i++)
{
output.append(' ');
}
output.append(field);
return output.toString();
}
}
| zyyeasy-log4jdbc-v1 | src-jdbc4/net/sf/log4jdbc/Utilities.java | Java | asf20 | 1,349 |