Browse Source

Pull request #1732: 无jira 询问了richie,先回滚

Merge in DESIGN/design from ~BRYANT/design:release/10.0 to release/10.0

* commit '62247e4fde42ebc2b67fe906a51977afbe8796e9':
  无jira 询问了richie,先回滚
feature/big-screen
Bryant 5 years ago
parent
commit
d48dd295c0
  1. 18
      designer-base/src/main/java/com/fr/design/dcm/UniversalDatabasePane.java
  2. 12
      designer-base/src/main/java/com/fr/design/dcm/UniversalDcmBridge.java
  3. 68
      designer-base/src/main/java/com/fr/design/ui/Assistant.java
  4. 130
      designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java
  5. 147
      designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java
  6. 85
      designer-base/src/main/java/com/fr/design/ui/NxComplexInterceptRequestCallback.java
  7. 134
      designer-base/src/main/java/com/fr/design/ui/NxInterceptRequestCallback.java
  8. 228
      designer-base/src/main/java/com/fr/design/upm/UpmBridge.java
  9. 4
      designer-base/src/main/java/com/fr/design/upm/UpmFinder.java
  10. 15
      designer-base/src/main/java/com/fr/design/upm/UpmShowPane.java
  11. 15
      designer-base/src/main/java/com/fr/design/upm/exec/UpmBrowserExecutor.java
  12. 4
      pom.xml

18
designer-base/src/main/java/com/fr/design/dcm/UniversalDatabasePane.java

@ -2,8 +2,9 @@ package com.fr.design.dcm;
import com.fr.design.dialog.BasicPane; import com.fr.design.dialog.BasicPane;
import com.fr.design.ui.ModernUIPane; import com.fr.design.ui.ModernUIPane;
import com.teamdev.jxbrowser.browser.callback.InjectJsCallback; import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.js.JsObject; import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter;
import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent;
import java.awt.*; import java.awt.*;
@ -25,13 +26,14 @@ public class UniversalDatabasePane extends BasicPane {
setLayout(new BorderLayout()); setLayout(new BorderLayout());
modernUIPane = new ModernUIPane.Builder<>() modernUIPane = new ModernUIPane.Builder<>()
.withComponent(UniversalDatabaseComponent.KEY) .withComponent(UniversalDatabaseComponent.KEY)
.prepare(params -> { .prepare(new ScriptContextAdapter() {
JsObject window = params.frame().executeJavaScript("window"); @Override
if (window != null) { public void onScriptContextCreated(ScriptContextEvent event) {
window.putProperty("DcmHelper", UniversalDcmBridge.getBridge()); JSValue window = event.getBrowser().executeJavaScriptAndReturnValue("window");
window.asObject().setProperty("DcmHelper", UniversalDcmBridge.getBridge(event.getBrowser()));
} }
return InjectJsCallback.Response.proceed(); })
}).build(); .build();
add(modernUIPane, BorderLayout.CENTER); add(modernUIPane, BorderLayout.CENTER);
} }
} }

12
designer-base/src/main/java/com/fr/design/dcm/UniversalDcmBridge.java

@ -2,6 +2,8 @@ package com.fr.design.dcm;
import com.fr.decision.webservice.bean.BaseBean; import com.fr.decision.webservice.bean.BaseBean;
import com.fr.design.bridge.exec.JSBridge; import com.fr.design.bridge.exec.JSBridge;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSObject;
/** /**
* @author richie * @author richie
@ -11,18 +13,18 @@ import com.fr.design.bridge.exec.JSBridge;
*/ */
public class UniversalDcmBridge { public class UniversalDcmBridge {
public static UniversalDcmBridge getBridge() { public static UniversalDcmBridge getBridge(Browser browser) {
return new UniversalDcmBridge(); return new UniversalDcmBridge(browser);
} }
private JSObject window;
private UniversalDcmBridge() { private UniversalDcmBridge(Browser browser) {
this.window = browser.executeJavaScriptAndReturnValue("window").asObject();
} }
/** /**
* 获取所有的数据连接 * 获取所有的数据连接
*
* @return 数据连接集合 * @return 数据连接集合
*/ */
@JSBridge @JSBridge

68
designer-base/src/main/java/com/fr/design/ui/Assistant.java

@ -0,0 +1,68 @@
package com.fr.design.ui;
import com.fr.stable.StringUtils;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.ProtocolService;
import com.teamdev.jxbrowser.chromium.URLResponse;
import javax.activation.MimetypesFileTypeMap;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author richie
* @version 10.0
* Created by richie on 2019-03-07
*/
public class Assistant {
public static URLResponse inputStream2Response(InputStream inputStream, String filePath) throws Exception {
URLResponse response = new URLResponse();
DataInputStream stream = new DataInputStream(inputStream);
byte[] data = new byte[stream.available()];
stream.readFully(data);
response.setData(data);
String mimeType = getMimeType(filePath);
response.getHeaders().setHeader("Content-Type", mimeType);
return response;
}
private static String getMimeType(String path) {
if (StringUtils.isBlank(path)) {
return "text/html";
}
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
if (path.endsWith(".svg")) {
return "image/svg+xml";
}
Path file = new File(path).toPath();
try {
return Files.probeContentType(file);
} catch (IOException e) {
return "text/html";
}
}
public static void setEmbProtocolHandler(Browser browser, EmbProtocolHandler handler) {
BrowserContext browserContext = browser.getContext();
ProtocolService protocolService = browserContext.getProtocolService();
// 支持读取jar包中文件的自定义协议————emb:/com/fr/design/images/bbs.png
protocolService.setProtocolHandler("emb", handler);
protocolService.setProtocolHandler("file", handler);
}
}

130
designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java

@ -0,0 +1,130 @@
package com.fr.design.ui;
import com.fr.base.TemplateUtils;
import com.fr.general.IOUtils;
import com.fr.log.FineLoggerFactory;
import com.fr.stable.EncodeConstants;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.commons.codec.net.URLCodec;
import com.fr.third.org.apache.commons.io.FileUtils;
import com.fr.third.org.apache.commons.io.FilenameUtils;
import com.fr.web.struct.AssembleComponent;
import com.fr.web.struct.AtomBuilder;
import com.fr.web.struct.PathGroup;
import com.fr.web.struct.category.ScriptPath;
import com.fr.web.struct.category.StylePath;
import com.teamdev.jxbrowser.chromium.ProtocolHandler;
import com.teamdev.jxbrowser.chromium.URLRequest;
import com.teamdev.jxbrowser.chromium.URLResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author richie
* @version 10.0
* Created by richie on 2019-03-07
*/
public class EmbProtocolHandler implements ProtocolHandler {
private AssembleComponent component;
private Map<String, String> map;
public EmbProtocolHandler() {
}
public EmbProtocolHandler(AssembleComponent component) {
this.component = component;
}
public EmbProtocolHandler(AssembleComponent component, Map<String, String> map) {
this.component = component;
this.map = map;
}
public EmbProtocolHandler(Map<String, String> map) {
this.map = map;
}
@Override
public URLResponse onRequest(URLRequest req) {
InputStream inputStream = null;
try {
String path = req.getURL();
if (path.startsWith("file:")) {
String url = new URLCodec().decode(path);
String filePath = TemplateUtils.renderParameter4Tpl(url, map);
File file = new File(URI.create(filePath).getPath());
inputStream = IOUtils.readResource(file.getAbsolutePath());
String text = IOUtils.inputStream2String(inputStream, EncodeConstants.ENCODING_UTF_8);
text = TemplateUtils.renderParameter4Tpl(text, map);
return Assistant.inputStream2Response(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), path);
} else if (path.startsWith("emb:dynamic")) {
URLResponse response = new URLResponse();
response.setData(htmlText(map).getBytes());
response.getHeaders().setHeader("Content-Type", "text/html");
return response;
} else {
int index = path.indexOf("=");
if (index > 0) {
path = path.substring(index + 1);
} else {
path = path.substring(4);
}
inputStream = IOUtils.readResource(path);
return Assistant.inputStream2Response(inputStream, path);
}
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
}
return null;
}
private String htmlText(Map<String, String> map) {
PathGroup pathGroup = AtomBuilder.create().buildAssembleFilePath(ModernRequestClient.KEY, component);
StylePath[] stylePaths = pathGroup.toStylePathGroup();
StringBuilder styleText = new StringBuilder();
for (StylePath path : stylePaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
styleText.append("<link rel=\"stylesheet\" href=\"emb:");
styleText.append(path.toFilePath());
styleText.append("\"/>");
}
}
String result = ModernUIConstants.HTML_TPL.replaceAll("##style##", styleText.toString());
ScriptPath[] scriptPaths = pathGroup.toScriptPathGroup();
StringBuilder scriptText = new StringBuilder();
for (ScriptPath path : scriptPaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
scriptText.append("<script src=\"emb:");
scriptText.append(path.toFilePath());
scriptText.append("\"></script>");
}
}
result = result.replaceAll("##script##", scriptText.toString());
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
result = result.replaceAll("\\$\\{" + key + "}", value);
}
}
return result;
}
}

147
designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java

@ -7,18 +7,21 @@ import com.fr.design.gui.itoolbar.UIToolbar;
import com.fr.design.i18n.Toolkit; import com.fr.design.i18n.Toolkit;
import com.fr.design.utils.gui.GUICoreUtils; import com.fr.design.utils.gui.GUICoreUtils;
import com.fr.web.struct.AssembleComponent; import com.fr.web.struct.AssembleComponent;
import com.teamdev.jxbrowser.browser.Browser; import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.browser.callback.InjectJsCallback; import com.teamdev.jxbrowser.chromium.BrowserPreferences;
import com.teamdev.jxbrowser.engine.Engine; import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.engine.EngineOptions; import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.engine.RenderingMode; import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.js.JsObject; import com.teamdev.jxbrowser.chromium.events.LoadListener;
import com.teamdev.jxbrowser.net.Network; import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter;
import com.teamdev.jxbrowser.net.callback.InterceptRequestCallback; import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent;
import com.teamdev.jxbrowser.view.swing.BrowserView; import com.teamdev.jxbrowser.chromium.events.ScriptContextListener;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map; import java.util.Map;
/** /**
@ -39,8 +42,9 @@ public class ModernUIPane<T> extends BasicPane {
} }
private void initialize() { private void initialize() {
setLayout(new BorderLayout());
if (browser == null) { if (browser == null) {
setLayout(new BorderLayout());
BrowserPreferences.setChromiumSwitches("--disable-google-traffic");
if (DesignerEnvManager.getEnvManager().isOpenDebug()) { if (DesignerEnvManager.getEnvManager().isOpenDebug()) {
UIToolbar toolbar = new UIToolbar(); UIToolbar toolbar = new UIToolbar();
add(toolbar, BorderLayout.NORTH); add(toolbar, BorderLayout.NORTH);
@ -51,67 +55,75 @@ public class ModernUIPane<T> extends BasicPane {
UIButton closeButton = new UIButton(Toolkit.i18nText("Fine-Design_Basic_Close_Window")); UIButton closeButton = new UIButton(Toolkit.i18nText("Fine-Design_Basic_Close_Window"));
toolbar.add(closeButton); toolbar.add(closeButton);
openDebugButton.addActionListener(e -> showDebuggerDialog()); openDebugButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showDebuggerDialog();
}
});
reloadButton.addActionListener(e -> browser.navigation().reloadIgnoringCache()); reloadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
browser.reloadIgnoringCache();
}
});
closeButton.addActionListener(e -> SwingUtilities.getWindowAncestor(ModernUIPane.this).setVisible(false)); closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(ModernUIPane.this).setVisible(false);
}
});
BrowserPreferences.setChromiumSwitches("--remote-debugging-port=9222");
initializeBrowser(); initializeBrowser();
add(BrowserView.newInstance(browser), BorderLayout.CENTER); add(new BrowserView(browser), BorderLayout.CENTER);
} else { } else {
initializeBrowser(); initializeBrowser();
add(BrowserView.newInstance(browser), BorderLayout.CENTER); add(new BrowserView(browser), BorderLayout.CENTER);
} }
} }
} }
private void showDebuggerDialog() { private void showDebuggerDialog() {
JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(this)); JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(this));
Engine engine = Engine.newInstance( Browser debugger = new Browser();
EngineOptions.newBuilder(RenderingMode.HARDWARE_ACCELERATED) BrowserView debuggerView = new BrowserView(debugger);
.addSwitch("--disable-google-traffic")
.remoteDebuggingPort(9222).build());
Browser debugger = engine.newBrowser();
BrowserView debuggerView = BrowserView.newInstance(debugger);
dialog.add(debuggerView, BorderLayout.CENTER); dialog.add(debuggerView, BorderLayout.CENTER);
dialog.setSize(new Dimension(800, 400)); dialog.setSize(new Dimension(800, 400));
GUICoreUtils.centerWindow(dialog); GUICoreUtils.centerWindow(dialog);
dialog.setVisible(true); dialog.setVisible(true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
browser.devTools().remoteDebuggingUrl().ifPresent(url -> { debugger.loadURL(browser.getRemoteDebuggingURL());
debugger.navigation().loadUrl(url);
});
} }
private void initializeBrowser() { private void initializeBrowser() {
Engine engine = Engine.newInstance(EngineOptions.newBuilder(RenderingMode.HARDWARE_ACCELERATED).addSwitch("--disable-google-traffic").build()); browser = new Browser();
browser = engine.newBrowser();
// 初始化的时候,就把命名空间对象初始化好,确保window.a.b.c("a.b.c"为命名空间)对象都是初始化过的 // 初始化的时候,就把命名空间对象初始化好,确保window.a.b.c("a.b.c"为命名空间)对象都是初始化过的
browser.set(InjectJsCallback.class, params -> { browser.addScriptContextListener(new ScriptContextAdapter() {
params.frame().executeJavaScript(String.format(ModernUIConstants.SCRIPT_INIT_NAME_SPACE, namespace)); @Override
return InjectJsCallback.Response.proceed(); public void onScriptContextCreated(ScriptContextEvent event) {
event.getBrowser().executeJavaScript(String.format(ModernUIConstants.SCRIPT_INIT_NAME_SPACE, namespace));
}
}); });
} }
/** /**
* 转向一个新的地址相当于重新加载 * 转向一个新的地址相当于重新加载
*
* @param url 新的地址 * @param url 新的地址
*/ */
public void redirect(String url) { public void redirect(String url) {
browser.navigation().loadUrl(url); browser.loadURL(url);
} }
/** /**
* 转向一个新的地址相当于重新加载 * 转向一个新的地址相当于重新加载
*
* @param url 新的地址 * @param url 新的地址
* @param map 初始化参数 * @param map 初始化参数
*/ */
public void redirect(String url, Map<String, String> map) { public void redirect(String url, Map<String, String> map) {
Network network = browser.engine().network(); Assistant.setEmbProtocolHandler(browser, new EmbProtocolHandler(map));
network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network, map)); browser.loadURL(url);
browser.navigation().loadUrl(url);
} }
@Override @Override
@ -121,18 +133,19 @@ public class ModernUIPane<T> extends BasicPane {
public void populate(final T t) { public void populate(final T t) {
browser.set(InjectJsCallback.class, params -> { browser.addScriptContextListener(new ScriptContextAdapter() {
JsObject ns = params.frame().executeJavaScript("window." + namespace); @Override
if (ns != null) { public void onScriptContextCreated(ScriptContextEvent event) {
ns.putProperty(variable, t); JSValue ns = event.getBrowser().executeJavaScriptAndReturnValue("window." + namespace);
ns.asObject().setProperty(variable, t);
} }
return InjectJsCallback.Response.proceed();
}); });
} }
public T update() { public T update() {
if (browser.mainFrame().isPresent()) { JSValue jsValue = browser.executeJavaScriptAndReturnValue("window." + namespace + "." + expression);
return browser.mainFrame().get().executeJavaScript("window." + namespace + "." + expression); if (jsValue.isObject()) {
return (T)jsValue.asJavaObject();
} }
return null; return null;
} }
@ -141,89 +154,79 @@ public class ModernUIPane<T> extends BasicPane {
private ModernUIPane<T> pane = new ModernUIPane<>(); private ModernUIPane<T> pane = new ModernUIPane<>();
public Builder<T> prepare(InjectJsCallback callback) { public Builder<T> prepare(ScriptContextListener contextListener) {
pane.browser.set(InjectJsCallback.class, callback); pane.browser.addScriptContextListener(contextListener);
return this;
}
public Builder<T> prepare(LoadListener loadListener) {
pane.browser.addLoadListener(loadListener);
return this; return this;
} }
/** /**
* 加载jar包中的资源 * 加载jar包中的资源
*
* @param path 资源路径 * @param path 资源路径
*/ */
public Builder<T> withEMB(final String path) { public Builder<T> withEMB(final String path) {
Network network = pane.browser.engine().network(); Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler());
network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network)); pane.browser.loadURL("emb:" + path);
pane.browser.navigation().loadUrl("emb:" + path);
return this; return this;
} }
/** /**
* 加载url指向的资源 * 加载url指向的资源
*
* @param url 文件的地址 * @param url 文件的地址
*/ */
public Builder<T> withURL(final String url) { public Builder<T> withURL(final String url) {
Network network = pane.browser.engine().network(); Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler());
network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network)); pane.browser.loadURL(url);
pane.browser.navigation().loadUrl(url);
return this; return this;
} }
/** /**
* 加载url指向的资源 * 加载url指向的资源
*
* @param url 文件的地址 * @param url 文件的地址
*/ */
public Builder<T> withURL(final String url, Map<String, String> map) { public Builder<T> withURL(final String url, Map<String, String> map) {
Network network = pane.browser.engine().network(); Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(map));
network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network, map)); pane.browser.loadURL(url);
pane.browser.navigation().loadUrl(url);
return this; return this;
} }
/** /**
* 加载Atom组件 * 加载Atom组件
*
* @param component Atom组件 * @param component Atom组件
*/ */
public Builder<T> withComponent(AssembleComponent component) { public Builder<T> withComponent(AssembleComponent component) {
Network network = pane.browser.engine().network(); Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(component));
network.set(InterceptRequestCallback.class, new NxComplexInterceptRequestCallback(network, component)); pane.browser.loadURL("emb:dynamic");
pane.browser.navigation().loadUrl("emb:dynamic");
return this; return this;
} }
/** /**
* 加载Atom组件 * 加载Atom组件
*
* @param component Atom组件 * @param component Atom组件
*/ */
public Builder<T> withComponent(AssembleComponent component, Map<String, String> map) { public Builder<T> withComponent(AssembleComponent component, Map<String, String> map) {
Network network = pane.browser.engine().network(); Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(component, map));
network.set(InterceptRequestCallback.class, new NxComplexInterceptRequestCallback(network, component, map)); pane.browser.loadURL("emb:dynamic");
pane.browser.navigation().loadUrl("emb:dynamic");
return this; return this;
} }
/** /**
* 加载html文本内容 * 加载html文本内容
*
* @param html 要加载html文本内容 * @param html 要加载html文本内容
*/ */
public Builder<T> withHTML(String html) { public Builder<T> withHTML(String html) {
Network network = pane.browser.engine().network(); Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler());
network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network)); pane.browser.loadHTML(html);
pane.browser.mainFrame().ifPresent(frame -> {
frame.loadHtml(html);
});
return this; return this;
} }
/** /**
* 设置该前端页面做数据交换所使用的对象 * 设置该前端页面做数据交换所使用的对象
*
* @param namespace 对象名 * @param namespace 对象名
*/ */
public Builder<T> namespace(String namespace) { public Builder<T> namespace(String namespace) {
@ -233,7 +236,6 @@ public class ModernUIPane<T> extends BasicPane {
/** /**
* java端往js端传数据时使用的变量名字 * java端往js端传数据时使用的变量名字
*
* @param name 变量的名字 * @param name 变量的名字
*/ */
public Builder<T> variable(String name) { public Builder<T> variable(String name) {
@ -243,7 +245,6 @@ public class ModernUIPane<T> extends BasicPane {
/** /**
* js端往java端传数据时执行的函数表达式 * js端往java端传数据时执行的函数表达式
*
* @param expression 函数表达式 * @param expression 函数表达式
*/ */
public Builder<T> expression(String expression) { public Builder<T> expression(String expression) {

85
designer-base/src/main/java/com/fr/design/ui/NxComplexInterceptRequestCallback.java

@ -1,85 +0,0 @@
package com.fr.design.ui;
import com.fr.general.IOUtils;
import com.fr.stable.StringUtils;
import com.fr.web.struct.AssembleComponent;
import com.fr.web.struct.AtomBuilder;
import com.fr.web.struct.PathGroup;
import com.fr.web.struct.category.ScriptPath;
import com.fr.web.struct.category.StylePath;
import com.teamdev.jxbrowser.net.Network;
import com.teamdev.jxbrowser.net.UrlRequest;
import com.teamdev.jxbrowser.net.callback.InterceptRequestCallback;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author richie
* @version 10.0
* Created by richie on 2020/3/25
*/
public class NxComplexInterceptRequestCallback extends NxInterceptRequestCallback {
private AssembleComponent component;
public NxComplexInterceptRequestCallback(Network network, AssembleComponent component) {
super(network);
this.component = component;
}
public NxComplexInterceptRequestCallback(Network network, AssembleComponent component, Map<String, String> map) {
super(network, map);
this.component = component;
}
@Override
protected Response next(UrlRequest urlRequest, String path) {
if (path.startsWith("emb:dynamic")) {
String text = htmlText(map);
return InterceptRequestCallback.Response.intercept(generateBasicUrlRequestJob(urlRequest, "text/html", text.getBytes(StandardCharsets.UTF_8)));
} else {
int index = path.indexOf("=");
if (index > 0) {
path = path.substring(index + 1);
} else {
path = path.substring(4);
}
InputStream inputStream = IOUtils.readResource(path);
return InterceptRequestCallback.Response.intercept(generateBasicUrlRequestJob(urlRequest, getMimeType(path), IOUtils.inputStream2Bytes(inputStream)));
}
}
private String htmlText(Map<String, String> map) {
PathGroup pathGroup = AtomBuilder.create().buildAssembleFilePath(ModernRequestClient.KEY, component);
StylePath[] stylePaths = pathGroup.toStylePathGroup();
StringBuilder styleText = new StringBuilder();
for (StylePath path : stylePaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
styleText.append("<link rel=\"stylesheet\" href=\"emb:");
styleText.append(path.toFilePath());
styleText.append("\"/>");
}
}
String result = ModernUIConstants.HTML_TPL.replaceAll("##style##", styleText.toString());
ScriptPath[] scriptPaths = pathGroup.toScriptPathGroup();
StringBuilder scriptText = new StringBuilder();
for (ScriptPath path : scriptPaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
scriptText.append("<script src=\"emb:");
scriptText.append(path.toFilePath());
scriptText.append("\"></script>");
}
}
result = result.replaceAll("##script##", scriptText.toString());
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
result = result.replaceAll("\\$\\{" + key + "}", value);
}
}
return result;
}
}

134
designer-base/src/main/java/com/fr/design/ui/NxInterceptRequestCallback.java

@ -1,134 +0,0 @@
package com.fr.design.ui;
import com.fr.base.TemplateUtils;
import com.fr.general.IOUtils;
import com.fr.log.FineLoggerFactory;
import com.fr.stable.ArrayUtils;
import com.fr.stable.EncodeConstants;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.commons.codec.net.URLCodec;
import com.teamdev.jxbrowser.net.HttpHeader;
import com.teamdev.jxbrowser.net.HttpStatus;
import com.teamdev.jxbrowser.net.Network;
import com.teamdev.jxbrowser.net.UrlRequest;
import com.teamdev.jxbrowser.net.UrlRequestJob;
import com.teamdev.jxbrowser.net.callback.InterceptRequestCallback;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
/**
* @author richie
* @version 10.0
* Created by richie on 2020/3/25
*/
public class NxInterceptRequestCallback implements InterceptRequestCallback {
Network network;
Map<String, String> map;
public NxInterceptRequestCallback(Network network) {
this.network = network;
}
public NxInterceptRequestCallback(Network network, Map<String, String> map) {
this.network = network;
this.map = map;
}
@Override
public Response on(Params params) {
UrlRequest urlRequest = params.urlRequest();
String path = urlRequest.url();
if (path.startsWith("file:")) {
Optional<UrlRequestJob> optional = generateFileProtocolUrlRequestJob(urlRequest, path);
if (optional.isPresent()) {
return InterceptRequestCallback.Response.intercept(optional.get());
}
} else {
return next(urlRequest, path);
}
return Response.proceed();
}
Response next(UrlRequest urlRequest, String path) {
return Response.proceed();
}
private Optional<UrlRequestJob> generateFileProtocolUrlRequestJob(UrlRequest urlRequest, String path) {
try {
String url = new URLCodec().decode(path);
String filePath = TemplateUtils.renderParameter4Tpl(url, map);
File file = new File(URI.create(filePath).getPath());
InputStream inputStream = IOUtils.readResource(file.getAbsolutePath());
String mimeType = getMimeType(path);
byte[] bytes;
if (isPlainText(mimeType)) {
String text = IOUtils.inputStream2String(inputStream, EncodeConstants.ENCODING_UTF_8);
text = TemplateUtils.renderParameter4Tpl(text, map);
bytes = text.getBytes(StandardCharsets.UTF_8);
} else {
bytes = IOUtils.inputStream2Bytes(inputStream);
}
return Optional.of(generateBasicUrlRequestJob(urlRequest, mimeType, bytes));
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return Optional.empty();
}
private boolean isPlainText(String mimeType) {
return ArrayUtils.contains(new String[]{"text/html", "text/javascript", "text/css"}, mimeType);
}
UrlRequestJob generateBasicUrlRequestJob(UrlRequest urlRequest, String mimeType, byte[] bytes) {
UrlRequestJob.Options options = UrlRequestJob.Options
.newBuilder(urlRequest.id(), HttpStatus.OK)
.addHttpHeader(HttpHeader.of("Content-Type", mimeType))
.build();
UrlRequestJob urlRequestJob = network.newUrlRequestJob(options);
urlRequestJob.write(bytes);
urlRequestJob.complete();
return urlRequestJob;
}
String getMimeType(String path) {
if (StringUtils.isBlank(path)) {
return "text/html";
}
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
if (path.endsWith(".svg")) {
return "image/svg+xml";
}
if (path.endsWith(".png")) {
return "image/png";
}
if (path.endsWith(".jpeg")) {
return "image/jpeg";
}
if (path.endsWith(".gif")) {
return "image/gif";
}
Path file = new File(path).toPath();
try {
return Files.probeContentType(file);
} catch (IOException e) {
return "text/html";
}
}
}

228
designer-base/src/main/java/com/fr/design/upm/UpmBridge.java

@ -6,7 +6,6 @@ import com.fr.config.ServerPreferenceConfig;
import com.fr.decision.webservice.v10.plugin.helper.category.impl.UpmResourceLoader; import com.fr.decision.webservice.v10.plugin.helper.category.impl.UpmResourceLoader;
import com.fr.design.bridge.exec.JSBridge; import com.fr.design.bridge.exec.JSBridge;
import com.fr.design.bridge.exec.JSCallback; import com.fr.design.bridge.exec.JSCallback;
import com.fr.design.bridge.exec.JSExecutor;
import com.fr.design.extra.PluginOperateUtils; import com.fr.design.extra.PluginOperateUtils;
import com.fr.design.extra.PluginUtils; import com.fr.design.extra.PluginUtils;
import com.fr.design.extra.exe.GetInstalledPluginsExecutor; import com.fr.design.extra.exe.GetInstalledPluginsExecutor;
@ -29,8 +28,10 @@ import com.fr.log.FineLoggerFactory;
import com.fr.plugin.context.PluginMarker; import com.fr.plugin.context.PluginMarker;
import com.fr.stable.ArrayUtils; import com.fr.stable.ArrayUtils;
import com.fr.stable.StringUtils; import com.fr.stable.StringUtils;
import com.teamdev.jxbrowser.js.JsAccessible; import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.js.JsObject; import com.teamdev.jxbrowser.chromium.JSArray;
import com.teamdev.jxbrowser.chromium.JSFunction;
import com.teamdev.jxbrowser.chromium.JSObject;
import javax.swing.*; import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileNameExtensionFilter;
@ -51,45 +52,42 @@ import java.util.concurrent.RunnableFuture;
*/ */
public class UpmBridge { public class UpmBridge {
public static UpmBridge getBridge() { public static UpmBridge getBridge(Browser browser) {
return new UpmBridge(); return new UpmBridge(browser);
} }
private JSObject window;
private UpmBridge() { private UpmBridge(Browser browser) {
this.window = browser.executeJavaScriptAndReturnValue("window").asObject();
} }
/** /**
* 更新插件管理中心资源文件这个方法仅仅是为了语义上的作用更新 * 更新插件管理中心资源文件这个方法仅仅是为了语义上的作用更新
*
* @param callback 安装完成后的回调函数 * @param callback 安装完成后的回调函数
*/ */
@JSBridge @JSBridge
@JsAccessible public void update(final JSFunction callback) {
public void update(final JsObject callback) { callback.invoke(window, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start"));
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start"));
try { try {
UpmResourceLoader.INSTANCE.download(); UpmResourceLoader.INSTANCE.download();
UpmResourceLoader.INSTANCE.install(); UpmResourceLoader.INSTANCE.install();
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success")); callback.invoke(window, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success"));
EventDispatcher.fire(DownloadEvent.UPDATE, "success"); EventDispatcher.fire(DownloadEvent.UPDATE, "success");
} catch (Exception e) { } catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e); FineLoggerFactory.getLogger().error(e.getMessage(), e);
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error")); callback.invoke(window, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error"));
} }
} }
/** /**
* 下载并安装插件管理中心的资源文件 * 下载并安装插件管理中心的资源文件
*
* @param callback 安装完成后的回调函数 * @param callback 安装完成后的回调函数
*/ */
@JSBridge @JSBridge
@JsAccessible public void startDownload(final JSFunction callback) {
public void startDownload(final JsObject callback) { callback.invoke(window, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start"));
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start")); new SwingWorker<Void, Void>(){
new SwingWorker<Void, Void>() {
@Override @Override
protected Void doInBackground() throws Exception { protected Void doInBackground() throws Exception {
UpmResourceLoader.INSTANCE.download(); UpmResourceLoader.INSTANCE.download();
@ -101,10 +99,10 @@ public class UpmBridge {
protected void done() { protected void done() {
try { try {
get(); get();
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success")); callback.invoke(window, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success"));
EventDispatcher.fire(DownloadEvent.SUCCESS, "success"); EventDispatcher.fire(DownloadEvent.SUCCESS, "success");
} catch (Exception e) { } catch (Exception e) {
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error")); callback.invoke(window, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error"));
FineLoggerFactory.getLogger().error(e.getMessage(), e); FineLoggerFactory.getLogger().error(e.getMessage(), e);
EventDispatcher.fire(DownloadEvent.ERROR, "error"); EventDispatcher.fire(DownloadEvent.ERROR, "error");
} }
@ -114,44 +112,37 @@ public class UpmBridge {
/** /**
* 获取upm的版本信息 * 获取upm的版本信息
*
* @return 版本信息 * @return 版本信息
*/ */
@JSBridge @JSBridge
@JsAccessible
public String getVersion() { public String getVersion() {
return ServerPreferenceConfig.getInstance().getOptimizedUPMVersion(); return ServerPreferenceConfig.getInstance().getOptimizedUPMVersion();
} }
@JSBridge @JSBridge
@JsAccessible
public String i18nText(String key) { public String i18nText(String key) {
return Toolkit.i18nText(key); return Toolkit.i18nText(key);
} }
@JSBridge @JSBridge
@JsAccessible
public void closeWindow() { public void closeWindow() {
UpmFinder.closeWindow(); UpmFinder.closeWindow();
} }
@JSBridge @JSBridge
@JsAccessible
public boolean isDesigner() { public boolean isDesigner() {
return true; return true;
} }
@JSBridge @JSBridge
@JsAccessible public void getPackInfo(final JSFunction callback) {
public void getPackInfo(final JsObject callback) { callback.invoke(window, StringUtils.EMPTY);
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, StringUtils.EMPTY);
} }
@JSBridge @JSBridge
@JsAccessible public void getPluginPrefix(final JSFunction callback) {
public void getPluginPrefix(final JsObject callback) { UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetPluginPrefixExecutor());
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetPluginPrefixExecutor());
task.execute(); task.execute();
} }
@ -161,9 +152,8 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
@JsAccessible public void getPluginCategories(final JSFunction callback) {
public void getPluginCategories(final JsObject callback) { UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetPluginCategoriesExecutor());
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetPluginCategoriesExecutor());
task.execute(); task.execute();
} }
@ -174,9 +164,8 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
@JsAccessible public void getPluginFromStoreNew(String info, final JSFunction callback) {
public void getPluginFromStoreNew(String info, final JsObject callback) { UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetPluginFromStoreExecutor(new JSONObject(info)));
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetPluginFromStoreExecutor(new JSONObject(info)));
task.execute(); task.execute();
} }
@ -184,9 +173,8 @@ public class UpmBridge {
* 已安装插件检查更新 * 已安装插件检查更新
*/ */
@JSBridge @JSBridge
@JsAccessible public void readUpdateOnline(final JSFunction callback) {
public void readUpdateOnline(final JsObject callback) { UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new ReadUpdateOnlineExecutor());
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new ReadUpdateOnlineExecutor());
task.execute(); task.execute();
} }
@ -194,9 +182,8 @@ public class UpmBridge {
* 获取已经安装的插件的数组 * 获取已经安装的插件的数组
*/ */
@JSBridge @JSBridge
@JsAccessible public void getInstalledPlugins(final JSFunction callback) {
public void getInstalledPlugins(final JsObject callback) { UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetInstalledPluginsExecutor());
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetInstalledPluginsExecutor());
task.execute(); task.execute();
} }
@ -206,36 +193,29 @@ public class UpmBridge {
* @param pluginIDs 插件集合 * @param pluginIDs 插件集合
*/ */
@JSBridge @JSBridge
@JsAccessible public void updatePluginOnline(Object pluginIDs, final JSFunction callback) {
public void updatePluginOnline(JsObject pluginIDs, final JsObject callback) { JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback));
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
List<PluginMarker> pluginMarkerList = new ArrayList<>(); List<PluginMarker> pluginMarkerList = new ArrayList<>();
for (String key : pluginIDs.propertyNames()) { if (pluginIDs instanceof String) {
pluginIDs.property(key).ifPresent(v -> { pluginMarkerList.add(PluginUtils.createPluginMarker(pluginIDs.toString()));
pluginMarkerList.add(PluginUtils.createPluginMarker(GeneralUtils.objectToString(v))); } else if (pluginIDs instanceof JSArray) {
}); JSArray pluginInfos = (JSArray) pluginIDs;
for (int i = 0, len = pluginInfos.length(); i < len; i++) {
String value = pluginInfos.get(i).asString().getValue();
pluginMarkerList.add(PluginUtils.createPluginMarker(value));
}
} }
PluginOperateUtils.updatePluginOnline(pluginMarkerList, jsCallback); PluginOperateUtils.updatePluginOnline(pluginMarkerList, jsCallback);
} }
@JSBridge
@JsAccessible
public void updatePluginOnline(String pluginID, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
List<PluginMarker> pluginMarkerList = new ArrayList<>();
pluginMarkerList.add(PluginUtils.createPluginMarker(pluginID));
PluginOperateUtils.updatePluginOnline(pluginMarkerList, jsCallback);
}
/** /**
* 搜索在线插件 * 搜索在线插件
* *
* @param keyword 关键字 * @param keyword 关键字
*/ */
@JSBridge @JSBridge
@JsAccessible public void searchPlugin(String keyword, final JSFunction callback) {
public void searchPlugin(String keyword, final JsObject callback) { UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new SearchOnlineExecutor(keyword));
UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new SearchOnlineExecutor(keyword));
worker.execute(); worker.execute();
} }
@ -245,9 +225,8 @@ public class UpmBridge {
* @param filePath 插件包的路径 * @param filePath 插件包的路径
*/ */
@JSBridge @JSBridge
@JsAccessible public void installPluginFromDisk(final String filePath, final JSFunction callback) {
public void installPluginFromDisk(final String filePath, final JsObject callback) { JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback));
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
File file = new File(filePath); File file = new File(filePath);
PluginOperateUtils.installPluginFromDisk(file, jsCallback); PluginOperateUtils.installPluginFromDisk(file, jsCallback);
} }
@ -258,9 +237,8 @@ public class UpmBridge {
* @param pluginInfo 插件信息 * @param pluginInfo 插件信息
*/ */
@JSBridge @JSBridge
@JsAccessible public void uninstallPlugin(final String pluginInfo, final boolean isForce, final JSFunction callback) {
public void uninstallPlugin(final String pluginInfo, final boolean isForce, final JsObject callback) { JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback));
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
PluginOperateUtils.uninstallPlugin(pluginInfo, isForce, jsCallback); PluginOperateUtils.uninstallPlugin(pluginInfo, isForce, jsCallback);
} }
@ -271,9 +249,8 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
@JsAccessible public void installPluginOnline(final String pluginInfo, final JSFunction callback) {
public void installPluginOnline(final String pluginInfo, final JsObject callback) { JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback));
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
PluginMarker pluginMarker = PluginUtils.createPluginMarker(pluginInfo); PluginMarker pluginMarker = PluginUtils.createPluginMarker(pluginInfo);
PluginOperateUtils.installPluginOnline(pluginMarker, jsCallback); PluginOperateUtils.installPluginOnline(pluginMarker, jsCallback);
} }
@ -283,10 +260,8 @@ public class UpmBridge {
* *
* @param filePath 插件包的路径 * @param filePath 插件包的路径
*/ */
@JSBridge public void updatePluginFromDisk(String filePath, final JSFunction callback) {
@JsAccessible JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback));
public void updatePluginFromDisk(String filePath, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
File file = new File(filePath); File file = new File(filePath);
PluginOperateUtils.updatePluginFromDisk(file, jsCallback); PluginOperateUtils.updatePluginFromDisk(file, jsCallback);
} }
@ -297,9 +272,8 @@ public class UpmBridge {
* @param pluginID 插件ID * @param pluginID 插件ID
*/ */
@JSBridge @JSBridge
@JsAccessible public void setPluginActive(String pluginID, final JSFunction callback) {
public void setPluginActive(String pluginID, final JsObject callback) { JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback));
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
PluginOperateUtils.setPluginActive(pluginID, jsCallback); PluginOperateUtils.setPluginActive(pluginID, jsCallback);
} }
@ -309,7 +283,6 @@ public class UpmBridge {
* @return 选择的文件的路径 * @return 选择的文件的路径
*/ */
@JSBridge @JSBridge
@JsAccessible
public String showFileChooser() { public String showFileChooser() {
return showFileChooserWithFilter(StringUtils.EMPTY, StringUtils.EMPTY); return showFileChooserWithFilter(StringUtils.EMPTY, StringUtils.EMPTY);
} }
@ -323,7 +296,6 @@ public class UpmBridge {
* 这里换用JFileChooser会卡死,不知道为什么 * 这里换用JFileChooser会卡死,不知道为什么
*/ */
@JSBridge @JSBridge
@JsAccessible
public String showFileChooserWithFilter(final String des, final String filter) { public String showFileChooserWithFilter(final String des, final String filter) {
RunnableFuture<String> future = new FutureTask<>(new Callable<String>() { RunnableFuture<String> future = new FutureTask<>(new Callable<String>() {
@Override @Override
@ -359,60 +331,31 @@ public class UpmBridge {
* @return 选择的文件的路径 * @return 选择的文件的路径
*/ */
@JSBridge @JSBridge
@JsAccessible public String showFileChooserWithFilters(final String des, final Object args) {
public String showFileChooserWithFilters(final String des, final String args) { RunnableFuture<String> future = new FutureTask<>(new Callable<String>() {
RunnableFuture<String> future = new FutureTask<>(() -> { @Override
JFileChooser fileChooser = new JFileChooser(); public String call() {
List<String> filterList = new ArrayList<>(); JFileChooser fileChooser = new JFileChooser();
filterList.add(args); List<String> filterList = new ArrayList<>();
String[] filters = filterList.toArray(new String[0]); if (args instanceof String) {
if (ArrayUtils.isNotEmpty(filters)) { filterList.add(GeneralUtils.objectToString(args));
FileNameExtensionFilter filter = new FileNameExtensionFilter(des, UpmUtils.findMatchedExtension(filters)); } else if (args instanceof JSArray) {
fileChooser.setFileFilter(filter); JSArray array = (JSArray)args;
} for (int i = 0, len = array.length(); i < len; i ++) {
int result = fileChooser.showOpenDialog(UpmFinder.getDialog()); filterList.add(array.get(i).getStringValue());
if (result == JFileChooser.APPROVE_OPTION) { }
return fileChooser.getSelectedFile().getAbsolutePath(); }
} String[] filters = filterList.toArray(new String[0]);
return null; if (ArrayUtils.isNotEmpty(filters)) {
}); FileNameExtensionFilter filter = new FileNameExtensionFilter(des, UpmUtils.findMatchedExtension(filters));
SwingUtilities.invokeLater(future); fileChooser.setFileFilter(filter);
try { }
return future.get(); int result = fileChooser.showOpenDialog(UpmFinder.getDialog());
} catch (Exception e) { if (result == JFileChooser.APPROVE_OPTION) {
FineLoggerFactory.getLogger().error(e.getMessage(), e); return fileChooser.getSelectedFile().getAbsolutePath();
} }
return null; return null;
}
/**
* 选择文件对话框
*
* @param des 过滤文件描述
* @param args 文件的后缀
* @return 选择的文件的路径
*/
@JSBridge
@JsAccessible
public String showFileChooserWithFilters(final String des, final JsObject args) {
RunnableFuture<String> future = new FutureTask<>(() -> {
JFileChooser fileChooser = new JFileChooser();
List<String> filterList = new ArrayList<>();
for (String key : args.propertyNames()) {
args.property(key).ifPresent(v -> {
filterList.add(GeneralUtils.objectToString(v));
});
}
String[] filters = filterList.toArray(new String[0]);
if (ArrayUtils.isNotEmpty(filters)) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(des, UpmUtils.findMatchedExtension(filters));
fileChooser.setFileFilter(filter);
}
int result = fileChooser.showOpenDialog(UpmFinder.getDialog());
if (result == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().getAbsolutePath();
} }
return null;
}); });
SwingUtilities.invokeLater(future); SwingUtilities.invokeLater(future);
try { try {
@ -429,8 +372,7 @@ public class UpmBridge {
* 获取系统登录的用户名 * 获取系统登录的用户名
*/ */
@JSBridge @JSBridge
@JsAccessible public String getLoginInfo(final JSFunction callback) {
public String getLoginInfo(final JsObject callback) {
registerLoginInfo(callback); registerLoginInfo(callback);
return MarketConfig.getInstance().getBbsUsername(); return MarketConfig.getInstance().getBbsUsername();
} }
@ -441,9 +383,8 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
@JsAccessible public void registerLoginInfo(final JSFunction callback) {
public void registerLoginInfo(final JsObject callback) { JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback));
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
String username = MarketConfig.getInstance().getBbsUsername(); String username = MarketConfig.getInstance().getBbsUsername();
if (StringUtils.isEmpty(username)) { if (StringUtils.isEmpty(username)) {
jsCallback.execute(StringUtils.EMPTY); jsCallback.execute(StringUtils.EMPTY);
@ -463,16 +404,14 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
@JsAccessible public void defaultLogin(String username, String password, final JSFunction callback) {
public void defaultLogin(String username, String password, final JsObject callback) { UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new PluginLoginExecutor(username, password));
UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new PluginLoginExecutor(username, password));
worker.execute(); worker.execute();
} }
/** /**
* 清除用户信息 * 清除用户信息
*/ */
@JsAccessible
public void clearUserInfo() { public void clearUserInfo() {
MarketConfig.getInstance().setInShowBBsName(StringUtils.EMPTY); MarketConfig.getInstance().setInShowBBsName(StringUtils.EMPTY);
FinePassportManager.getInstance().logout(); FinePassportManager.getInstance().logout();
@ -483,7 +422,6 @@ public class UpmBridge {
* 打开论坛消息界面 * 打开论坛消息界面
*/ */
@JSBridge @JSBridge
@JsAccessible
public void getPriviteMessage() { public void getPriviteMessage() {
try { try {
String loginUrl = CloudCenter.getInstance().acquireUrlByKind("bbs.default"); String loginUrl = CloudCenter.getInstance().acquireUrlByKind("bbs.default");
@ -497,7 +435,6 @@ public class UpmBridge {
* 忘记密码 * 忘记密码
*/ */
@JSBridge @JSBridge
@JsAccessible
public void forgetHref() { public void forgetHref() {
try { try {
Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.reset"))); Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.reset")));
@ -510,7 +447,6 @@ public class UpmBridge {
* 立即注册 * 立即注册
*/ */
@JSBridge @JSBridge
@JsAccessible
public void registerHref() { public void registerHref() {
try { try {
Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.register"))); Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.register")));
@ -521,11 +457,9 @@ public class UpmBridge {
/** /**
* 使用系统浏览器打开网页 * 使用系统浏览器打开网页
*
* @param url 要打开的网页 * @param url 要打开的网页
*/ */
@JSBridge @JSBridge
@JsAccessible
public void openShopUrlAtWebBrowser(String url) { public void openShopUrlAtWebBrowser(String url) {
if (Desktop.isDesktopSupported()) { if (Desktop.isDesktopSupported()) {
try { try {

4
designer-base/src/main/java/com/fr/design/upm/UpmFinder.java

@ -58,7 +58,7 @@ public class UpmFinder {
public static void showUPMDialog() { public static void showUPMDialog() {
boolean flag = true; boolean flag = true;
try { try {
Class.forName("com.teamdev.jxbrowser.browser.Browser"); Class.forName("com.teamdev.jxbrowser.chromium.Browser");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
flag = false; flag = false;
} }
@ -88,7 +88,7 @@ public class UpmFinder {
dialog.setVisible(true); dialog.setVisible(true);
} }
} else { } else {
FineJOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Toolkit.i18nText("Fine-Design_Update_Info_Plugin_Message")); JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Toolkit.i18nText("Fine-Design_Update_Info_Plugin_Message"));
UpdateMainDialog dialog = new UpdateMainDialog(DesignerContext.getDesignerFrame()); UpdateMainDialog dialog = new UpdateMainDialog(DesignerContext.getDesignerFrame());
dialog.setAutoUpdateAfterInit(); dialog.setAutoUpdateAfterInit();
dialog.showDialog(); dialog.showDialog();

15
designer-base/src/main/java/com/fr/design/upm/UpmShowPane.java

@ -6,8 +6,9 @@ import com.fr.design.upm.event.DownloadEvent;
import com.fr.event.Event; import com.fr.event.Event;
import com.fr.event.EventDispatcher; import com.fr.event.EventDispatcher;
import com.fr.event.Listener; import com.fr.event.Listener;
import com.teamdev.jxbrowser.browser.callback.InjectJsCallback; import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.js.JsObject; import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter;
import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent;
import java.awt.*; import java.awt.*;
@ -31,10 +32,12 @@ public class UpmShowPane extends BasicPane {
// 先屏蔽掉这个判断,后续可能修改交互 // 先屏蔽掉这个判断,后续可能修改交互
// if (UpmFinder.checkUPMResourcesExist()) { // if (UpmFinder.checkUPMResourcesExist()) {
modernUIPane = new ModernUIPane.Builder<>() modernUIPane = new ModernUIPane.Builder<>()
.prepare(params -> { .prepare(new ScriptContextAdapter() {
JsObject window = params.frame().executeJavaScript("window"); @Override
window.putProperty("PluginHelper", UpmBridge.getBridge()); public void onScriptContextCreated(ScriptContextEvent event) {
return InjectJsCallback.Response.proceed(); JSValue window = event.getBrowser().executeJavaScriptAndReturnValue("window");
window.asObject().setProperty("PluginHelper", UpmBridge.getBridge(event.getBrowser()));
}
}) })
.withURL(UpmFinder.getMainResourcePath(), UpmUtils.renderMap()) .withURL(UpmFinder.getMainResourcePath(), UpmUtils.renderMap())
.build(); .build();

15
designer-base/src/main/java/com/fr/design/upm/exec/UpmBrowserExecutor.java

@ -1,7 +1,8 @@
package com.fr.design.upm.exec; package com.fr.design.upm.exec;
import com.fr.design.bridge.exec.JSExecutor; import com.fr.design.bridge.exec.JSExecutor;
import com.teamdev.jxbrowser.js.JsObject; import com.teamdev.jxbrowser.chromium.JSFunction;
import com.teamdev.jxbrowser.chromium.JSObject;
/** /**
* @author richie * @author richie
@ -10,18 +11,20 @@ import com.teamdev.jxbrowser.js.JsObject;
*/ */
public class UpmBrowserExecutor implements JSExecutor { public class UpmBrowserExecutor implements JSExecutor {
public static UpmBrowserExecutor create(JsObject callback) { public static UpmBrowserExecutor create(JSObject window, JSFunction callback) {
return new UpmBrowserExecutor(callback); return new UpmBrowserExecutor(window, callback);
} }
private JsObject callback; private JSObject window;
private JSFunction callback;
private UpmBrowserExecutor(JsObject callback) { private UpmBrowserExecutor(JSObject window, JSFunction callback) {
this.window = window;
this.callback = callback; this.callback = callback;
} }
@Override @Override
public void executor(String newValue) { public void executor(String newValue) {
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, newValue); callback.invoke(window, newValue);
} }
} }

4
pom.xml

@ -28,8 +28,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>3.1</version>
<configuration> <configuration>
<source>1.8</source> <source>1.7</source>
<target>1.8</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

Loading…
Cancel
Save