From 7bac8813849117e83ced3f61493eed2102ff388f Mon Sep 17 00:00:00 2001 From: "honfika@gmail.com" Date: Mon, 21 Nov 2016 14:31:12 +0100 Subject: [PATCH] #1309 recent files not getting updates --- CHANGELOG.md | 1 + .../decompiler/flash/gui/ImagePanel.java | 2871 +++---- src/com/jpexs/decompiler/flash/gui/Main.java | 4747 +++++------ .../jpexs/decompiler/flash/gui/MainPanel.java | 7362 ++++++++--------- 4 files changed, 7496 insertions(+), 7485 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43a6d20db..c0d672ea0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ All notable changes to this project will be documented in this file. - #1283 AS3 Unbounded Vector - Vector<*> decompilation and direct editation fix - #1294 Font editation (DefineFont2/3) - correct switching of wide character codes - #1302 Callpropvoid instruction docblock not correct +- #1309 recent files not getting updates ## [9.0.0] - 2016-08-12 ### Added diff --git a/src/com/jpexs/decompiler/flash/gui/ImagePanel.java b/src/com/jpexs/decompiler/flash/gui/ImagePanel.java index 4299dbb96..08ec2452a 100644 --- a/src/com/jpexs/decompiler/flash/gui/ImagePanel.java +++ b/src/com/jpexs/decompiler/flash/gui/ImagePanel.java @@ -1,1434 +1,1437 @@ -/* - * Copyright (C) 2010-2016 JPEXS - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.jpexs.decompiler.flash.gui; - -import com.jpexs.decompiler.flash.SWF; -import com.jpexs.decompiler.flash.SWFInputStream; -import com.jpexs.decompiler.flash.action.Action; -import com.jpexs.decompiler.flash.action.LocalDataArea; -import com.jpexs.decompiler.flash.action.Stage; -import com.jpexs.decompiler.flash.configuration.Configuration; -import com.jpexs.decompiler.flash.ecma.Undefined; -import com.jpexs.decompiler.flash.exporters.commonshape.Matrix; -import com.jpexs.decompiler.flash.gui.player.MediaDisplay; -import com.jpexs.decompiler.flash.gui.player.MediaDisplayListener; -import com.jpexs.decompiler.flash.gui.player.Zoom; -import com.jpexs.decompiler.flash.tags.DefineButtonSoundTag; -import com.jpexs.decompiler.flash.tags.DoActionTag; -import com.jpexs.decompiler.flash.tags.base.BoundedTag; -import com.jpexs.decompiler.flash.tags.base.ButtonTag; -import com.jpexs.decompiler.flash.tags.base.CharacterTag; -import com.jpexs.decompiler.flash.tags.base.DrawableTag; -import com.jpexs.decompiler.flash.tags.base.PlaceObjectTypeTag; -import com.jpexs.decompiler.flash.tags.base.RenderContext; -import com.jpexs.decompiler.flash.tags.base.SoundTag; -import com.jpexs.decompiler.flash.tags.base.TextTag; -import com.jpexs.decompiler.flash.timeline.DepthState; -import com.jpexs.decompiler.flash.timeline.Frame; -import com.jpexs.decompiler.flash.timeline.Timeline; -import com.jpexs.decompiler.flash.timeline.Timelined; -import com.jpexs.decompiler.flash.types.ConstantColorColorTransform; -import com.jpexs.decompiler.flash.types.RECT; -import com.jpexs.decompiler.flash.types.SOUNDINFO; -import com.jpexs.helpers.ByteArrayRange; -import com.jpexs.helpers.Cache; -import com.jpexs.helpers.SerializableImage; -import com.jpexs.helpers.Stopwatch; -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.Transparency; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionAdapter; -import java.awt.event.MouseMotionListener; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.awt.image.VolatileImage; -import java.io.IOException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.sound.sampled.LineUnavailableException; -import javax.sound.sampled.UnsupportedAudioFileException; -import javax.swing.JLabel; -import javax.swing.JPanel; - -/** - * - * @author JPEXS - */ -public final class ImagePanel extends JPanel implements MediaDisplay { - - private static final Logger logger = Logger.getLogger(ImagePanel.class.getName()); - - private final List listeners = new ArrayList<>(); - - private Timelined timelined; - - private boolean stillFrame = false; - - private Timer timer; - - private int frame = -1; - - private boolean loop; - - private LocalDataArea lda; - - private boolean zoomAvailable = false; - - private SWF swf; - - private boolean loaded; - - private int mouseButton; - - private final JLabel debugLabel = new JLabel("-"); - - private Point cursorPosition = null; - - private MouseEvent lastMouseEvent = null; - - private final List soundPlayers = new ArrayList<>(); - - private final Cache displayObjectCache = Cache.getInstance(false, false, "displayObject"); - - private final IconPanel iconPanel; - - private int time = 0; - - private int selectedDepth = -1; - - private Zoom zoom = new Zoom(); - - private final Object delayObject = new Object(); - - private boolean drawReady; - - private final int drawWaitLimit = 50; // ms - - private TextTag textTag; - - private TextTag newTextTag; - - private int msPerFrame; - - private final boolean lowQuality = false; - - private final double LQ_FACTOR = 2; - - public synchronized void selectDepth(int depth) { - if (depth != selectedDepth) { - this.selectedDepth = depth; - } - - hideMouseSelection(); - } - - public void fireMediaDisplayStateChanged() { - for (MediaDisplayListener l : listeners) { - l.mediaDisplayStateChanged(this); - } - } - - @Override - public void addEventListener(MediaDisplayListener listener) { - listeners.add(listener); - } - - @Override - public void removeEventListener(MediaDisplayListener listener) { - listeners.remove(listener); - } - - private class IconPanel extends JPanel { - - private SerializableImage _img; - - private Rectangle _rect = null; - - private ButtonTag mouseOverButton = null; - - private boolean autoFit = false; - - private boolean allowMove = true; - - private Point dragStart = null; - - private Point offsetPoint = new Point(0, 0); - - private synchronized SerializableImage getImg() { - return _img; - } - - public synchronized Rectangle getRect() { - return _rect; - } - - public boolean hasAllowMove() { - return allowMove; - } - - VolatileImage renderImage; - - public void render() { - SerializableImage img = getImg(); - Rectangle rect = getRect(); - if (img == null) { - return; - } - if (renderImage == null) { - return; - } - Graphics2D g2 = null; - do { - - int valid = renderImage.validate(View.getDefaultConfiguration()); - - if (valid == VolatileImage.IMAGE_INCOMPATIBLE) { - renderImage = View.createRenderImage(getWidth(), getHeight(), Transparency.TRANSLUCENT); - } - - try { - g2 = renderImage.createGraphics(); - g2.setPaint(View.transparentPaint); - g2.fill(new Rectangle(0, 0, getWidth(), getHeight())); - g2.setComposite(AlphaComposite.SrcOver); - g2.setPaint(View.getSwfBackgroundColor()); - g2.fill(new Rectangle(0, 0, getWidth(), getHeight())); - - g2.setComposite(AlphaComposite.SrcOver); - if (rect != null) { - g2.drawImage(img.getBufferedImage(), rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, 0, 0, img.getWidth(), img.getHeight(), null); - } - } finally { - if (g2 != null) { - g2.dispose(); - } - } - - } while (renderImage.contentsLost()); - } - - public IconPanel() { - addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - renderImage = View.createRenderImage(getWidth(), getHeight(), Transparency.TRANSLUCENT); - if (_img != null) { - calcRect(); - render(); - } - repaint(); - } - - }); - addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - dragStart = e.getPoint(); - } - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - dragStart = null; - } - } - - }); - addMouseMotionListener(new MouseMotionAdapter() { - @Override - public void mouseDragged(MouseEvent e) { - if (dragStart != null && allowMove) { - Point dragEnd = e.getPoint(); - Point delta = new Point(dragEnd.x - dragStart.x, dragEnd.y - dragStart.y); - offsetPoint.x += delta.x; - offsetPoint.y += delta.y; - dragStart = dragEnd; - repaint(); - } - } - - }); - } - - public void setAutoFit(boolean autoFit) { - this.autoFit = autoFit; - repaint(); - } - - public synchronized BufferedImage getLastImage() { - if (_img == null) { - return null; - } - return _img.getBufferedImage(); - } - - public synchronized void setImg(SerializableImage img) { - this._img = img; - if (img != null) { - calcRect(); - render(); - } - repaint(); - } - - public synchronized Point toImagePoint(Point p) { - if (_img == null) { - return null; - } - - return new Point((p.x - _rect.x) * _img.getWidth() / _rect.width, (p.y - _rect.y) * _img.getHeight() / _rect.height); - } - - private void setAllowMove(boolean allowMove) { - this.allowMove = allowMove; - if (!allowMove) { - offsetPoint = new Point(); - } - } - - private synchronized void calcRect() { - if (_img != null) { - int w1 = (int) (_img.getWidth() * (lowQuality ? LQ_FACTOR : 1)); - int h1 = (int) (_img.getHeight() * (lowQuality ? LQ_FACTOR : 1)); - - int w2 = getWidth(); - int h2 = getHeight(); - - int w; - int h; - if (autoFit) { - if (w1 <= w2 && h1 <= h2) { - w = w1; - h = h1; - } else { - - h = h1 * w2 / w1; - if (h > h2) { - w = w1 * h2 / h1; - h = h2; - } else { - w = w2; - } - } - } else { - w = w1; - h = h1; - } - - setAllowMove(h > h2 || w > w2); - _rect = new Rectangle(getWidth() / 2 - w / 2 + offsetPoint.x, getHeight() / 2 - h / 2 + offsetPoint.y, w, h); - } else { - _rect = null; - } - } - - @Override - protected void paintComponent(Graphics g) { - Graphics2D g2d = (Graphics2D) g; - - if (renderImage != null) { - calcRect(); - if (renderImage.validate(View.getDefaultConfiguration()) != VolatileImage.IMAGE_OK) { - renderImage = View.createRenderImage(getWidth(), getHeight(), Transparency.TRANSLUCENT); - render(); - } - - if (renderImage != null) { - g2d.drawImage(renderImage, 0, 0, null); - } - } - g2d.setColor(Color.red); - - DecimalFormat df = new DecimalFormat(); - df.setMaximumFractionDigits(2); - df.setMinimumFractionDigits(0); - df.setGroupingUsed(false); - - float frameLoss = 100 - (getFpsIs() / fpsShouldBe * 100); - - if (Configuration._debugMode.get()) { - g2d.drawString("frameLoss:" + df.format(frameLoss) + "%", 20, 20); - } - } - } - - @Override - public void setBackground(Color bg) { - if (iconPanel != null) { - iconPanel.setBackground(bg); - } - super.setBackground(bg); - } - - @Override - public synchronized void addMouseListener(MouseListener l) { - iconPanel.addMouseListener(l); - } - - @Override - public synchronized void removeMouseListener(MouseListener l) { - iconPanel.removeMouseListener(l); - } - - @Override - public synchronized void addMouseMotionListener(MouseMotionListener l) { - iconPanel.addMouseMotionListener(l); - } - - @Override - public synchronized void removeMouseMotionListener(MouseMotionListener l) { - iconPanel.removeMouseMotionListener(l); - } - - private void updatePos(Timelined timelined, MouseEvent lastMouseEvent, Timer thisTimer) { - if (timelined != null) { - - BoundedTag bounded = (BoundedTag) timelined; - RECT rect = bounded.getRect(); - int width = rect.getWidth(); - double scale = 1.0; - /*if (width > swf.displayRect.getWidth()) { - scale = (double) swf.displayRect.getWidth() / (double) width; - }*/ - Matrix m = Matrix.getTranslateInstance(-rect.Xmin, -rect.Ymin); - m.scale(scale); - - Point p = lastMouseEvent == null ? null : lastMouseEvent.getPoint(); - - synchronized (ImagePanel.class) { - if (timer == thisTimer) { - cursorPosition = p; - } - } - } - } - - private void showSelectedName() { - if (selectedDepth > -1 && frame > -1) { - DepthState ds = timelined.getTimeline().getFrame(frame).layers.get(selectedDepth); - if (ds != null) { - CharacterTag cht = timelined.getTimeline().swf.getCharacter(ds.characterId); - if (cht != null) { - debugLabel.setText(cht.getName()); - } - } - } - } - - public void hideMouseSelection() { - if (selectedDepth > -1) { - showSelectedName(); - } else { - debugLabel.setText(" - "); - } - } - - public ImagePanel() { - super(new BorderLayout()); - //iconPanel.setHorizontalAlignment(JLabel.CENTER); - setOpaque(true); - setBackground(View.getDefaultBackgroundColor()); - - loop = true; - iconPanel = new IconPanel(); - //labelPan.add(label, new GridBagConstraints()); - add(iconPanel, BorderLayout.CENTER); - add(debugLabel, BorderLayout.NORTH); - iconPanel.addMouseListener(new MouseAdapter() { - - @Override - public void mouseEntered(MouseEvent e) { - synchronized (ImagePanel.class) { - lastMouseEvent = e; - redraw(); - } - } - - @Override - public void mouseExited(MouseEvent e) { - synchronized (ImagePanel.class) { - lastMouseEvent = null; - hideMouseSelection(); - redraw(); - } - } - - @Override - public void mousePressed(MouseEvent e) { - synchronized (ImagePanel.class) { - mouseButton = e.getButton(); - lastMouseEvent = e; - redraw(); - ButtonTag button = iconPanel.mouseOverButton; - if (button != null) { - DefineButtonSoundTag sounds = button.getSounds(); - if (sounds != null && sounds.buttonSoundChar2 != 0) { // OverUpToOverDown - playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar2), sounds.buttonSoundInfo2, timer); - } - } - } - } - - @Override - public void mouseReleased(MouseEvent e) { - synchronized (ImagePanel.class) { - mouseButton = 0; - lastMouseEvent = e; - redraw(); - ButtonTag button = iconPanel.mouseOverButton; - if (button != null) { - DefineButtonSoundTag sounds = button.getSounds(); - if (sounds != null && sounds.buttonSoundChar3 != 0) { // OverDownToOverUp - playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar3), sounds.buttonSoundInfo3, timer); - } - } - } - } - - }); - iconPanel.addMouseMotionListener(new MouseMotionAdapter() { - @Override - public void mouseMoved(MouseEvent e) { - synchronized (ImagePanel.class) { - lastMouseEvent = e; - redraw(); - } - } - - @Override - public void mouseDragged(MouseEvent e) { - synchronized (ImagePanel.class) { - lastMouseEvent = e; - redraw(); - } - } - - }); - } - - private synchronized void redraw() { - if (timer == null && timelined != null) { - startTimer(timelined.getTimeline(), false); - } - } - - @Override - public synchronized void zoom(Zoom zoom) { - boolean modified = this.zoom.value != zoom.value || this.zoom.fit != zoom.fit; - if (modified) { - this.zoom = zoom; - displayObjectCache.clear(); - redraw(); - if (textTag != null) { - setText(textTag, newTextTag); - } - - fireMediaDisplayStateChanged(); - } - } - - @Override - public synchronized BufferedImage printScreen() { - return iconPanel.getLastImage(); - } - - @Override - public synchronized double getZoomToFit() { - if (timelined != null) { - RECT bounds = timelined.getRect(); - double w1 = bounds.getWidth() / SWF.unitDivisor; - double h1 = bounds.getHeight() / SWF.unitDivisor; - - double w2 = getWidth(); - double h2 = getHeight(); - - double w; - double h; - h = h1 * w2 / w1; - if (h > h2) { - w = w1 * h2 / h1; - } else { - w = w2; - } - - if (w1 <= Double.MIN_NORMAL) { - return 1.0; - } - - return (double) w / (double) w1; - } - - return 1; - } - - @Override - public synchronized boolean zoomAvailable() { - return zoomAvailable; - } - - public void setTimelined(final Timelined drawable, final SWF swf, int frame) { - Stage stage = new Stage(drawable) { - @Override - public void callFrame(int frame) { - executeFrame(frame); - } - - @Override - public Object callFunction(long functionAddress, long functionLength, List args, Map regNames, Object thisObj) { - try { - SWFInputStream sis = new SWFInputStream(swf, swf.uncompressedData, functionAddress, (int) (functionAddress + functionLength)); - return execute(sis); - } catch (IOException ex) { - Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex); - } - return Undefined.INSTANCE; - } - - @Override - public int getCurrentFrame() { - return ImagePanel.this.getCurrentFrame(); - } - - @Override - public int getTotalFrames() { - return ImagePanel.this.getTotalFrames(); - } - - @Override - public void gotoFrame(int frame) { - ImagePanel.this.pause(); - ImagePanel.this.gotoFrame(frame); - } - - @Override - public void gotoLabel(String label) { - //TODO - } - - @Override - public void pause() { - ImagePanel.this.pause(); - } - - @Override - public void play() { - ImagePanel.this.play(); - } - - @Override - public void trace(Object... val) { - for (Object o : val) { - System.out.println("trace:" + o.toString()); - } - } - - }; - lda = new LocalDataArea(stage); - synchronized (ImagePanel.class) { - stopInternal(); - if (drawable instanceof ButtonTag) { - frame = ButtonTag.FRAME_UP; - } - - displayObjectCache.clear(); - this.timelined = drawable; - this.swf = swf; - zoomAvailable = true; - timer = null; - if (frame > -1) { - this.frame = frame; - this.stillFrame = true; - } else { - this.frame = 0; - this.stillFrame = false; - } - - loaded = true; - - if (drawable.getTimeline().getFrameCount() == 0) { - clearImagePanel(); - return; - } - - time = 0; - drawReady = false; - redraw(); - play(); - } - - synchronized (delayObject) { - try { - delayObject.wait(drawWaitLimit); - } catch (InterruptedException ex) { - logger.log(Level.SEVERE, null, ex); - } - } - - synchronized (ImagePanel.class) { - if (!drawReady) { - clearImagePanel(); - } - } - - fireMediaDisplayStateChanged(); - } - - public synchronized void setImage(SerializableImage image) { - lda = null; - setBackground(View.getSwfBackgroundColor()); - clear(); - - timelined = null; - loaded = true; - stillFrame = true; - zoomAvailable = false; - iconPanel.setImg(image); - drawReady = true; - - fireMediaDisplayStateChanged(); - } - - public synchronized void setText(TextTag textTag, TextTag newTextTag) { - setBackground(View.getSwfBackgroundColor()); - clear(); - - lda = null; - timelined = null; - loaded = true; - stillFrame = true; - zoomAvailable = true; - - this.textTag = textTag; - this.newTextTag = newTextTag; - - double zoomDouble = zoom.fit ? getZoomToFit() : zoom.value; - - RECT rect = textTag.getRect(); - int width = (int) (rect.getWidth() * zoomDouble); - int height = (int) (rect.getHeight() * zoomDouble); - SerializableImage image = new SerializableImage((int) (width / SWF.unitDivisor) + 1, - (int) (height / SWF.unitDivisor) + 1, SerializableImage.TYPE_INT_ARGB); - image.fillTransparent(); - Matrix m = Matrix.getTranslateInstance(-rect.Xmin * zoomDouble, -rect.Ymin * zoomDouble); - m.scale(zoomDouble); - textTag.toImage(0, 0, 0, new RenderContext(), image, false, m, m, m, new ConstantColorColorTransform(0xFFC0C0C0)); - - if (newTextTag != null) { - newTextTag.toImage(0, 0, 0, new RenderContext(), image, false, m, m, m, new ConstantColorColorTransform(0xFF000000)); - } - - iconPanel.setImg(image); - drawReady = true; - - fireMediaDisplayStateChanged(); - } - - private synchronized void clearImagePanel() { - iconPanel.setImg(null); - } - - @Override - public synchronized int getCurrentFrame() { - return frame; - } - - @Override - public synchronized int getTotalFrames() { - if (timelined == null) { - return 0; - } - if (stillFrame) { - return 0; - } - return timelined.getTimeline().getFrameCount(); - } - - @Override - public void pause() { - stopInternal(); - redraw(); - } - - @Override - public void stop() { - stopInternal(); - rewind(); - redraw(); - } - - @Override - public void close() throws IOException { - stopInternal(); - } - - private void stopAllSounds() { - for (int i = soundPlayers.size() - 1; i >= 0; i--) { - SoundTagPlayer pl = soundPlayers.get(i); - pl.close(); - } - soundPlayers.clear(); - } - - private void clear() { - if (timer != null) { - timer.cancel(); - timer = null; - fireMediaDisplayStateChanged(); - } - - textTag = null; - newTextTag = null; - displayObjectCache.clear(); - } - - private void nextFrame(Timer thisTimer, final int cnt, final int timeShouldBe) { - drawFrame(thisTimer, true); - - synchronized (ImagePanel.class) { - if (timelined != null && timer == thisTimer) { - int frameCount = timelined.getTimeline().getFrameCount(); - - int oldFrame = frame; - for (int i = 0; i < cnt; i++) { - if (!stillFrame && frameCount > 0) { - frame = (frame + 1) % frameCount; - } - - if (!stillFrame && frame == frameCount - 1 && !loop) { - stopInternal(); - return; - } - - if (i < cnt - 1) { //skip not displayed frames, do not display, only play sounds, etc. - drawFrame(thisTimer, false); - } - } - if (frame != oldFrame) { - if (frame == 0) { - stopAllSounds(); - } - time = 0; - } else { - time = timeShouldBe; - } - } - } - - fireMediaDisplayStateChanged(); - } - - private static SerializableImage getFrame(SWF swf, int frame, int time, Timelined drawable, RenderContext renderContext, int selectedDepth, double zoom) { - Timeline timeline = drawable.getTimeline(); - //int mouseButton = renderContext.mouseButton; - //Point cursorPosition = renderContext.cursorPosition; - //String key = "drawable_" + frame + "_" + drawable.hashCode() + "_" + mouseButton + "_depth" + selectedDepth + "_" + (cursorPosition == null ? "out" : cursorPosition.hashCode()) + "_" + zoom + "_" + timeline.fontFrameNum; - SerializableImage img; - //SerializableImage img = swf.getFromCache(key); - //if (img == null) { - //boolean shouldCache = timeline.isSingleFrame(frame); - RECT rect = drawable.getRect(); - - int width = (int) (rect.getWidth() * zoom); - int height = (int) (rect.getHeight() * zoom); - SerializableImage image = new SerializableImage((int) Math.ceil(width / SWF.unitDivisor), - (int) Math.ceil(height / SWF.unitDivisor), SerializableImage.TYPE_INT_ARGB); - //renderContext.borderImage = new SerializableImage(image.getWidth(), image.getHeight(), SerializableImage.TYPE_INT_ARGB); - image.fillTransparent(); - Matrix m = new Matrix(); - m.translate(-rect.Xmin * zoom, -rect.Ymin * zoom); - m.scale(zoom); - timeline.toImage(frame, time, renderContext, image, false, m, m, m, null); - - Graphics2D gg = (Graphics2D) image.getGraphics(); - gg.setStroke(new BasicStroke(3)); - gg.setPaint(Color.green); - gg.setTransform(AffineTransform.getTranslateInstance(0, 0)); - DepthState ds = null; - if (timeline.getFrameCount() > frame) { - ds = timeline.getFrame(frame).layers.get(selectedDepth); - } - - if (ds != null) { - CharacterTag cht = swf.getCharacter(ds.characterId); - if (cht != null) { - if (cht instanceof DrawableTag) { - DrawableTag dt = (DrawableTag) cht; - int drawableFrameCount = dt.getNumFrames(); - if (drawableFrameCount == 0) { - drawableFrameCount = 1; - } - - int dframe = time % drawableFrameCount; - Shape outline = dt.getOutline(dframe, time, ds.ratio, renderContext, Matrix.getScaleInstance(1 / SWF.unitDivisor).concatenate(m.concatenate(new Matrix(ds.matrix))), true); - Rectangle bounds = outline.getBounds(); - gg.setStroke(new BasicStroke(2.0f, - BasicStroke.CAP_BUTT, - BasicStroke.JOIN_MITER, - 10.0f, new float[]{10.0f}, 0.0f)); - gg.setPaint(Color.red); - gg.draw(bounds); - } - } - } - - img = image; - - /*if (shouldCache) { - swf.putToCache(key, img); - }*/ - //} - return img; - } - - private Object execute(SWFInputStream sis) throws IOException { - if (!Configuration.internalFlashViewerExecuteAs12.get()) { - return Undefined.INSTANCE; - } - if (lda == null) { - return Undefined.INSTANCE; - } - long ip = sis.getPos(); - //System.err.println("============="); - Action a; - while ((a = sis.readAction()) != null) { - int actionLengthWithHeader = a.getTotalActionLength(); - a.setAddress(ip); - a.execute(lda); - /*System.err.print("" + a + ", stack: ["); - for (Object o : lda.stack) { - System.err.print("" + o + ","); - } - System.err.println("]");*/ - if (lda.returnValue != null) { - return lda.returnValue; - } - if (lda.jump != null) { - ip = lda.jump; - lda.jump = null; - } else { - ip += actionLengthWithHeader; - } - sis.seek(ip); - } - return Undefined.INSTANCE; - } - - private void executeFrame(int frame) { - if (!Configuration.internalFlashViewerExecuteAs12.get()) { - return; - } - if (timelined == null) { - return; - } - Frame f = timelined.getTimeline().getFrame(frame); - List actions = f.actions; - if (lda != null) { - lda.clear(); - } - for (DoActionTag src : actions) { - try { - ByteArrayRange actionBytes = src.getActionBytes(); - int prevLength = actionBytes.getPos(); - SWFInputStream rri = new SWFInputStream(swf, actionBytes.getArray(), 0, prevLength + actionBytes.getLength()); - if (prevLength != 0) { - rri.seek(prevLength); - } - execute(rri); - } catch (IOException ex) { - Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex); - } - - } - } - - private void drawFrame(Timer thisTimer, boolean display) { - Timelined timelined; - MouseEvent lastMouseEvent; - int frame; - int time; - Point cursorPosition; - int mouseButton; - int selectedDepth; - Zoom zoom; - SWF swf; - - synchronized (ImagePanel.class) { - timelined = this.timelined; - lastMouseEvent = this.lastMouseEvent; - } - - synchronized (ImagePanel.class) { - frame = this.frame; - time = this.time; - cursorPosition = this.cursorPosition; - if (cursorPosition != null) { - cursorPosition = iconPanel.toImagePoint(cursorPosition); - } - - mouseButton = this.mouseButton; - selectedDepth = this.selectedDepth; - zoom = this.zoom; - swf = this.swf; - } - - if (timelined == null) { - return; - } - - RenderContext renderContext = new RenderContext(); - renderContext.displayObjectCache = displayObjectCache; - if (cursorPosition != null) { - renderContext.cursorPosition = new Point((int) (cursorPosition.x * SWF.unitDivisor), (int) (cursorPosition.y * SWF.unitDivisor)); - } - - renderContext.mouseButton = mouseButton; - renderContext.stateUnderCursor = new ArrayList<>(); - - SerializableImage img; - try { - Timeline timeline = timelined.getTimeline(); - if (frame >= timeline.getFrameCount()) { - return; - } - - double zoomDouble = zoom.fit ? getZoomToFit() : zoom.value; - if (lowQuality) { - zoomDouble /= LQ_FACTOR; - } - updatePos(timelined, lastMouseEvent, thisTimer); - - Matrix mat = new Matrix(); - mat.translateX = swf.displayRect.Xmin; - mat.translateY = swf.displayRect.Ymin; - - img = null; - if (display) { - Stopwatch sw = Stopwatch.startNew(); - img = getFrame(swf, frame, time, timelined, renderContext, selectedDepth, zoomDouble); - sw.stop(); - if (sw.getElapsedMilliseconds() > 100) { - logger.log(Level.WARNING, "Slow rendering. {0}. frame, time={1}, {2}ms", new Object[]{frame, time, sw.getElapsedMilliseconds()}); - } - - if (renderContext.borderImage != null) { - img = renderContext.borderImage; - } - } - - List sounds = new ArrayList<>(); - List soundClasses = new ArrayList<>(); - timeline.getSounds(frame, time, renderContext.mouseOverButton, mouseButton, sounds, soundClasses); - for (int cid : swf.getCharacters().keySet()) { - CharacterTag c = swf.getCharacter(cid); - for (String cls : soundClasses) { - if (cls.equals(c.getClassName())) { - sounds.add(cid); - } - } - } - - for (int sndId : sounds) { - CharacterTag c = swf.getCharacter(sndId); - if (c instanceof SoundTag) { - SoundTag st = (SoundTag) c; - playSound(st, null, thisTimer); - } - } - executeFrame(frame); - } catch (Throwable ex) { - // swf was closed during the rendering probably - return; - } - if (display) { - - StringBuilder ret = new StringBuilder(); - - if (cursorPosition != null) { - ret.append(" [").append(cursorPosition.x).append(",").append(cursorPosition.y).append("] : "); - } - - boolean handCursor = renderContext.mouseOverButton != null; - boolean first = true; - for (int i = renderContext.stateUnderCursor.size() - 1; i >= 0; i--) { - DepthState ds = renderContext.stateUnderCursor.get(i); - if (!first) { - ret.append(", "); - } - - first = false; - CharacterTag c = swf.getCharacter(ds.characterId); - ret.append(c.toString()); - } - - if (first) { - ret.append(" - "); - } - - ButtonTag lastMouseOverButton; - synchronized (ImagePanel.class) { - if (timer == thisTimer) { - iconPanel.setImg(img); - lastMouseOverButton = iconPanel.mouseOverButton; - iconPanel.mouseOverButton = renderContext.mouseOverButton; - debugLabel.setText(ret.toString()); - if (handCursor) { - iconPanel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } else if (iconPanel.hasAllowMove()) { - iconPanel.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); - } else { - iconPanel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - - if (lastMouseOverButton != renderContext.mouseOverButton) { - ButtonTag b = renderContext.mouseOverButton; - if (b != null) { - // New mouse entered - DefineButtonSoundTag sounds = b.getSounds(); - if (sounds != null && sounds.buttonSoundChar1 != 0) { // IdleToOverUp - playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar1), sounds.buttonSoundInfo1, timer); - } - } - - b = lastMouseOverButton; - if (b != null) { - // Old mouse leave - DefineButtonSoundTag sounds = b.getSounds(); - if (sounds != null && sounds.buttonSoundChar0 != 0) { // OverUpToIdle - playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar0), sounds.buttonSoundInfo0, timer); - } - } - } - - drawReady = true; - synchronized (delayObject) { - delayObject.notify(); - } - } - } - } - } - - private void playSound(SoundTag st, SOUNDINFO soundInfo, Timer thisTimer) { - final SoundTagPlayer sp; - try { - int loopCount = 1; - if (soundInfo != null && soundInfo.hasLoops) { - loopCount = Math.max(1, soundInfo.loopCount); - } - - sp = new SoundTagPlayer(st, loopCount, false); - sp.addEventListener(new MediaDisplayListener() { - - @Override - public void mediaDisplayStateChanged(MediaDisplay source) { - } - - @Override - public void playingFinished(MediaDisplay source) { - synchronized (ImagePanel.class) { - sp.close(); - soundPlayers.remove(sp); - } - } - }); - - synchronized (ImagePanel.class) { - if (timer != null && timer == thisTimer) { - soundPlayers.add(sp); - sp.play(); - } else { - sp.close(); - } - } - } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) { - logger.log(Level.SEVERE, "Error during playing sound", ex); - } - } - - public synchronized void clearAll() { - stopInternal(); - clearImagePanel(); - timelined = null; - swf = null; - - fireMediaDisplayStateChanged(); - } - - private synchronized void stopInternal() { - clear(); - stopAllSounds(); - } - - @Override - public synchronized void play() { - stopInternal(); - if (timelined != null) { - Timeline timeline = timelined.getTimeline(); - if (!stillFrame && frame == timeline.getFrameCount() - 1) { - frame = 0; - } - - startTimer(timeline, true); - } - } - - private synchronized void setMsPerFrame(int val) { - this.msPerFrame = val; - } - - private synchronized int getMsPerFrame() { - return this.msPerFrame; - } - - private long startRun = 0L; - - private final long startDrop = 0L; - - private int skippedFrames = 0; - - private float fpsShouldBe = 0; - - private float fpsIs = 0; - - private Timer fpsTimer; - - private int startFrame = 0; - - private synchronized void setFpsIs(float val) { - fpsIs = val; - } - - private synchronized float getFpsIs() { - return fpsIs; - } - - private synchronized void setSkippedFrames(int val) { - skippedFrames = val; - } - - private synchronized void addSkippedFrames(int val) { - skippedFrames += val; - } - - private synchronized int getSkippedFrames() { - return skippedFrames; - } - - private synchronized int getAndResetSkippedFrames() { - int ret = skippedFrames; - skippedFrames = 0; - return ret; - } - - private void scheduleTask(boolean singleFrame, long msDelay) { - TimerTask task = new TimerTask() { - public final Timer thisTimer = timer; - - public final boolean isSingleFrame = singleFrame; - - private long lastRun = 0L; - - @Override - public void run() { - try { - synchronized (ImagePanel.class) { - if (timer != thisTimer) { - return; - } - } - lastRun = System.currentTimeMillis(); - int curFrame = frame; - long delay = getMsPerFrame(); - if (isSingleFrame) { - drawFrame(thisTimer, true); - synchronized (ImagePanel.class) { - thisTimer.cancel(); - if (timer == thisTimer) { - timer = null; - } - } - - fireMediaDisplayStateChanged(); - } else { - //Time before drawing current frame - long frameTimeMsIs = System.currentTimeMillis(); - //Total number of frames in this timeline - int frameCount = timelined.getTimeline().getFrameCount(); - //How many ticks (= times where frame should be displayed in framerate) are there from hitting play button - int ticksFromStart = (int) Math.floor((frameTimeMsIs - startRun) / (double) getMsPerFrame()) + 1; - //Add ticks to first frame when hitting play button, ignoring total framecount => this value can be larger than number of frames in timeline - int frameOverMaxShouldBeNow = startFrame + ticksFromStart; - //Apply maximum frames repating, this is actual frame which should be drawed now - int frameShouldBeNow = frameOverMaxShouldBeNow % frameCount; - - //How many frames are there between last displayed frame and now. For perfect display(=no framedrop), value should be 1 - int skipFrames = frameShouldBeNow - curFrame; - //It is negative for some reason, this will display older frames. Add frameCount to stay in modulu framecount. - if (skipFrames < 0) { - skipFrames += frameCount; - } - //Change for more than 1 frame - if (skipFrames > 1) { - addSkippedFrames(skipFrames - 1); //drop those frames, draw only last one - } - //Frame "time" - ticks in current frame - int currentFrameTicks = 0; - if (frameCount == 1) { //We have only one frame, so the ticks on that frame equal ticks on whole timeline - currentFrameTicks = ticksFromStart; - } - nextFrame(thisTimer, skipFrames, currentFrameTicks); - - long afterDrawFrameTimeMsIs = System.currentTimeMillis(); - - int nextFrameOverMax = frameOverMaxShouldBeNow; - while (delay < 0) { //while the frame time already passed - nextFrameOverMax++; - long nextFrameOverMaxTimeMsShouldBe = startRun + getMsPerFrame() * nextFrameOverMax; - delay = nextFrameOverMaxTimeMsShouldBe - afterDrawFrameTimeMsIs; - } - } - //schedule next run of the task - scheduleTask(isSingleFrame, delay); - - } catch (Exception ex) { - logger.log(Level.SEVERE, "Frame drawing error", ex); - } - } - }; - if (timer != null) { - timer.schedule(task, msDelay); - } - } - - private synchronized void startTimer(Timeline timeline, boolean playing) { - - startRun = System.currentTimeMillis(); - startFrame = frame; - float frameRate = timeline.frameRate; - setMsPerFrame(frameRate == 0 ? 1000 : (int) (1000.0 / frameRate)); - final boolean singleFrame = !playing - || (stillFrame && timeline.isSingleFrame(frame)) - || (!stillFrame && timeline.getRealFrameCount() <= 1 && timeline.isSingleFrame()); - - if (fpsTimer == null) { - fpsTimer = new Timer(); - fpsTimer.schedule(new TimerTask() { - @Override - public void run() { - float skipped = getAndResetSkippedFrames(); - setFpsIs(fpsShouldBe - skipped); - } - }, 1000, 1000); - } - timer = new Timer(); - fpsShouldBe = timeline.frameRate; - fpsIs = fpsShouldBe; - scheduleTask(singleFrame, 0); - - } - - @Override - public synchronized void rewind() { - frame = 0; - fireMediaDisplayStateChanged(); - } - - @Override - public synchronized boolean isPlaying() { - if (timelined == null || stillFrame) { - return false; - } - - return (timelined.getTimeline().getFrameCount() <= 1) || (timer != null); - } - - @Override - public void setLoop(boolean loop) { - this.loop = loop; - } - - @Override - public synchronized void gotoFrame(int frame) { - if (timelined == null) { - return; - } - Timeline timeline = timelined.getTimeline(); - if (frame >= timeline.getFrameCount()) { - return; - } - if (frame < 0) { - return; - } - - this.frame = frame; - stopInternal(); - redraw(); - fireMediaDisplayStateChanged(); - } - - @Override - public synchronized float getFrameRate() { - if (timelined == null) { - return 1; - } - if (stillFrame) { - return 1; - } - return timelined.getTimeline().frameRate; - } - - @Override - public synchronized boolean isLoaded() { - return loaded; - } - - @Override - public boolean loopAvailable() { - return false; - } - - @Override - public boolean screenAvailable() { - return true; - } - - @Override - public synchronized Zoom getZoom() { - return zoom; - } -} +/* + * Copyright (C) 2010-2016 JPEXS + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.jpexs.decompiler.flash.gui; + +import com.jpexs.decompiler.flash.SWF; +import com.jpexs.decompiler.flash.SWFInputStream; +import com.jpexs.decompiler.flash.action.Action; +import com.jpexs.decompiler.flash.action.LocalDataArea; +import com.jpexs.decompiler.flash.action.Stage; +import com.jpexs.decompiler.flash.configuration.Configuration; +import com.jpexs.decompiler.flash.ecma.Undefined; +import com.jpexs.decompiler.flash.exporters.commonshape.Matrix; +import com.jpexs.decompiler.flash.gui.player.MediaDisplay; +import com.jpexs.decompiler.flash.gui.player.MediaDisplayListener; +import com.jpexs.decompiler.flash.gui.player.Zoom; +import com.jpexs.decompiler.flash.tags.DefineButtonSoundTag; +import com.jpexs.decompiler.flash.tags.DoActionTag; +import com.jpexs.decompiler.flash.tags.base.BoundedTag; +import com.jpexs.decompiler.flash.tags.base.ButtonTag; +import com.jpexs.decompiler.flash.tags.base.CharacterTag; +import com.jpexs.decompiler.flash.tags.base.DrawableTag; +import com.jpexs.decompiler.flash.tags.base.PlaceObjectTypeTag; +import com.jpexs.decompiler.flash.tags.base.RenderContext; +import com.jpexs.decompiler.flash.tags.base.SoundTag; +import com.jpexs.decompiler.flash.tags.base.TextTag; +import com.jpexs.decompiler.flash.timeline.DepthState; +import com.jpexs.decompiler.flash.timeline.Frame; +import com.jpexs.decompiler.flash.timeline.Timeline; +import com.jpexs.decompiler.flash.timeline.Timelined; +import com.jpexs.decompiler.flash.types.ConstantColorColorTransform; +import com.jpexs.decompiler.flash.types.RECT; +import com.jpexs.decompiler.flash.types.SOUNDINFO; +import com.jpexs.helpers.ByteArrayRange; +import com.jpexs.helpers.Cache; +import com.jpexs.helpers.SerializableImage; +import com.jpexs.helpers.Stopwatch; +import java.awt.AlphaComposite; +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.Transparency; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionAdapter; +import java.awt.event.MouseMotionListener; +import java.awt.geom.AffineTransform; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; +import java.io.IOException; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.UnsupportedAudioFileException; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + * + * @author JPEXS + */ +public final class ImagePanel extends JPanel implements MediaDisplay { + + private static final Logger logger = Logger.getLogger(ImagePanel.class.getName()); + + private final List listeners = new ArrayList<>(); + + private Timelined timelined; + + private boolean stillFrame = false; + + private Timer timer; + + private int frame = -1; + + private boolean loop; + + private LocalDataArea lda; + + private boolean zoomAvailable = false; + + private SWF swf; + + private boolean loaded; + + private int mouseButton; + + private final JLabel debugLabel = new JLabel("-"); + + private Point cursorPosition = null; + + private MouseEvent lastMouseEvent = null; + + private final List soundPlayers = new ArrayList<>(); + + private final Cache displayObjectCache = Cache.getInstance(false, false, "displayObject"); + + private final IconPanel iconPanel; + + private int time = 0; + + private int selectedDepth = -1; + + private Zoom zoom = new Zoom(); + + private final Object delayObject = new Object(); + + private boolean drawReady; + + private final int drawWaitLimit = 50; // ms + + private TextTag textTag; + + private TextTag newTextTag; + + private int msPerFrame; + + private final boolean lowQuality = false; + + private final double LQ_FACTOR = 2; + + public synchronized void selectDepth(int depth) { + if (depth != selectedDepth) { + this.selectedDepth = depth; + } + + hideMouseSelection(); + } + + public void fireMediaDisplayStateChanged() { + for (MediaDisplayListener l : listeners) { + l.mediaDisplayStateChanged(this); + } + } + + @Override + public void addEventListener(MediaDisplayListener listener) { + listeners.add(listener); + } + + @Override + public void removeEventListener(MediaDisplayListener listener) { + listeners.remove(listener); + } + + private class IconPanel extends JPanel { + + private SerializableImage _img; + + private Rectangle _rect = null; + + private ButtonTag mouseOverButton = null; + + private boolean autoFit = false; + + private boolean allowMove = true; + + private Point dragStart = null; + + private Point offsetPoint = new Point(0, 0); + + private synchronized SerializableImage getImg() { + return _img; + } + + public synchronized Rectangle getRect() { + return _rect; + } + + public boolean hasAllowMove() { + return allowMove; + } + + VolatileImage renderImage; + + public void render() { + SerializableImage img = getImg(); + Rectangle rect = getRect(); + if (img == null) { + return; + } + + Graphics2D g2 = null; + VolatileImage ri; + do { + ri = this.renderImage; + if (ri == null) { + return; + } + + int valid = ri.validate(View.getDefaultConfiguration()); + + if (valid == VolatileImage.IMAGE_INCOMPATIBLE) { + ri = View.createRenderImage(getWidth(), getHeight(), Transparency.TRANSLUCENT); + } + + try { + g2 = ri.createGraphics(); + g2.setPaint(View.transparentPaint); + g2.fill(new Rectangle(0, 0, getWidth(), getHeight())); + g2.setComposite(AlphaComposite.SrcOver); + g2.setPaint(View.getSwfBackgroundColor()); + g2.fill(new Rectangle(0, 0, getWidth(), getHeight())); + + g2.setComposite(AlphaComposite.SrcOver); + if (rect != null) { + g2.drawImage(img.getBufferedImage(), rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, 0, 0, img.getWidth(), img.getHeight(), null); + } + } finally { + if (g2 != null) { + g2.dispose(); + } + } + + } while (ri.contentsLost()); + } + + public IconPanel() { + addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + int width = getWidth(); + int height = getHeight(); + if (width > 0 && height > 0) { + renderImage = View.createRenderImage(width, height, Transparency.TRANSLUCENT); + } else { + renderImage = null; + } + + if (_img != null) { + calcRect(); + render(); + } + repaint(); + } + }); + addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + dragStart = e.getPoint(); + } + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + dragStart = null; + } + } + }); + addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseDragged(MouseEvent e) { + if (dragStart != null && allowMove) { + Point dragEnd = e.getPoint(); + Point delta = new Point(dragEnd.x - dragStart.x, dragEnd.y - dragStart.y); + offsetPoint.x += delta.x; + offsetPoint.y += delta.y; + dragStart = dragEnd; + repaint(); + } + } + }); + } + + public void setAutoFit(boolean autoFit) { + this.autoFit = autoFit; + repaint(); + } + + public synchronized BufferedImage getLastImage() { + if (_img == null) { + return null; + } + return _img.getBufferedImage(); + } + + public synchronized void setImg(SerializableImage img) { + this._img = img; + if (img != null) { + calcRect(); + render(); + } + repaint(); + } + + public synchronized Point toImagePoint(Point p) { + if (_img == null) { + return null; + } + + return new Point((p.x - _rect.x) * _img.getWidth() / _rect.width, (p.y - _rect.y) * _img.getHeight() / _rect.height); + } + + private void setAllowMove(boolean allowMove) { + this.allowMove = allowMove; + if (!allowMove) { + offsetPoint = new Point(); + } + } + + private synchronized void calcRect() { + if (_img != null) { + int w1 = (int) (_img.getWidth() * (lowQuality ? LQ_FACTOR : 1)); + int h1 = (int) (_img.getHeight() * (lowQuality ? LQ_FACTOR : 1)); + + int w2 = getWidth(); + int h2 = getHeight(); + + int w; + int h; + if (autoFit) { + if (w1 <= w2 && h1 <= h2) { + w = w1; + h = h1; + } else { + + h = h1 * w2 / w1; + if (h > h2) { + w = w1 * h2 / h1; + h = h2; + } else { + w = w2; + } + } + } else { + w = w1; + h = h1; + } + + setAllowMove(h > h2 || w > w2); + _rect = new Rectangle(getWidth() / 2 - w / 2 + offsetPoint.x, getHeight() / 2 - h / 2 + offsetPoint.y, w, h); + } else { + _rect = null; + } + } + + @Override + protected void paintComponent(Graphics g) { + Graphics2D g2d = (Graphics2D) g; + + VolatileImage ri = this.renderImage; + if (ri != null) { + calcRect(); + if (ri.validate(View.getDefaultConfiguration()) != VolatileImage.IMAGE_OK) { + ri = View.createRenderImage(getWidth(), getHeight(), Transparency.TRANSLUCENT); + render(); + } + + if (ri != null) { + g2d.drawImage(ri, 0, 0, null); + } + } + g2d.setColor(Color.red); + + DecimalFormat df = new DecimalFormat(); + df.setMaximumFractionDigits(2); + df.setMinimumFractionDigits(0); + df.setGroupingUsed(false); + + float frameLoss = 100 - (getFpsIs() / fpsShouldBe * 100); + + if (Configuration._debugMode.get()) { + g2d.drawString("frameLoss:" + df.format(frameLoss) + "%", 20, 20); + } + } + } + + @Override + public void setBackground(Color bg) { + if (iconPanel != null) { + iconPanel.setBackground(bg); + } + super.setBackground(bg); + } + + @Override + public synchronized void addMouseListener(MouseListener l) { + iconPanel.addMouseListener(l); + } + + @Override + public synchronized void removeMouseListener(MouseListener l) { + iconPanel.removeMouseListener(l); + } + + @Override + public synchronized void addMouseMotionListener(MouseMotionListener l) { + iconPanel.addMouseMotionListener(l); + } + + @Override + public synchronized void removeMouseMotionListener(MouseMotionListener l) { + iconPanel.removeMouseMotionListener(l); + } + + private void updatePos(Timelined timelined, MouseEvent lastMouseEvent, Timer thisTimer) { + if (timelined != null) { + + BoundedTag bounded = (BoundedTag) timelined; + RECT rect = bounded.getRect(); + int width = rect.getWidth(); + double scale = 1.0; + /*if (width > swf.displayRect.getWidth()) { + scale = (double) swf.displayRect.getWidth() / (double) width; + }*/ + Matrix m = Matrix.getTranslateInstance(-rect.Xmin, -rect.Ymin); + m.scale(scale); + + Point p = lastMouseEvent == null ? null : lastMouseEvent.getPoint(); + + synchronized (ImagePanel.class) { + if (timer == thisTimer) { + cursorPosition = p; + } + } + } + } + + private void showSelectedName() { + if (selectedDepth > -1 && frame > -1) { + DepthState ds = timelined.getTimeline().getFrame(frame).layers.get(selectedDepth); + if (ds != null) { + CharacterTag cht = timelined.getTimeline().swf.getCharacter(ds.characterId); + if (cht != null) { + debugLabel.setText(cht.getName()); + } + } + } + } + + public void hideMouseSelection() { + if (selectedDepth > -1) { + showSelectedName(); + } else { + debugLabel.setText(" - "); + } + } + + public ImagePanel() { + super(new BorderLayout()); + //iconPanel.setHorizontalAlignment(JLabel.CENTER); + setOpaque(true); + setBackground(View.getDefaultBackgroundColor()); + + loop = true; + iconPanel = new IconPanel(); + //labelPan.add(label, new GridBagConstraints()); + add(iconPanel, BorderLayout.CENTER); + add(debugLabel, BorderLayout.NORTH); + iconPanel.addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + synchronized (ImagePanel.class) { + lastMouseEvent = e; + redraw(); + } + } + + @Override + public void mouseExited(MouseEvent e) { + synchronized (ImagePanel.class) { + lastMouseEvent = null; + hideMouseSelection(); + redraw(); + } + } + + @Override + public void mousePressed(MouseEvent e) { + synchronized (ImagePanel.class) { + mouseButton = e.getButton(); + lastMouseEvent = e; + redraw(); + ButtonTag button = iconPanel.mouseOverButton; + if (button != null) { + DefineButtonSoundTag sounds = button.getSounds(); + if (sounds != null && sounds.buttonSoundChar2 != 0) { // OverUpToOverDown + playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar2), sounds.buttonSoundInfo2, timer); + } + } + } + } + + @Override + public void mouseReleased(MouseEvent e) { + synchronized (ImagePanel.class) { + mouseButton = 0; + lastMouseEvent = e; + redraw(); + ButtonTag button = iconPanel.mouseOverButton; + if (button != null) { + DefineButtonSoundTag sounds = button.getSounds(); + if (sounds != null && sounds.buttonSoundChar3 != 0) { // OverDownToOverUp + playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar3), sounds.buttonSoundInfo3, timer); + } + } + } + } + }); + iconPanel.addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseMoved(MouseEvent e) { + synchronized (ImagePanel.class) { + lastMouseEvent = e; + redraw(); + } + } + + @Override + public void mouseDragged(MouseEvent e) { + synchronized (ImagePanel.class) { + lastMouseEvent = e; + redraw(); + } + } + }); + } + + private synchronized void redraw() { + if (timer == null && timelined != null) { + startTimer(timelined.getTimeline(), false); + } + } + + @Override + public synchronized void zoom(Zoom zoom) { + boolean modified = this.zoom.value != zoom.value || this.zoom.fit != zoom.fit; + if (modified) { + this.zoom = zoom; + displayObjectCache.clear(); + redraw(); + if (textTag != null) { + setText(textTag, newTextTag); + } + + fireMediaDisplayStateChanged(); + } + } + + @Override + public synchronized BufferedImage printScreen() { + return iconPanel.getLastImage(); + } + + @Override + public synchronized double getZoomToFit() { + if (timelined != null) { + RECT bounds = timelined.getRect(); + double w1 = bounds.getWidth() / SWF.unitDivisor; + double h1 = bounds.getHeight() / SWF.unitDivisor; + + double w2 = getWidth(); + double h2 = getHeight(); + + double w; + double h; + h = h1 * w2 / w1; + if (h > h2) { + w = w1 * h2 / h1; + } else { + w = w2; + } + + if (w1 <= Double.MIN_NORMAL) { + return 1.0; + } + + return (double) w / (double) w1; + } + + return 1; + } + + @Override + public synchronized boolean zoomAvailable() { + return zoomAvailable; + } + + public void setTimelined(final Timelined drawable, final SWF swf, int frame) { + Stage stage = new Stage(drawable) { + @Override + public void callFrame(int frame) { + executeFrame(frame); + } + + @Override + public Object callFunction(long functionAddress, long functionLength, List args, Map regNames, Object thisObj) { + try { + SWFInputStream sis = new SWFInputStream(swf, swf.uncompressedData, functionAddress, (int) (functionAddress + functionLength)); + return execute(sis); + } catch (IOException ex) { + Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex); + } + return Undefined.INSTANCE; + } + + @Override + public int getCurrentFrame() { + return ImagePanel.this.getCurrentFrame(); + } + + @Override + public int getTotalFrames() { + return ImagePanel.this.getTotalFrames(); + } + + @Override + public void gotoFrame(int frame) { + ImagePanel.this.pause(); + ImagePanel.this.gotoFrame(frame); + } + + @Override + public void gotoLabel(String label) { + //TODO + } + + @Override + public void pause() { + ImagePanel.this.pause(); + } + + @Override + public void play() { + ImagePanel.this.play(); + } + + @Override + public void trace(Object... val) { + for (Object o : val) { + System.out.println("trace:" + o.toString()); + } + } + }; + lda = new LocalDataArea(stage); + synchronized (ImagePanel.class) { + stopInternal(); + if (drawable instanceof ButtonTag) { + frame = ButtonTag.FRAME_UP; + } + + displayObjectCache.clear(); + this.timelined = drawable; + this.swf = swf; + zoomAvailable = true; + timer = null; + if (frame > -1) { + this.frame = frame; + this.stillFrame = true; + } else { + this.frame = 0; + this.stillFrame = false; + } + + loaded = true; + + if (drawable.getTimeline().getFrameCount() == 0) { + clearImagePanel(); + return; + } + + time = 0; + drawReady = false; + redraw(); + play(); + } + + synchronized (delayObject) { + try { + delayObject.wait(drawWaitLimit); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + + synchronized (ImagePanel.class) { + if (!drawReady) { + clearImagePanel(); + } + } + + fireMediaDisplayStateChanged(); + } + + public synchronized void setImage(SerializableImage image) { + lda = null; + setBackground(View.getSwfBackgroundColor()); + clear(); + + timelined = null; + loaded = true; + stillFrame = true; + zoomAvailable = false; + iconPanel.setImg(image); + drawReady = true; + + fireMediaDisplayStateChanged(); + } + + public synchronized void setText(TextTag textTag, TextTag newTextTag) { + setBackground(View.getSwfBackgroundColor()); + clear(); + + lda = null; + timelined = null; + loaded = true; + stillFrame = true; + zoomAvailable = true; + + this.textTag = textTag; + this.newTextTag = newTextTag; + + double zoomDouble = zoom.fit ? getZoomToFit() : zoom.value; + + RECT rect = textTag.getRect(); + int width = (int) (rect.getWidth() * zoomDouble); + int height = (int) (rect.getHeight() * zoomDouble); + SerializableImage image = new SerializableImage((int) (width / SWF.unitDivisor) + 1, + (int) (height / SWF.unitDivisor) + 1, SerializableImage.TYPE_INT_ARGB); + image.fillTransparent(); + Matrix m = Matrix.getTranslateInstance(-rect.Xmin * zoomDouble, -rect.Ymin * zoomDouble); + m.scale(zoomDouble); + textTag.toImage(0, 0, 0, new RenderContext(), image, false, m, m, m, new ConstantColorColorTransform(0xFFC0C0C0)); + + if (newTextTag != null) { + newTextTag.toImage(0, 0, 0, new RenderContext(), image, false, m, m, m, new ConstantColorColorTransform(0xFF000000)); + } + + iconPanel.setImg(image); + drawReady = true; + + fireMediaDisplayStateChanged(); + } + + private synchronized void clearImagePanel() { + iconPanel.setImg(null); + } + + @Override + public synchronized int getCurrentFrame() { + return frame; + } + + @Override + public synchronized int getTotalFrames() { + if (timelined == null) { + return 0; + } + if (stillFrame) { + return 0; + } + return timelined.getTimeline().getFrameCount(); + } + + @Override + public void pause() { + stopInternal(); + redraw(); + } + + @Override + public void stop() { + stopInternal(); + rewind(); + redraw(); + } + + @Override + public void close() throws IOException { + stopInternal(); + } + + private void stopAllSounds() { + for (int i = soundPlayers.size() - 1; i >= 0; i--) { + SoundTagPlayer pl = soundPlayers.get(i); + pl.close(); + } + soundPlayers.clear(); + } + + private void clear() { + if (timer != null) { + timer.cancel(); + timer = null; + fireMediaDisplayStateChanged(); + } + + textTag = null; + newTextTag = null; + displayObjectCache.clear(); + } + + private void nextFrame(Timer thisTimer, final int cnt, final int timeShouldBe) { + drawFrame(thisTimer, true); + + synchronized (ImagePanel.class) { + if (timelined != null && timer == thisTimer) { + int frameCount = timelined.getTimeline().getFrameCount(); + + int oldFrame = frame; + for (int i = 0; i < cnt; i++) { + if (!stillFrame && frameCount > 0) { + frame = (frame + 1) % frameCount; + } + + if (!stillFrame && frame == frameCount - 1 && !loop) { + stopInternal(); + return; + } + + if (i < cnt - 1) { //skip not displayed frames, do not display, only play sounds, etc. + drawFrame(thisTimer, false); + } + } + if (frame != oldFrame) { + if (frame == 0) { + stopAllSounds(); + } + time = 0; + } else { + time = timeShouldBe; + } + } + } + + fireMediaDisplayStateChanged(); + } + + private static SerializableImage getFrame(SWF swf, int frame, int time, Timelined drawable, RenderContext renderContext, int selectedDepth, double zoom) { + Timeline timeline = drawable.getTimeline(); + //int mouseButton = renderContext.mouseButton; + //Point cursorPosition = renderContext.cursorPosition; + //String key = "drawable_" + frame + "_" + drawable.hashCode() + "_" + mouseButton + "_depth" + selectedDepth + "_" + (cursorPosition == null ? "out" : cursorPosition.hashCode()) + "_" + zoom + "_" + timeline.fontFrameNum; + SerializableImage img; + //SerializableImage img = swf.getFromCache(key); + //if (img == null) { + //boolean shouldCache = timeline.isSingleFrame(frame); + RECT rect = drawable.getRect(); + + int width = (int) (rect.getWidth() * zoom); + int height = (int) (rect.getHeight() * zoom); + SerializableImage image = new SerializableImage((int) Math.ceil(width / SWF.unitDivisor), + (int) Math.ceil(height / SWF.unitDivisor), SerializableImage.TYPE_INT_ARGB); + //renderContext.borderImage = new SerializableImage(image.getWidth(), image.getHeight(), SerializableImage.TYPE_INT_ARGB); + image.fillTransparent(); + Matrix m = new Matrix(); + m.translate(-rect.Xmin * zoom, -rect.Ymin * zoom); + m.scale(zoom); + timeline.toImage(frame, time, renderContext, image, false, m, m, m, null); + + Graphics2D gg = (Graphics2D) image.getGraphics(); + gg.setStroke(new BasicStroke(3)); + gg.setPaint(Color.green); + gg.setTransform(AffineTransform.getTranslateInstance(0, 0)); + DepthState ds = null; + if (timeline.getFrameCount() > frame) { + ds = timeline.getFrame(frame).layers.get(selectedDepth); + } + + if (ds != null) { + CharacterTag cht = swf.getCharacter(ds.characterId); + if (cht != null) { + if (cht instanceof DrawableTag) { + DrawableTag dt = (DrawableTag) cht; + int drawableFrameCount = dt.getNumFrames(); + if (drawableFrameCount == 0) { + drawableFrameCount = 1; + } + + int dframe = time % drawableFrameCount; + Shape outline = dt.getOutline(dframe, time, ds.ratio, renderContext, Matrix.getScaleInstance(1 / SWF.unitDivisor).concatenate(m.concatenate(new Matrix(ds.matrix))), true); + Rectangle bounds = outline.getBounds(); + gg.setStroke(new BasicStroke(2.0f, + BasicStroke.CAP_BUTT, + BasicStroke.JOIN_MITER, + 10.0f, new float[]{10.0f}, 0.0f)); + gg.setPaint(Color.red); + gg.draw(bounds); + } + } + } + + img = image; + + /*if (shouldCache) { + swf.putToCache(key, img); + }*/ + //} + return img; + } + + private Object execute(SWFInputStream sis) throws IOException { + if (!Configuration.internalFlashViewerExecuteAs12.get()) { + return Undefined.INSTANCE; + } + if (lda == null) { + return Undefined.INSTANCE; + } + long ip = sis.getPos(); + //System.err.println("============="); + Action a; + while ((a = sis.readAction()) != null) { + int actionLengthWithHeader = a.getTotalActionLength(); + a.setAddress(ip); + a.execute(lda); + /*System.err.print("" + a + ", stack: ["); + for (Object o : lda.stack) { + System.err.print("" + o + ","); + } + System.err.println("]");*/ + if (lda.returnValue != null) { + return lda.returnValue; + } + if (lda.jump != null) { + ip = lda.jump; + lda.jump = null; + } else { + ip += actionLengthWithHeader; + } + sis.seek(ip); + } + return Undefined.INSTANCE; + } + + private void executeFrame(int frame) { + if (!Configuration.internalFlashViewerExecuteAs12.get()) { + return; + } + if (timelined == null) { + return; + } + Frame f = timelined.getTimeline().getFrame(frame); + List actions = f.actions; + if (lda != null) { + lda.clear(); + } + for (DoActionTag src : actions) { + try { + ByteArrayRange actionBytes = src.getActionBytes(); + int prevLength = actionBytes.getPos(); + SWFInputStream rri = new SWFInputStream(swf, actionBytes.getArray(), 0, prevLength + actionBytes.getLength()); + if (prevLength != 0) { + rri.seek(prevLength); + } + execute(rri); + } catch (IOException ex) { + Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex); + } + + } + } + + private void drawFrame(Timer thisTimer, boolean display) { + Timelined timelined; + MouseEvent lastMouseEvent; + int frame; + int time; + Point cursorPosition; + int mouseButton; + int selectedDepth; + Zoom zoom; + SWF swf; + + synchronized (ImagePanel.class) { + timelined = this.timelined; + lastMouseEvent = this.lastMouseEvent; + } + + synchronized (ImagePanel.class) { + frame = this.frame; + time = this.time; + cursorPosition = this.cursorPosition; + if (cursorPosition != null) { + cursorPosition = iconPanel.toImagePoint(cursorPosition); + } + + mouseButton = this.mouseButton; + selectedDepth = this.selectedDepth; + zoom = this.zoom; + swf = this.swf; + } + + if (timelined == null) { + return; + } + + RenderContext renderContext = new RenderContext(); + renderContext.displayObjectCache = displayObjectCache; + if (cursorPosition != null) { + renderContext.cursorPosition = new Point((int) (cursorPosition.x * SWF.unitDivisor), (int) (cursorPosition.y * SWF.unitDivisor)); + } + + renderContext.mouseButton = mouseButton; + renderContext.stateUnderCursor = new ArrayList<>(); + + SerializableImage img; + try { + Timeline timeline = timelined.getTimeline(); + if (frame >= timeline.getFrameCount()) { + return; + } + + double zoomDouble = zoom.fit ? getZoomToFit() : zoom.value; + if (lowQuality) { + zoomDouble /= LQ_FACTOR; + } + updatePos(timelined, lastMouseEvent, thisTimer); + + Matrix mat = new Matrix(); + mat.translateX = swf.displayRect.Xmin; + mat.translateY = swf.displayRect.Ymin; + + img = null; + if (display) { + Stopwatch sw = Stopwatch.startNew(); + img = getFrame(swf, frame, time, timelined, renderContext, selectedDepth, zoomDouble); + sw.stop(); + if (sw.getElapsedMilliseconds() > 100) { + logger.log(Level.WARNING, "Slow rendering. {0}. frame, time={1}, {2}ms", new Object[]{frame, time, sw.getElapsedMilliseconds()}); + } + + if (renderContext.borderImage != null) { + img = renderContext.borderImage; + } + } + + List sounds = new ArrayList<>(); + List soundClasses = new ArrayList<>(); + timeline.getSounds(frame, time, renderContext.mouseOverButton, mouseButton, sounds, soundClasses); + for (int cid : swf.getCharacters().keySet()) { + CharacterTag c = swf.getCharacter(cid); + for (String cls : soundClasses) { + if (cls.equals(c.getClassName())) { + sounds.add(cid); + } + } + } + + for (int sndId : sounds) { + CharacterTag c = swf.getCharacter(sndId); + if (c instanceof SoundTag) { + SoundTag st = (SoundTag) c; + playSound(st, null, thisTimer); + } + } + executeFrame(frame); + } catch (Throwable ex) { + // swf was closed during the rendering probably + return; + } + if (display) { + + StringBuilder ret = new StringBuilder(); + + if (cursorPosition != null) { + ret.append(" [").append(cursorPosition.x).append(",").append(cursorPosition.y).append("] : "); + } + + boolean handCursor = renderContext.mouseOverButton != null; + boolean first = true; + for (int i = renderContext.stateUnderCursor.size() - 1; i >= 0; i--) { + DepthState ds = renderContext.stateUnderCursor.get(i); + if (!first) { + ret.append(", "); + } + + first = false; + CharacterTag c = swf.getCharacter(ds.characterId); + ret.append(c.toString()); + } + + if (first) { + ret.append(" - "); + } + + ButtonTag lastMouseOverButton; + synchronized (ImagePanel.class) { + if (timer == thisTimer) { + iconPanel.setImg(img); + lastMouseOverButton = iconPanel.mouseOverButton; + iconPanel.mouseOverButton = renderContext.mouseOverButton; + debugLabel.setText(ret.toString()); + if (handCursor) { + iconPanel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } else if (iconPanel.hasAllowMove()) { + iconPanel.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); + } else { + iconPanel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } + + if (lastMouseOverButton != renderContext.mouseOverButton) { + ButtonTag b = renderContext.mouseOverButton; + if (b != null) { + // New mouse entered + DefineButtonSoundTag sounds = b.getSounds(); + if (sounds != null && sounds.buttonSoundChar1 != 0) { // IdleToOverUp + playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar1), sounds.buttonSoundInfo1, timer); + } + } + + b = lastMouseOverButton; + if (b != null) { + // Old mouse leave + DefineButtonSoundTag sounds = b.getSounds(); + if (sounds != null && sounds.buttonSoundChar0 != 0) { // OverUpToIdle + playSound((SoundTag) swf.getCharacter(sounds.buttonSoundChar0), sounds.buttonSoundInfo0, timer); + } + } + } + + drawReady = true; + synchronized (delayObject) { + delayObject.notify(); + } + } + } + } + } + + private void playSound(SoundTag st, SOUNDINFO soundInfo, Timer thisTimer) { + final SoundTagPlayer sp; + try { + int loopCount = 1; + if (soundInfo != null && soundInfo.hasLoops) { + loopCount = Math.max(1, soundInfo.loopCount); + } + + sp = new SoundTagPlayer(st, loopCount, false); + sp.addEventListener(new MediaDisplayListener() { + @Override + public void mediaDisplayStateChanged(MediaDisplay source) { + } + + @Override + public void playingFinished(MediaDisplay source) { + synchronized (ImagePanel.class) { + sp.close(); + soundPlayers.remove(sp); + } + } + }); + + synchronized (ImagePanel.class) { + if (timer != null && timer == thisTimer) { + soundPlayers.add(sp); + sp.play(); + } else { + sp.close(); + } + } + } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) { + logger.log(Level.SEVERE, "Error during playing sound", ex); + } + } + + public synchronized void clearAll() { + stopInternal(); + clearImagePanel(); + timelined = null; + swf = null; + + fireMediaDisplayStateChanged(); + } + + private synchronized void stopInternal() { + clear(); + stopAllSounds(); + } + + @Override + public synchronized void play() { + stopInternal(); + if (timelined != null) { + Timeline timeline = timelined.getTimeline(); + if (!stillFrame && frame == timeline.getFrameCount() - 1) { + frame = 0; + } + + startTimer(timeline, true); + } + } + + private synchronized void setMsPerFrame(int val) { + this.msPerFrame = val; + } + + private synchronized int getMsPerFrame() { + return this.msPerFrame; + } + + private long startRun = 0L; + + private final long startDrop = 0L; + + private int skippedFrames = 0; + + private float fpsShouldBe = 0; + + private float fpsIs = 0; + + private Timer fpsTimer; + + private int startFrame = 0; + + private synchronized void setFpsIs(float val) { + fpsIs = val; + } + + private synchronized float getFpsIs() { + return fpsIs; + } + + private synchronized void setSkippedFrames(int val) { + skippedFrames = val; + } + + private synchronized void addSkippedFrames(int val) { + skippedFrames += val; + } + + private synchronized int getSkippedFrames() { + return skippedFrames; + } + + private synchronized int getAndResetSkippedFrames() { + int ret = skippedFrames; + skippedFrames = 0; + return ret; + } + + private void scheduleTask(boolean singleFrame, long msDelay) { + TimerTask task = new TimerTask() { + public final Timer thisTimer = timer; + + public final boolean isSingleFrame = singleFrame; + + private long lastRun = 0L; + + @Override + public void run() { + try { + synchronized (ImagePanel.class) { + if (timer != thisTimer) { + return; + } + } + lastRun = System.currentTimeMillis(); + int curFrame = frame; + long delay = getMsPerFrame(); + if (isSingleFrame) { + drawFrame(thisTimer, true); + synchronized (ImagePanel.class) { + thisTimer.cancel(); + if (timer == thisTimer) { + timer = null; + } + } + + fireMediaDisplayStateChanged(); + } else { + //Time before drawing current frame + long frameTimeMsIs = System.currentTimeMillis(); + //Total number of frames in this timeline + int frameCount = timelined.getTimeline().getFrameCount(); + //How many ticks (= times where frame should be displayed in framerate) are there from hitting play button + int ticksFromStart = (int) Math.floor((frameTimeMsIs - startRun) / (double) getMsPerFrame()) + 1; + //Add ticks to first frame when hitting play button, ignoring total framecount => this value can be larger than number of frames in timeline + int frameOverMaxShouldBeNow = startFrame + ticksFromStart; + //Apply maximum frames repating, this is actual frame which should be drawed now + int frameShouldBeNow = frameOverMaxShouldBeNow % frameCount; + + //How many frames are there between last displayed frame and now. For perfect display(=no framedrop), value should be 1 + int skipFrames = frameShouldBeNow - curFrame; + //It is negative for some reason, this will display older frames. Add frameCount to stay in modulu framecount. + if (skipFrames < 0) { + skipFrames += frameCount; + } + //Change for more than 1 frame + if (skipFrames > 1) { + addSkippedFrames(skipFrames - 1); //drop those frames, draw only last one + } + //Frame "time" - ticks in current frame + int currentFrameTicks = 0; + if (frameCount == 1) { //We have only one frame, so the ticks on that frame equal ticks on whole timeline + currentFrameTicks = ticksFromStart; + } + nextFrame(thisTimer, skipFrames, currentFrameTicks); + + long afterDrawFrameTimeMsIs = System.currentTimeMillis(); + + int nextFrameOverMax = frameOverMaxShouldBeNow; + while (delay < 0) { //while the frame time already passed + nextFrameOverMax++; + long nextFrameOverMaxTimeMsShouldBe = startRun + getMsPerFrame() * nextFrameOverMax; + delay = nextFrameOverMaxTimeMsShouldBe - afterDrawFrameTimeMsIs; + } + } + //schedule next run of the task + scheduleTask(isSingleFrame, delay); + + } catch (Exception ex) { + logger.log(Level.SEVERE, "Frame drawing error", ex); + } + } + }; + if (timer != null) { + timer.schedule(task, msDelay); + } + } + + private synchronized void startTimer(Timeline timeline, boolean playing) { + + startRun = System.currentTimeMillis(); + startFrame = frame; + float frameRate = timeline.frameRate; + setMsPerFrame(frameRate == 0 ? 1000 : (int) (1000.0 / frameRate)); + final boolean singleFrame = !playing + || (stillFrame && timeline.isSingleFrame(frame)) + || (!stillFrame && timeline.getRealFrameCount() <= 1 && timeline.isSingleFrame()); + + if (fpsTimer == null) { + fpsTimer = new Timer(); + fpsTimer.schedule(new TimerTask() { + @Override + public void run() { + float skipped = getAndResetSkippedFrames(); + setFpsIs(fpsShouldBe - skipped); + } + }, 1000, 1000); + } + timer = new Timer(); + fpsShouldBe = timeline.frameRate; + fpsIs = fpsShouldBe; + scheduleTask(singleFrame, 0); + + } + + @Override + public synchronized void rewind() { + frame = 0; + fireMediaDisplayStateChanged(); + } + + @Override + public synchronized boolean isPlaying() { + if (timelined == null || stillFrame) { + return false; + } + + return (timelined.getTimeline().getFrameCount() <= 1) || (timer != null); + } + + @Override + public void setLoop(boolean loop) { + this.loop = loop; + } + + @Override + public synchronized void gotoFrame(int frame) { + if (timelined == null) { + return; + } + Timeline timeline = timelined.getTimeline(); + if (frame >= timeline.getFrameCount()) { + return; + } + if (frame < 0) { + return; + } + + this.frame = frame; + stopInternal(); + redraw(); + fireMediaDisplayStateChanged(); + } + + @Override + public synchronized float getFrameRate() { + if (timelined == null) { + return 1; + } + if (stillFrame) { + return 1; + } + return timelined.getTimeline().frameRate; + } + + @Override + public synchronized boolean isLoaded() { + return loaded; + } + + @Override + public boolean loopAvailable() { + return false; + } + + @Override + public boolean screenAvailable() { + return true; + } + + @Override + public synchronized Zoom getZoom() { + return zoom; + } +} diff --git a/src/com/jpexs/decompiler/flash/gui/Main.java b/src/com/jpexs/decompiler/flash/gui/Main.java index 6467600bf..0bde11431 100644 --- a/src/com/jpexs/decompiler/flash/gui/Main.java +++ b/src/com/jpexs/decompiler/flash/gui/Main.java @@ -1,2370 +1,2377 @@ -/* - * Copyright (C) 2010-2016 JPEXS - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.jpexs.decompiler.flash.gui; - -import com.jpexs.debugger.flash.Debugger; -import com.jpexs.debugger.flash.DebuggerCommands; -import com.jpexs.debugger.flash.Variable; -import com.jpexs.debugger.flash.VariableType; -import com.jpexs.debugger.flash.messages.in.InCallFunction; -import com.jpexs.decompiler.flash.ApplicationInfo; -import com.jpexs.decompiler.flash.EventListener; -import com.jpexs.decompiler.flash.SWF; -import com.jpexs.decompiler.flash.SWFBundle; -import com.jpexs.decompiler.flash.SWFSourceInfo; -import com.jpexs.decompiler.flash.SearchMode; -import com.jpexs.decompiler.flash.SwfOpenException; -import com.jpexs.decompiler.flash.UrlResolver; -import com.jpexs.decompiler.flash.Version; -import com.jpexs.decompiler.flash.abc.avm2.AVM2Code; -import com.jpexs.decompiler.flash.abc.avm2.parser.script.Reference; -import com.jpexs.decompiler.flash.configuration.Configuration; -import com.jpexs.decompiler.flash.configuration.SwfSpecificConfiguration; -import com.jpexs.decompiler.flash.console.CommandLineArgumentParser; -import com.jpexs.decompiler.flash.console.ContextMenuTools; -import com.jpexs.decompiler.flash.exporters.modes.ExeExportMode; -import com.jpexs.decompiler.flash.gui.debugger.DebugListener; -import com.jpexs.decompiler.flash.gui.debugger.DebuggerTools; -import com.jpexs.decompiler.flash.gui.pipes.FirstInstance; -import com.jpexs.decompiler.flash.gui.proxy.ProxyFrame; -import com.jpexs.decompiler.flash.helpers.SWFDecompilerPlugin; -import com.jpexs.decompiler.flash.tags.Tag; -import com.jpexs.decompiler.flash.tags.base.FontTag; -import com.jpexs.decompiler.flash.tags.base.ImportTag; -import com.jpexs.decompiler.flash.treeitems.SWFList; -import com.jpexs.helpers.Cache; -import com.jpexs.helpers.CancellableWorker; -import com.jpexs.helpers.Helper; -import com.jpexs.helpers.Path; -import com.jpexs.helpers.ProgressListener; -import com.jpexs.helpers.Stopwatch; -import com.jpexs.helpers.streams.SeekableInputStream; -import com.sun.jna.Platform; -import com.sun.jna.platform.win32.Advapi32Util; -import com.sun.jna.platform.win32.Kernel32; -import com.sun.jna.platform.win32.WinReg; -import java.awt.AWTException; -import java.awt.Frame; -import java.awt.GraphicsEnvironment; -import java.awt.MenuItem; -import java.awt.PopupMenu; -import java.awt.SystemTray; -import java.awt.TrayIcon; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.logging.ConsoleHandler; -import java.util.logging.FileHandler; -import java.util.logging.Formatter; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.SwingWorker; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; -import javax.swing.filechooser.FileFilter; -import org.pushingpixels.substance.api.SubstanceLookAndFeel; - -/** - * Main executable class - * - * @author JPEXS - */ -public class Main { - - protected static ProxyFrame proxyFrame; - - private static List sourceInfos = new ArrayList<>(); - - public static LoadingDialog loadingDialog; - - private static boolean working = false; - - private static TrayIcon trayIcon; - - private static MenuItem stopMenuItem; - - private static volatile MainFrame mainFrame; - - public static final int UPDATE_SYSTEM_MAJOR = 1; - - public static final int UPDATE_SYSTEM_MINOR = 3; - - private static LoadFromMemoryFrame loadFromMemoryFrame; - - private static LoadFromCacheFrame loadFromCacheFrame; - - private static final Logger logger = Logger.getLogger(Main.class.getName()); - - public static DebugLogDialog debugDialog; - - public static boolean shouldCloseWhenClosingLoadingDialog; - - private static Debugger flashDebugger; - - private static DebuggerHandler debugHandler = null; - - //private static int ip = 0; - //private static String ipClass = null; - private static Process runProcess; - - private static boolean runProcessDebug; - - private static boolean runProcessDebugPCode; - - private static boolean inited = false; - - private static File runTempFile; - - private static List runTempFiles = new ArrayList<>(); - - public static void freeRun() { - synchronized (Main.class) { - if (runTempFile != null) { - runTempFile.delete(); - runTempFile = null; - } - for (File f : runTempFiles) { - f.delete(); - } - runTempFiles.clear(); - - runProcess = null; - } - if (mainFrame != null && mainFrame.getPanel() != null) { - mainFrame.getPanel().clearDebuggerColors(); - } - if (runProcessDebug) { - Main.getDebugHandler().disconnect(); - } - } - - public static synchronized boolean isDebugPaused() { - return runProcess != null && runProcessDebug && getDebugHandler().isPaused(); - } - - public static synchronized boolean isDebugRunning() { - return runProcess != null && runProcessDebug; - } - - public static synchronized boolean isDebugPCode() { - return runProcessDebugPCode; - } - - public static synchronized boolean isDebugConnected() { - return getDebugHandler().isConnected(); - } - - public static synchronized boolean isRunning() { - return runProcess != null && !runProcessDebug; - } - - /** - * FIXME! - * - * @param v - */ - public static synchronized void dumpBytes(Variable v) { - InCallFunction icf; - try { - long objectId = 0l; - if ((v.vType == VariableType.OBJECT || v.vType == VariableType.MOVIECLIP)) { - objectId = (Long) v.value; - } - Object oldPos = getDebugHandler().getVariable(objectId, "position", true).parent.value; - getDebugHandler().setVariable(objectId, "position", VariableType.NUMBER, 0); - icf = getDebugHandler().callFunction(false, "readUTF", v, new ArrayList<>()); - System.out.println("Result=" + icf.variables.get(0).value); - getDebugHandler().setVariable(objectId, "position", VariableType.NUMBER, oldPos); - } catch (DebuggerHandler.ActionScriptException ex) { - Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); - } - - } - - public static synchronized boolean addWatch(Variable v, long v_id, boolean watchRead, boolean watchWrite) { - DebuggerCommands.Watch w = getDebugHandler().addWatch(v, v_id, watchRead, watchWrite); - return w != null; - } - - public static void runPlayer(String title, final String exePath, String file, String flashVars) { - if (!new File(file).exists()) { - return; - } - if (flashVars != null && !flashVars.isEmpty()) { - file += "?" + flashVars; - } - final String ffile = file; - - CancellableWorker runWorker = new CancellableWorker() { - @Override - protected Object doInBackground() throws Exception { - Process proc; - try { - proc = Runtime.getRuntime().exec(new String[]{exePath, ffile}); - } catch (IOException ex) { - logger.log(Level.SEVERE, null, ex); - return null; - } - boolean isDebug; - - synchronized (Main.class) { - runProcess = proc; - isDebug = runProcessDebug; - } - if (isDebug) { - mainFrame.getMenu().hilightPath("/debugging"); - } - mainFrame.getMenu().updateComponents(); - try { - if (proc != null) { - proc.waitFor(); - } - } catch (InterruptedException ex) { - if (proc != null) { - try { - proc.destroy(); - } catch (Exception ex2) { - //ignore - } - } - } - freeRun(); - stopDebugger(); - mainFrame.getMenu().updateComponents(); - return null; - } - - @Override - protected void done() { - Main.stopWork(); - } - - @Override - public void workerCancelled() { - Main.stopWork(); - synchronized (Main.class) { - if (runProcess != null) { - try { - runProcess.destroy(); - } catch (Exception ex) { - - } - } - } - freeRun(); - mainFrame.getMenu().updateComponents(); - } - }; - - mainFrame.getMenu().updateComponents(); - Main.startWork(title + "...", runWorker); - runWorker.execute(); - } - - public static void stopRun() { - - synchronized (Main.class) { - if (runProcess != null) { - runProcess.destroy(); - } - } - freeRun(); - stopDebugger(); - mainFrame.getMenu().updateComponents(); - } - - private static interface SwfPreparation { - - public SWF prepare(SWF swf); - } - - private static class SwfRunPrepare implements SwfPreparation { - - @Override - public SWF prepare(SWF swf) { - if (Configuration.autoOpenLoadedSWFs.get()) { - if (!DebuggerTools.hasDebugger(swf)) { - DebuggerTools.switchDebugger(swf); - } - DebuggerTools.injectDebugLoader(swf); - } - return swf; - } - } - - private static class SwfDebugPrepare extends SwfRunPrepare { - - private boolean doPCode; - - public SwfDebugPrepare(boolean doPCode) { - this.doPCode = doPCode; - } - - @Override - public SWF prepare(SWF instrSWF) { - instrSWF = super.prepare(instrSWF); - try { - File fTempFile = new File(instrSWF.getFile()); - instrSWF.enableDebugging(true, new File("."), true, doPCode); - FileOutputStream fos = new FileOutputStream(fTempFile); - instrSWF.saveTo(fos); - fos.close(); - if (!instrSWF.isAS3()) { - //Read again, because line file offsets changed with adding debug tags - //TODO: handle somehow without rereading? - instrSWF = null; - try (FileInputStream fis = new FileInputStream(fTempFile)) { - instrSWF = new SWF(fis, false, false); - } catch (InterruptedException ex) { - logger.log(Level.SEVERE, null, ex); - } - if (instrSWF != null) { - String swfFileName = fTempFile.getAbsolutePath(); - if (swfFileName.toLowerCase().endsWith(".swf")) { - swfFileName = swfFileName.substring(0, swfFileName.length() - 4) + ".swd"; - } else { - swfFileName = swfFileName + ".swd"; - } - File swdFile = new File(swfFileName); - if (doPCode) { - instrSWF.generatePCodeSwdFile(swdFile, getPackBreakPoints(true)); - } else { - instrSWF.generateSwdFile(swdFile, getPackBreakPoints(true)); - } - } - } - } catch (IOException ex) { - //ignore, return instrSWF - } - return instrSWF; - } - } - - private static void prepareSwf(SwfPreparation prep, File toPrepareFile, File origFile, List tempFiles) throws IOException { - SWF instrSWF = null; - try (FileInputStream fis = new FileInputStream(toPrepareFile)) { - instrSWF = new SWF(fis, toPrepareFile.getAbsolutePath(), origFile.getName(), false); - } catch (InterruptedException ex) { - logger.log(Level.SEVERE, null, ex); - } - if (instrSWF != null) { - for (Tag t : instrSWF.getLocalTags()) { - if (t instanceof ImportTag) { - ImportTag it = (ImportTag) t; - String url = it.getUrl(); - File importedFile = new File(origFile.getParentFile(), url); - if (importedFile.exists()) { - File newTempFile = File.createTempFile("ffdec_run_import_", ".swf"); - it.setUrl("./" + newTempFile.getName()); - byte[] impData = Helper.readFile(importedFile.getAbsolutePath()); - Helper.writeFile(newTempFile.getAbsolutePath(), impData); - tempFiles.add(newTempFile); - prepareSwf(prep, newTempFile, importedFile, tempFiles); - } - } - } - if (prep != null) { - instrSWF = prep.prepare(instrSWF); - } - try (FileOutputStream fos = new FileOutputStream(toPrepareFile)) { - instrSWF.saveTo(fos); - } - } - } - - public static void run(SWF swf) { - String flashVars = "";//key=val&key2=val2 - String playerLocation = Configuration.playerLocation.get(); - if (playerLocation.isEmpty() || (!new File(playerLocation).exists())) { - View.showMessageDialog(null, AppStrings.translate("message.playerpath.notset"), AppStrings.translate("error"), JOptionPane.ERROR_MESSAGE); - advancedSettings("paths"); - return; - } - if (swf == null) { - return; - } - File tempFile; - List tempFiles = new ArrayList<>(); - try { - tempFile = File.createTempFile("ffdec_run_", ".swf"); - - try (FileOutputStream fos = new FileOutputStream(tempFile)) { - swf.saveTo(fos); - } - - prepareSwf(new SwfRunPrepare(), tempFile, new File(swf.getFile()), tempFiles); - - } catch (IOException ex) { - return; - - } - if (tempFile != null) { - synchronized (Main.class) { - runTempFile = tempFile; - runTempFiles = tempFiles; - runProcessDebug = false; - } - runPlayer(AppStrings.translate("work.running"), playerLocation, tempFile.getAbsolutePath(), flashVars); - } - } - - public static void runDebug(SWF swf, final boolean doPCode) { - String flashVars = "";//key=val&key2=val2 - String playerLocation = Configuration.playerDebugLocation.get(); - if (playerLocation.isEmpty() || (!new File(playerLocation).exists())) { - View.showMessageDialog(null, AppStrings.translate("message.playerpath.debug.notset"), AppStrings.translate("error"), JOptionPane.ERROR_MESSAGE); - Main.advancedSettings("paths"); - return; - } - if (swf == null) { - return; - } - File tempFile = null; - - try { - tempFile = File.createTempFile("ffdec_debug_", ".swf"); - } catch (Exception ex) { - - } - - if (tempFile != null) { - final File fTempFile = tempFile; - final List tempFiles = new ArrayList<>(); - CancellableWorker instrumentWorker = new CancellableWorker() { - @Override - protected Object doInBackground() throws Exception { - - try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(fTempFile))) { - swf.saveTo(fos); - } - prepareSwf(new SwfDebugPrepare(doPCode), fTempFile, new File(swf.getFile()), tempFiles); - return null; - } - - @Override - public void workerCancelled() { - Main.stopWork(); - } - - @Override - protected void done() { - synchronized (Main.class) { - runTempFile = fTempFile; - runProcessDebug = true; - runProcessDebugPCode = doPCode; - runTempFiles = tempFiles; - } - Main.stopWork(); - Main.startDebugger(); - runPlayer(AppStrings.translate("work.debugging.wait"), playerLocation, fTempFile.getAbsolutePath(), flashVars); - } - }; - - Main.startWork(AppStrings.translate("work.debugging.instrumenting"), instrumentWorker); - instrumentWorker.execute(); - } - } - - /* public static void debuggerNotSuspended() { - - }*/ - public static boolean isDebugging() { - return isDebugRunning(); - } - - public synchronized static int getIp(Object pack) { - return getDebugHandler().getBreakIp(); - } - - public synchronized static String getIpClass() { - return getDebugHandler().getBreakScriptName(); - } - - public static synchronized boolean isBreakPointValid(String scriptName, int line) { - return !getDebugHandler().isBreakpointInvalid(scriptName, line); - } - - public synchronized static void addBreakPoint(String scriptName, int line) { - getDebugHandler().addBreakPoint(scriptName, line); - } - - public synchronized static void removeBreakPoint(String scriptName, int line) { - getDebugHandler().removeBreakPoint(scriptName, line); - } - - public synchronized static boolean toggleBreakPoint(String scriptName, int line) { - if (getDebugHandler().isBreakpointToAdd(scriptName, line) || getDebugHandler().isBreakpointConfirmed(scriptName, line) || getDebugHandler().isBreakpointInvalid(scriptName, line)) { - getDebugHandler().removeBreakPoint(scriptName, line); - return false; - } else { - getDebugHandler().addBreakPoint(scriptName, line); - return true; - } - } - - public synchronized static Map> getPackBreakPoints(boolean validOnly) { - return getDebugHandler().getAllBreakPoints(validOnly); - } - - public synchronized static Set getScriptBreakPoints(String pack, boolean onlyValid) { - return getDebugHandler().getBreakPoints(pack, onlyValid); - } - - public static DebuggerHandler getDebugHandler() { - return debugHandler; - } - - public static void ensureMainFrame() { - if (mainFrame == null) { - synchronized (Main.class) { - if (mainFrame == null) { - MainFrame frame; - if (Configuration.useRibbonInterface.get()) { - frame = new MainFrameRibbon(); - } else { - frame = new MainFrameClassic(); - } - frame.getPanel().setErrorState(ErrorLogFrame.getInstance().getErrorState()); - mainFrame = frame; - } - } - } - } - - public static MainFrame getMainFrame() { - return mainFrame; - } - - public static void loadFromCache() { - if (loadFromCacheFrame == null) { - loadFromCacheFrame = new LoadFromCacheFrame(); - } - loadFromCacheFrame.setVisible(true); - } - - public static void loadFromMemory() { - if (loadFromMemoryFrame == null) { - loadFromMemoryFrame = new LoadFromMemoryFrame(mainFrame); - } - loadFromMemoryFrame.setVisible(true); - } - - public static void setVariable(long parentId, String varName, int valueType, Object value) { - getDebugHandler().setVariable(parentId, varName, valueType, value); - } - - public static void setSubLimiter(boolean value) { - if (value) { - AVM2Code.toSourceLimit = Configuration.sublimiter.get(); - } else { - AVM2Code.toSourceLimit = -1; - } - } - - public synchronized static boolean isInited() { - return inited; - } - - public synchronized static void setSessionLoaded(boolean v) { - inited = v; - } - - public static boolean isWorking() { - return working; - } - - public static void startProxy(int port) { - if (proxyFrame == null) { - proxyFrame = new ProxyFrame(mainFrame); - } - - proxyFrame.setPort(port); - addTrayIcon(); - switchProxy(); - } - - public static void showProxy() { - if (proxyFrame == null) { - proxyFrame = new ProxyFrame(mainFrame); - } - proxyFrame.setVisible(true); - proxyFrame.setState(Frame.NORMAL); - } - - public static void startWork(String name, CancellableWorker worker) { - startWork(name, -1, worker); - } - - public static void startWork(final String name, final int percent, final CancellableWorker worker) { - working = true; - View.execInEventDispatchLater(() -> { - if (mainFrame != null) { - mainFrame.getPanel().setWorkStatus(name, worker); - if (percent == -1) { - mainFrame.getPanel().hidePercent(); - } else { - mainFrame.getPanel().setPercent(percent); - } - } - if (loadingDialog != null) { - loadingDialog.setDetail(name); - loadingDialog.setPercent(percent); - } - if (CommandLineArgumentParser.isCommandLineMode()) { - System.out.println(name); - } - }); - } - - public static void stopWork() { - working = false; - View.execInEventDispatchLater(() -> { - if (mainFrame != null) { - mainFrame.getPanel().setWorkStatus("", null); - } - if (loadingDialog != null) { - loadingDialog.setDetail(""); - } - }); - } - - public static SWFList parseSWF(SWFSourceInfo sourceInfo) throws Exception { - SWFList result = new SWFList(); - - InputStream inputStream = sourceInfo.getInputStream(); - SWFBundle bundle = null; - FileInputStream fis = null; - if (inputStream == null) { - inputStream = new BufferedInputStream(fis = new FileInputStream(sourceInfo.getFile())); - bundle = sourceInfo.getBundle(false, SearchMode.ALL); - logger.log(Level.INFO, "Load file: {0}", sourceInfo.getFile()); - } else if (inputStream instanceof SeekableInputStream - || inputStream instanceof BufferedInputStream) { - try { - inputStream.reset(); - } catch (IOException ex) { - logger.log(Level.SEVERE, null, ex); - } - logger.log(Level.INFO, "Load stream: {0}", sourceInfo.getFileTitle()); - } - - Stopwatch sw = Stopwatch.startNew(); - if (bundle != null) { - result.bundle = bundle; - result.name = new File(sourceInfo.getFileTitleOrName()).getName(); - for (Entry streamEntry : bundle.getAll().entrySet()) { - InputStream stream = streamEntry.getValue(); - stream.reset(); - CancellableWorker worker = new CancellableWorker() { - @Override - public SWF doInBackground() throws Exception { - final CancellableWorker worker = this; - SWF swf = new SWF(stream, null, streamEntry.getKey(), new ProgressListener() { - @Override - public void progress(int p) { - startWork(AppStrings.translate("work.reading.swf"), p, worker); - } - }, Configuration.parallelSpeedUp.get()); - return swf; - } - }; - loadingDialog.setWroker(worker); - worker.execute(); - - try { - result.add(worker.get()); - } catch (CancellationException ex) { - logger.log(Level.WARNING, "Loading SWF {0} was cancelled.", streamEntry.getKey()); - } - } - } else { - InputStream fInputStream = inputStream; - - final String[] yesno = new String[]{AppStrings.translate("button.yes"), AppStrings.translate("button.no"), AppStrings.translate("button.yes.all"), AppStrings.translate("button.no.all")}; - - CancellableWorker worker = new CancellableWorker() { - private boolean yestoall = false; - - private boolean notoall = false; - - private SWF open(InputStream is, String file, String fileTitle) throws IOException, InterruptedException { - final CancellableWorker worker = this; - - SWF swf = new SWF(is, file, fileTitle, new ProgressListener() { - @Override - public void progress(int p) { - startWork(AppStrings.translate("work.reading.swf"), p, worker); - } - }, Configuration.parallelSpeedUp.get(), false, true, new UrlResolver() { - @Override - public SWF resolveUrl(final String url) { - int opt = -1; - if (!(yestoall || notoall)) { - opt = View.showOptionDialog(null, AppStrings.translate("message.imported.swf").replace("%url%", url), AppStrings.translate("message.warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, yesno, AppStrings.translate("button.yes")); - if (opt == 2) { - yestoall = true; - } - if (opt == 3) { - notoall = true; - } - } - - if (yestoall) { - opt = 0; // yes - } else if (notoall) { - opt = 1; // no - } - - if (opt == 1) //no - { - return null; - } - - if (url.startsWith("http://") || url.startsWith("https://")) { - try { - URL u = new URL(url); - return open(u.openStream(), null, url); //? - } catch (Exception ex) { - //ignore - } - } else { - File f = new File(new File(file).getParentFile(), url); - if (f.exists()) { - try { - return open(new FileInputStream(f), f.getAbsolutePath(), f.getName()); - } catch (Exception ex) { - //ignore - } - } - } - Reference ret = new Reference<>(null); - View.execInEventDispatch(new Runnable() { - @Override - public void run() { - - while (JOptionPane.YES_OPTION == View.showConfirmDialog(null, AppStrings.translate("message.imported.swf.manually").replace("%url%", url), AppStrings.translate("error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE)) { - - JFileChooser fc = new JFileChooser(); - fc.setCurrentDirectory(new File(Configuration.lastOpenDir.get())); - FileFilter allSupportedFilter = new FileFilter() { - private final String[] supportedExtensions = new String[]{".swf", ".gfx"}; - - @Override - public boolean accept(File f) { - String name = f.getName().toLowerCase(); - for (String ext : supportedExtensions) { - if (name.endsWith(ext)) { - return true; - } - } - return f.isDirectory(); - } - - @Override - public String getDescription() { - String exts = Helper.joinStrings(supportedExtensions, "*%s", "; "); - return AppStrings.translate("filter.supported") + " (" + exts + ")"; - } - }; - fc.setFileFilter(allSupportedFilter); - FileFilter swfFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".swf")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.swf"); - } - }; - fc.addChoosableFileFilter(swfFilter); - - FileFilter gfxFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".gfx")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.gfx"); - } - }; - fc.addChoosableFileFilter(gfxFilter); - fc.setAcceptAllFileFilterUsed(false); - JFrame f = new JFrame(); - View.setWindowIcon(f); - int returnVal = fc.showOpenDialog(f); - if (returnVal == JFileChooser.APPROVE_OPTION) { - Configuration.lastOpenDir.set(Helper.fixDialogFile(fc.getSelectedFile()).getParentFile().getAbsolutePath()); - File selFile = Helper.fixDialogFile(fc.getSelectedFile()); - try { - ret.setVal(open(new FileInputStream(selFile), selFile.getAbsolutePath(), selFile.getName())); - break; - } catch (Exception ex) { - //ignore; - } - } else { - break; - } - } - } - }); - return ret.getVal(); - } - }); - return swf; - } - - @Override - public SWF doInBackground() throws Exception { - return open(fInputStream, sourceInfo.getFile(), sourceInfo.getFileTitle()); - } - }; - if (loadingDialog != null) { - loadingDialog.setWroker(worker); - } - worker.execute(); - - try { - result.add(worker.get()); - } catch (CancellationException ex) { - logger.log(Level.WARNING, "Loading SWF {0} was cancelled.", sourceInfo.getFileTitleOrName()); - } - } - - if (fis != null) { - logger.log(Level.INFO, "File loaded in {0} seconds.", (sw.getElapsedMilliseconds() / 1000)); - fis.close(); - } else { - logger.log(Level.INFO, "Stream loaded in {0} seconds.", (sw.getElapsedMilliseconds() / 1000)); - } - - result.sourceInfo = sourceInfo; - for (SWF swf : result) { - logger.log(Level.INFO, ""); - logger.log(Level.INFO, "== File information =="); - logger.log(Level.INFO, "Size: {0}", Helper.formatFileSize(swf.fileSize)); - logger.log(Level.INFO, "Flash version: {0}", swf.version); - int width = (int) ((swf.displayRect.Xmax - swf.displayRect.Xmin) / SWF.unitDivisor); - int height = (int) ((swf.displayRect.Ymax - swf.displayRect.Ymin) / SWF.unitDivisor); - logger.log(Level.INFO, "Width: {0}", width); - logger.log(Level.INFO, "Height: {0}", height); - - swf.swfList = result; - swf.addEventListener(new EventListener() { - @Override - public void handleExportingEvent(String type, int index, int count, Object data) { - String text = AppStrings.translate("work.exporting"); - if (type != null && type.length() > 0) { - text += " " + type; - } - - startWork(text + " " + index + "/" + count + " " + data, null); - } - - @Override - public void handleExportedEvent(String type, int index, int count, Object data) { - String text = AppStrings.translate("work.exported"); - if (type != null && type.length() > 0) { - text += " " + type; - } - - startWork(text + " " + index + "/" + count + " " + data, null); - } - - @Override - public void handleEvent(String event, Object data) { - if (event.equals("exporting") || event.equals("exported")) { - throw new Error("Event is not supported by this handler."); - } - if (event.equals("getVariables")) { - startWork(AppStrings.translate("work.gettingvariables") + "..." + (String) data, null); - } - if (event.equals("deobfuscate")) { - startWork(AppStrings.translate("work.deobfuscating") + "..." + (String) data, null); - } - if (event.equals("rename")) { - startWork(AppStrings.translate("work.renaming") + "..." + (String) data, null); - } - } - }); - } - - return result; - } - - public static void saveFile(SWF swf, String outfile) throws IOException { - saveFile(swf, outfile, SaveFileMode.SAVE, null); - } - - public static void saveFile(SWF swf, String outfile, SaveFileMode mode, ExeExportMode exeExportMode) throws IOException { - if (mode == SaveFileMode.SAVEAS && !swf.swfList.isBundle()) { - swf.setFile(outfile); - swf.swfList.sourceInfo.setFile(outfile); - } - File outfileF = new File(outfile); - File tmpFile = new File(outfile + ".tmp"); - try (FileOutputStream fos = new FileOutputStream(tmpFile); - BufferedOutputStream bos = new BufferedOutputStream(fos)) { - if (mode == SaveFileMode.EXE) { - switch (exeExportMode) { - case WRAPPER: - InputStream exeStream = View.class.getClassLoader().getResourceAsStream("com/jpexs/helpers/resource/Swf2Exe.bin"); - Helper.copyStream(exeStream, bos); - int width = swf.displayRect.Xmax - swf.displayRect.Xmin; - int height = swf.displayRect.Ymax - swf.displayRect.Ymin; - bos.write(width & 0xff); - bos.write((width >> 8) & 0xff); - bos.write((width >> 16) & 0xff); - bos.write((width >> 24) & 0xff); - bos.write(height & 0xff); - bos.write((height >> 8) & 0xff); - bos.write((height >> 16) & 0xff); - bos.write((height >> 24) & 0xff); - bos.write(Configuration.saveAsExeScaleMode.get()); - break; - case PROJECTOR_WIN: - case PROJECTOR_MAC: - case PROJECTOR_LINUX: - File projectorFile = Configuration.getProjectorFile(exeExportMode); - if (projectorFile == null) { - String message = "Projector not found, please place it to " + Configuration.getProjectorPath(); - logger.log(Level.SEVERE, message); - throw new IOException(message); - } - Helper.copyStream(new FileInputStream(projectorFile), bos); - bos.flush(); - break; - } - } - - long pos = fos.getChannel().position(); - swf.saveTo(bos); - - if (mode == SaveFileMode.EXE) { - switch (exeExportMode) { - case PROJECTOR_WIN: - case PROJECTOR_MAC: - case PROJECTOR_LINUX: - bos.flush(); - int swfSize = (int) (fos.getChannel().position() - pos); - - // write magic number - bos.write(0x56); - bos.write(0x34); - bos.write(0x12); - bos.write(0xfa); - - bos.write(swfSize & 0xff); - bos.write((swfSize >> 8) & 0xff); - bos.write((swfSize >> 16) & 0xff); - bos.write((swfSize >> 24) & 0xff); - } - } - } - if (tmpFile.exists()) { - if (tmpFile.length() > 0) { - outfileF.delete(); - if (!tmpFile.renameTo(outfileF)) { - tmpFile.delete(); - throw new IOException("Cannot access " + outfile); - } - } else { - throw new IOException("Output is empty"); - } - } else { - throw new IOException("Output not found"); - } - } - - private static class OpenFileWorker extends SwingWorker { - - private final SWFSourceInfo[] sourceInfos; - - private final Runnable executeAfterOpen; - - private final int[] reloadIndices; - - public OpenFileWorker(SWFSourceInfo sourceInfo) { - this(sourceInfo, -1); - } - - public OpenFileWorker(SWFSourceInfo sourceInfo, int reloadIndex) { - this(sourceInfo, null, reloadIndex); - } - - public OpenFileWorker(SWFSourceInfo sourceInfo, Runnable executeAfterOpen) { - this(sourceInfo, executeAfterOpen, -1); - } - - public OpenFileWorker(SWFSourceInfo sourceInfo, Runnable executeAfterOpen, int reloadIndex) { - this.sourceInfos = new SWFSourceInfo[]{sourceInfo}; - this.executeAfterOpen = executeAfterOpen; - this.reloadIndices = new int[]{reloadIndex}; - } - - public OpenFileWorker(SWFSourceInfo[] sourceInfos) { - this(sourceInfos, null, null); - } - - public OpenFileWorker(SWFSourceInfo[] sourceInfos, Runnable executeAfterOpen) { - this(sourceInfos, executeAfterOpen, null); - } - - public OpenFileWorker(SWFSourceInfo[] sourceInfos, Runnable executeAfterOpen, int[] reloadIndices) { - this.sourceInfos = sourceInfos; - this.executeAfterOpen = executeAfterOpen; - int[] indices = new int[sourceInfos.length]; - for (int i = 0; i < indices.length; i++) { - indices[i] = -1; - } - this.reloadIndices = reloadIndices == null ? indices : reloadIndices; - } - - @Override - protected Object doInBackground() throws Exception { - boolean first = true; - SWF firstSWF = null; - for (int index = 0; index < sourceInfos.length; index++) { - SWFSourceInfo sourceInfo = sourceInfos[index]; - SWFList swfs = null; - try { - Main.startWork(AppStrings.translate("work.reading.swf") + "...", null); - try { - swfs = parseSWF(sourceInfo); - } catch (ExecutionException ex) { - Throwable cause = ex.getCause(); - if (cause instanceof SwfOpenException) { - throw (SwfOpenException) cause; - } - - throw ex; - } - } catch (OutOfMemoryError ex) { - logger.log(Level.SEVERE, null, ex); - View.showMessageDialog(null, "Cannot load SWF file. Out of memory."); - continue; - } catch (SwfOpenException ex) { - logger.log(Level.SEVERE, null, ex); - View.showMessageDialog(null, ex.getMessage()); - continue; - } catch (Exception ex) { - logger.log(Level.SEVERE, null, ex); - View.showMessageDialog(null, "Cannot load SWF file."); - continue; - } - - final SWFList swfs1 = swfs; - final boolean first1 = first; - first = false; - if (firstSWF == null && swfs1.size() > 0) { - firstSWF = swfs1.get(0); - } - - final int findex = index; - try { - View.execInEventDispatch(() -> { - Main.startWork(AppStrings.translate("work.creatingwindow") + "...", null); - ensureMainFrame(); - if (reloadIndices[findex] > -1) { - mainFrame.getPanel().loadSwfAtPos(swfs1, reloadIndices[findex]); - } else { - mainFrame.getPanel().load(swfs1, first1); - } - }); - } catch (Exception ex) { - logger.log(Level.SEVERE, null, ex); - } - } - - loadingDialog.setVisible(false); - shouldCloseWhenClosingLoadingDialog = false; - - final SWF fswf = firstSWF; - View.execInEventDispatch(() -> { - if (mainFrame != null) { - mainFrame.setVisible(true); - } - - Main.stopWork(); - - if (mainFrame != null && Configuration.gotoMainClassOnStartup.get()) { - mainFrame.getPanel().gotoDocumentClass(fswf); - } - - if (mainFrame != null && fswf != null) { - SwfSpecificConfiguration swfConf = Configuration.getSwfSpecificConfiguration(fswf.getShortFileName()); - if (swfConf != null) { - String pathStr = swfConf.lastSelectedPath; - mainFrame.getPanel().tagTree.setSelectionPathString(pathStr); - } - } - - if (executeAfterOpen != null) { - executeAfterOpen.run(); - } - }); - - return true; - } - } - - public static boolean reloadSWFs() { - CancellableWorker.cancelBackgroundThreads(); - if (Main.sourceInfos.isEmpty()) { - Helper.freeMem(); - showModeFrame(); - return true; - } else { - SWFSourceInfo[] sourceInfosCopy = new SWFSourceInfo[sourceInfos.size()]; - sourceInfos.toArray(sourceInfosCopy); - sourceInfos.clear(); - openFile(sourceInfosCopy); - return true; - } - } - - public static void reloadApp() { - if (debugDialog != null) { - debugDialog.setVisible(false); - debugDialog.dispose(); - debugDialog = null; - } - if (loadingDialog != null) { - synchronized (Main.class) { - if (loadingDialog != null) { - loadingDialog.setVisible(false); - loadingDialog.dispose(); - loadingDialog = null; - } - } - } - if (proxyFrame != null) { - proxyFrame.setVisible(false); - proxyFrame.dispose(); - proxyFrame = null; - } - if (loadFromMemoryFrame != null) { - loadFromMemoryFrame.setVisible(false); - loadFromMemoryFrame.dispose(); - loadFromMemoryFrame = null; - } - if (loadFromCacheFrame != null) { - loadFromCacheFrame.setVisible(false); - loadFromCacheFrame.dispose(); - loadFromCacheFrame = null; - } - if (mainFrame != null) { - mainFrame.setVisible(false); - mainFrame.getPanel().closeAll(false); - mainFrame.dispose(); - mainFrame = null; - } - FontTag.reload(); - Cache.clearAll(); - initGui(); - reloadSWFs(); - } - - public static OpenFileResult openFile(String swfFile, String fileTitle) { - return openFile(swfFile, fileTitle, null); - } - - public static OpenFileResult openFile(String swfFile, String fileTitle, Runnable executeAfterOpen) { - try { - File file = new File(swfFile); - if (!file.exists()) { - View.showMessageDialog(null, AppStrings.translate("open.error.fileNotFound"), AppStrings.translate("open.error"), JOptionPane.ERROR_MESSAGE); - return OpenFileResult.NOT_FOUND; - } - swfFile = file.getCanonicalPath(); - Configuration.addRecentFile(swfFile); - SWFSourceInfo sourceInfo = new SWFSourceInfo(null, swfFile, fileTitle); - OpenFileResult openResult = openFile(sourceInfo); - return openResult; - } catch (IOException ex) { - View.showMessageDialog(null, AppStrings.translate("open.error.cannotOpen"), AppStrings.translate("open.error"), JOptionPane.ERROR_MESSAGE); - return OpenFileResult.ERROR; - } - } - - public static OpenFileResult openFile(SWFSourceInfo sourceInfo) { - return openFile(new SWFSourceInfo[]{sourceInfo}); - } - - public static OpenFileResult openFile(SWFSourceInfo sourceInfo, Runnable executeAfterOpen) { - return openFile(new SWFSourceInfo[]{sourceInfo}, executeAfterOpen); - } - - public static OpenFileResult openFile(SWFSourceInfo sourceInfo, Runnable executeAfterOpen, int reloadIndex) { - return openFile(new SWFSourceInfo[]{sourceInfo}, executeAfterOpen, new int[]{reloadIndex}); - } - - public static OpenFileResult openFile(SWFSourceInfo[] newSourceInfos) { - return openFile(newSourceInfos, null); - } - - public static OpenFileResult openFile(SWFSourceInfo[] newSourceInfos, Runnable executeAfterOpen) { - return openFile(newSourceInfos, executeAfterOpen, null); - } - - public static OpenFileResult openFile(SWFSourceInfo[] newSourceInfos, Runnable executeAfterOpen, int[] reloadIndices) { - if (mainFrame != null && !Configuration.openMultipleFiles.get()) { - sourceInfos.clear(); - mainFrame.getPanel().closeAll(false); - mainFrame.setVisible(false); - Helper.freeMem(); - reloadIndices = null; - } - - loadingDialog.setVisible(true); - - OpenFileWorker wrk = new OpenFileWorker(newSourceInfos, executeAfterOpen, reloadIndices); - wrk.execute(); - if (reloadIndices == null) { - sourceInfos.addAll(Arrays.asList(newSourceInfos)); - } else { - for (int i = 0; i < reloadIndices.length; i++) { - sourceInfos.set(reloadIndices[i], newSourceInfos[i]); - } - } - return OpenFileResult.OK; - } - - public static void closeFile(SWFList swf) { - sourceInfos.remove(swf.sourceInfo); - mainFrame.getPanel().close(swf); - } - - public static void reloadFile(SWFList swf) { - //mainFrame.getPanel().close(swf); - openFile(swf.sourceInfo, null, sourceInfos.indexOf(swf.sourceInfo)); - } - - public static boolean closeAll() { - boolean closeResult = mainFrame.getPanel().closeAll(true); - if (closeResult) { - sourceInfos.clear(); - } - - return closeResult; - } - - public static boolean saveFileDialog(SWF swf, final SaveFileMode mode) { - JFileChooser fc = new JFileChooser(); - fc.setCurrentDirectory(new File(Configuration.lastSaveDir.get())); - String ext = ".swf"; - switch (mode) { - case SAVE: - case SAVEAS: - if (swf.getFile() != null) { - ext = Path.getExtension(swf.getFile()); - } - break; - case EXE: - ext = ".exe"; - break; - } - - FileFilter swfFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".swf")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.swf"); - } - }; - - FileFilter gfxFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".gfx")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.gfx"); - } - }; - - ExeExportMode exeExportMode = null; - if (mode == SaveFileMode.EXE) { - exeExportMode = Configuration.exeExportMode.get(); - if (exeExportMode == null) { - exeExportMode = ExeExportMode.WRAPPER; - } - String filterDescription = null; - switch (exeExportMode) { - case WRAPPER: - case PROJECTOR_WIN: - ext = ".exe"; - filterDescription = "filter.exe"; - break; - case PROJECTOR_MAC: - ext = ".dmg"; - filterDescription = "filter.dmg"; - break; - case PROJECTOR_LINUX: - // linux projector is compressed with tar.gz - // todo: decompress - ext = ""; - filterDescription = "filter.linuxExe"; - break; - } - - String fext = ext; - String ffilterDescription = filterDescription; - FileFilter exeFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(fext)) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate(ffilterDescription); - } - }; - fc.setFileFilter(exeFilter); - } else if (swf.gfx) { - fc.addChoosableFileFilter(swfFilter); - fc.setFileFilter(gfxFilter); - } else { - fc.setFileFilter(swfFilter); - fc.addChoosableFileFilter(gfxFilter); - } - final String extension = ext; - fc.setAcceptAllFileFilterUsed(false); - JFrame f = new JFrame(); - View.setWindowIcon(f); - if (fc.showSaveDialog(f) == JFileChooser.APPROVE_OPTION) { - File file = Helper.fixDialogFile(fc.getSelectedFile()); - FileFilter selFilter = fc.getFileFilter(); - try { - String fileName = file.getAbsolutePath(); - if (selFilter == swfFilter) { - if (!fileName.toLowerCase().endsWith(extension)) { - fileName += extension; - } - swf.gfx = false; - } - if (selFilter == gfxFilter) { - if (!fileName.toLowerCase().endsWith(".gfx")) { - fileName += ".gfx"; - } - swf.gfx = true; - } - Main.saveFile(swf, fileName, mode, exeExportMode); - Configuration.lastSaveDir.set(file.getParentFile().getAbsolutePath()); - return true; - } catch (IOException ex) { - View.showMessageDialog(null, AppStrings.translate("error.file.write")); - } - } - return false; - } - - public static boolean openFileDialog() { - JFileChooser fc = new JFileChooser(); - if (Configuration.openMultipleFiles.get()) { - fc.setMultiSelectionEnabled(true); - } - fc.setCurrentDirectory(new File(Configuration.lastOpenDir.get())); - FileFilter allSupportedFilter = new FileFilter() { - private final String[] supportedExtensions = new String[]{".swf", ".gfx", ".swc", ".zip"}; - - @Override - public boolean accept(File f) { - String name = f.getName().toLowerCase(); - for (String ext : supportedExtensions) { - if (name.endsWith(ext)) { - return true; - } - } - return f.isDirectory(); - } - - @Override - public String getDescription() { - String exts = Helper.joinStrings(supportedExtensions, "*%s", "; "); - return AppStrings.translate("filter.supported") + " (" + exts + ")"; - } - }; - fc.setFileFilter(allSupportedFilter); - FileFilter swfFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".swf")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.swf"); - } - }; - fc.addChoosableFileFilter(swfFilter); - - FileFilter swcFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".swc")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.swc"); - } - }; - fc.addChoosableFileFilter(swcFilter); - - FileFilter gfxFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".gfx")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.gfx"); - } - }; - fc.addChoosableFileFilter(gfxFilter); - - FileFilter zipFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return (f.getName().toLowerCase().endsWith(".zip")) || (f.isDirectory()); - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.zip"); - } - }; - fc.addChoosableFileFilter(zipFilter); - - FileFilter binaryFilter = new FileFilter() { - @Override - public boolean accept(File f) { - return true; - } - - @Override - public String getDescription() { - return AppStrings.translate("filter.binary"); - } - }; - fc.addChoosableFileFilter(binaryFilter); - - fc.setAcceptAllFileFilterUsed(false); - JFrame f = new JFrame(); - View.setWindowIcon(f); - int returnVal = fc.showOpenDialog(f); - if (returnVal == JFileChooser.APPROVE_OPTION) { - Configuration.lastOpenDir.set(Helper.fixDialogFile(fc.getSelectedFile()).getParentFile().getAbsolutePath()); - File[] selFiles = fc.getSelectedFiles(); - for (File file : selFiles) { - File selfile = Helper.fixDialogFile(file); - Main.openFile(selfile.getAbsolutePath(), null); - } - return true; - } else { - return false; - } - } - - public static void displayErrorFrame() { - ErrorLogFrame.getInstance().setVisible(true); - } - - private static String md5(byte data[]) { - try { - java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); - byte[] array = md.digest(data); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < array.length; ++i) { - sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); - } - return sb.toString(); - } catch (java.security.NoSuchAlgorithmException e) { - } - return null; - } - - private static void initGui() { - if (GraphicsEnvironment.isHeadless()) { - System.err.println("Error: Your system does not support Graphic User Interface"); - exit(); - } - - System.setProperty("sun.java2d.d3d", "false"); - System.setProperty("sun.java2d.noddraw", "true"); - - if (Configuration.hwAcceleratedGraphics.get()) { - System.setProperty("sun.java2d.opengl", Configuration._debugMode.get() ? "True" : "true"); - } else { - System.setProperty("sun.java2d.opengl", "false"); - } - - initUiLang(); - - if (Configuration.useRibbonInterface.get()) { - View.setLookAndFeel(); - } else { - try { - UIManager.put(SubstanceLookAndFeel.COLORIZATION_FACTOR, null); - UIManager.put("Tree.expandedIcon", null); - UIManager.put("Tree.collapsedIcon", null); - UIManager.put("ColorChooserUI", null); - UIManager.put("ColorChooser.swatchesRecentSwatchSize", null); - UIManager.put("ColorChooser.swatchesSwatchSize", null); - UIManager.put("RibbonApplicationMenuPopupPanelUI", null); - UIManager.put("RibbonApplicationMenuButtonUI", null); - UIManager.put("ProgressBarUI", null); - UIManager.put("TextField.background", null); - UIManager.put("FormattedTextField.background", null); - UIManager.put("CommandButtonUI", null); - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { - logger.log(Level.SEVERE, null, ex); - } - } - - View.execInEventDispatch(() -> { - ErrorLogFrame.createNewInstance(); - - autoCheckForUpdates(); - offerAssociation(); - loadingDialog = new LoadingDialog(); - - DebuggerTools.initDebugger().addMessageListener(new DebugListener() { - @Override - public void onMessage(String clientId, String msg) { - } - - @Override - public void onLoaderURL(String clientId, String url) { - } - - @Override - public void onLoaderBytes(String clientId, byte[] data) { - String hash = md5(data); - for (SWFList sl : Main.getMainFrame().getPanel().getSwfs()) { - for (int s = 0; s < sl.size(); s++) { - String t = sl.get(s).getFileTitle(); - if (t == null) { - t = ""; - } - if (t.endsWith(":" + hash)) { //this one is already opened - return; - } - } - } - SWF swf = Main.getMainFrame().getPanel().getCurrentSwf(); - - String title = swf == null ? "?" : swf.getFileTitle(); - title = title + ":" + hash; - String tfile; - try { - tfile = tempFile(title); - Helper.writeFile(tfile, data); - openFile(new SWFSourceInfo(null, tfile, title)); - } catch (IOException ex) { - logger.log(Level.SEVERE, "Cannot create tempfile"); - } - } - - @Override - public void onFinish(String clientId) { - } - }); - - try { - flashDebugger = new Debugger(); - debugHandler = new DebuggerHandler(); - debugHandler.addBreakListener(new DebuggerHandler.BreakListener() { - @Override - public void doContinue() { - mainFrame.getPanel().clearDebuggerColors(); - } - - @Override - public void breakAt(String scriptName, int line, final int classIndex, final int traitIndex, final int methodIndex) { - View.execInEventDispatch(new Runnable() { - @Override - public void run() { - mainFrame.getPanel().gotoScriptLine(getMainFrame().getPanel().getCurrentSwf(), scriptName, line, classIndex, traitIndex, methodIndex); - } - }); - } - }); - debugHandler.addConnectionListener(new DebuggerHandler.ConnectionListener() { - @Override - public void connected() { - Main.mainFrame.getMenu().updateComponents(); - } - - @Override - public void disconnected() { - if (Main.mainFrame != null && Main.mainFrame.getPanel() != null) { - Main.mainFrame.getPanel().refreshBreakPoints(); - } - } - }); - flashDebugger.addConnectionListener(debugHandler); - } catch (IOException ex) { - logger.log(Level.SEVERE, "eeex", ex); - } - }); - } - - public static void startDebugger() { - flashDebugger.startDebugger(); - } - - public static void stopDebugger() { - flashDebugger.stopDebugger(); - } - - public static void showModeFrame() { - ensureMainFrame(); - mainFrame.setVisible(true); - } - - private static void offerAssociation() { - boolean offered = Configuration.offeredAssociation.get(); - if (!offered) { - if (Platform.isWindows()) { - if ((!ContextMenuTools.isAddedToContextMenu()) && View.showConfirmDialog(null, "Do you want to add FFDec to context menu of SWF files?\n(Can be changed later from main menu)", "Context menu", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { - ContextMenuTools.addToContextMenu(true, false); - } - } - - Configuration.offeredAssociation.set(true); - } - } - - public static void initUiLang() { - if (GraphicsEnvironment.isHeadless()) { //No GUI in OS - return; - } - try { - Class cl = Class.forName("org.pushingpixels.substance.api.SubstanceLookAndFeel"); - Field field = cl.getDeclaredField("LABEL_BUNDLE"); - field.setAccessible(true); - field.set(null, null); - } catch (Throwable ex) { - logger.log(Level.SEVERE, null, ex); - } - - UIManager.put("OptionPane.okButtonText", AppStrings.translate("button.ok")); - UIManager.put("OptionPane.yesButtonText", AppStrings.translate("button.yes")); - UIManager.put("OptionPane.noButtonText", AppStrings.translate("button.no")); - UIManager.put("OptionPane.cancelButtonText", AppStrings.translate("button.cancel")); - UIManager.put("OptionPane.messageDialogTitle", AppStrings.translate("dialog.message.title")); - UIManager.put("OptionPane.titleText", AppStrings.translate("dialog.select.title")); - - UIManager.put("FileChooser.acceptAllFileFilterText", AppStrings.translate("FileChooser.acceptAllFileFilterText")); - UIManager.put("FileChooser.lookInLabelText", AppStrings.translate("FileChooser.lookInLabelText")); - UIManager.put("FileChooser.cancelButtonText", AppStrings.translate("button.cancel")); - UIManager.put("FileChooser.cancelButtonToolTipText", AppStrings.translate("button.cancel")); - UIManager.put("FileChooser.openButtonText", AppStrings.translate("FileChooser.openButtonText")); - UIManager.put("FileChooser.openButtonToolTipText", AppStrings.translate("FileChooser.openButtonToolTipText")); - UIManager.put("FileChooser.filesOfTypeLabelText", AppStrings.translate("FileChooser.filesOfTypeLabelText")); - UIManager.put("FileChooser.fileNameLabelText", AppStrings.translate("FileChooser.fileNameLabelText")); - UIManager.put("FileChooser.listViewButtonToolTipText", AppStrings.translate("FileChooser.listViewButtonToolTipText")); - UIManager.put("FileChooser.listViewButtonAccessibleName", AppStrings.translate("FileChooser.listViewButtonAccessibleName")); - UIManager.put("FileChooser.detailsViewButtonToolTipText", AppStrings.translate("FileChooser.detailsViewButtonToolTipText")); - UIManager.put("FileChooser.detailsViewButtonAccessibleName", AppStrings.translate("FileChooser.detailsViewButtonAccessibleName")); - UIManager.put("FileChooser.upFolderToolTipText", AppStrings.translate("FileChooser.upFolderToolTipText")); - UIManager.put("FileChooser.upFolderAccessibleName", AppStrings.translate("FileChooser.upFolderAccessibleName")); - UIManager.put("FileChooser.homeFolderToolTipText", AppStrings.translate("FileChooser.homeFolderToolTipText")); - UIManager.put("FileChooser.homeFolderAccessibleName", AppStrings.translate("FileChooser.homeFolderAccessibleName")); - UIManager.put("FileChooser.fileNameHeaderText", AppStrings.translate("FileChooser.fileNameHeaderText")); - UIManager.put("FileChooser.fileSizeHeaderText", AppStrings.translate("FileChooser.fileSizeHeaderText")); - UIManager.put("FileChooser.fileTypeHeaderText", AppStrings.translate("FileChooser.fileTypeHeaderText")); - UIManager.put("FileChooser.fileDateHeaderText", AppStrings.translate("FileChooser.fileDateHeaderText")); - UIManager.put("FileChooser.fileAttrHeaderText", AppStrings.translate("FileChooser.fileAttrHeaderText")); - UIManager.put("FileChooser.openDialogTitleText", AppStrings.translate("FileChooser.openDialogTitleText")); - UIManager.put("FileChooser.directoryDescriptionText", AppStrings.translate("FileChooser.directoryDescriptionText")); - UIManager.put("FileChooser.directoryOpenButtonText", AppStrings.translate("FileChooser.directoryOpenButtonText")); - UIManager.put("FileChooser.directoryOpenButtonToolTipText", AppStrings.translate("FileChooser.directoryOpenButtonToolTipText")); - UIManager.put("FileChooser.fileDescriptionText", AppStrings.translate("FileChooser.fileDescriptionText")); - UIManager.put("FileChooser.fileNameLabelText", AppStrings.translate("FileChooser.fileNameLabelText")); - UIManager.put("FileChooser.helpButtonText", AppStrings.translate("FileChooser.helpButtonText")); - UIManager.put("FileChooser.helpButtonToolTipText", AppStrings.translate("FileChooser.helpButtonToolTipText")); - UIManager.put("FileChooser.newFolderAccessibleName", AppStrings.translate("FileChooser.newFolderAccessibleName")); - UIManager.put("FileChooser.newFolderErrorText", AppStrings.translate("FileChooser.newFolderErrorText")); - UIManager.put("FileChooser.newFolderToolTipText", AppStrings.translate("FileChooser.newFolderToolTipText")); - UIManager.put("FileChooser.other.newFolder", AppStrings.translate("FileChooser.other.newFolder")); - UIManager.put("FileChooser.other.newFolder.subsequent", AppStrings.translate("FileChooser.other.newFolder.subsequent")); - UIManager.put("FileChooser.win32.newFolder", AppStrings.translate("FileChooser.win32.newFolder")); - UIManager.put("FileChooser.win32.newFolder.subsequent", AppStrings.translate("FileChooser.win32.newFolder.subsequent")); - UIManager.put("FileChooser.saveButtonText", AppStrings.translate("FileChooser.saveButtonText")); - UIManager.put("FileChooser.saveButtonToolTipText", AppStrings.translate("FileChooser.saveButtonToolTipText")); - UIManager.put("FileChooser.saveDialogTitleText", AppStrings.translate("FileChooser.saveDialogTitleText")); - UIManager.put("FileChooser.saveInLabelText", AppStrings.translate("FileChooser.saveInLabelText")); - UIManager.put("FileChooser.updateButtonText", AppStrings.translate("FileChooser.updateButtonText")); - UIManager.put("FileChooser.updateButtonToolTipText", AppStrings.translate("FileChooser.updateButtonToolTipText")); - - UIManager.put("FileChooser.detailsViewActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.detailsViewActionLabel.textAndMnemonic")); - UIManager.put("FileChooser.detailsViewButtonToolTip.textAndMnemonic", AppStrings.translate("FileChooser.detailsViewButtonToolTip.textAndMnemonic")); - UIManager.put("FileChooser.fileAttrHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileAttrHeader.textAndMnemonic")); - UIManager.put("FileChooser.fileDateHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileDateHeader.textAndMnemonic")); - UIManager.put("FileChooser.fileNameHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileNameHeader.textAndMnemonic")); - UIManager.put("FileChooser.fileNameLabel.textAndMnemonic", AppStrings.translate("FileChooser.fileNameLabel.textAndMnemonic")); - UIManager.put("FileChooser.fileSizeHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileSizeHeader.textAndMnemonic")); - UIManager.put("FileChooser.fileTypeHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileTypeHeader.textAndMnemonic")); - UIManager.put("FileChooser.filesOfTypeLabel.textAndMnemonic", AppStrings.translate("FileChooser.filesOfTypeLabel.textAndMnemonic")); - UIManager.put("FileChooser.folderNameLabel.textAndMnemonic", AppStrings.translate("FileChooser.folderNameLabel.textAndMnemonic")); - UIManager.put("FileChooser.homeFolderToolTip.textAndMnemonic", AppStrings.translate("FileChooser.homeFolderToolTip.textAndMnemonic")); - UIManager.put("FileChooser.listViewActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.listViewActionLabel.textAndMnemonic")); - UIManager.put("FileChooser.listViewButtonToolTip.textAndMnemonic", AppStrings.translate("FileChooser.listViewButtonToolTip.textAndMnemonic")); - UIManager.put("FileChooser.lookInLabel.textAndMnemonic", AppStrings.translate("FileChooser.lookInLabel.textAndMnemonic")); - UIManager.put("FileChooser.newFolderActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.newFolderActionLabel.textAndMnemonic")); - UIManager.put("FileChooser.newFolderToolTip.textAndMnemonic", AppStrings.translate("FileChooser.newFolderToolTip.textAndMnemonic")); - UIManager.put("FileChooser.refreshActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.refreshActionLabel.textAndMnemonic")); - UIManager.put("FileChooser.saveInLabel.textAndMnemonic", AppStrings.translate("FileChooser.saveInLabel.textAndMnemonic")); - UIManager.put("FileChooser.upFolderToolTip.textAndMnemonic", AppStrings.translate("FileChooser.upFolderToolTip.textAndMnemonic")); - UIManager.put("FileChooser.viewMenuButtonAccessibleName", AppStrings.translate("FileChooser.viewMenuButtonAccessibleName")); - UIManager.put("FileChooser.viewMenuButtonToolTipText", AppStrings.translate("FileChooser.viewMenuButtonToolTipText")); - UIManager.put("FileChooser.viewMenuLabel.textAndMnemonic", AppStrings.translate("FileChooser.viewMenuLabel.textAndMnemonic")); - UIManager.put("FileChooser.newFolderActionLabelText", AppStrings.translate("FileChooser.newFolderActionLabelText")); - UIManager.put("FileChooser.listViewActionLabelText", AppStrings.translate("FileChooser.listViewActionLabelText")); - UIManager.put("FileChooser.detailsViewActionLabelText", AppStrings.translate("FileChooser.detailsViewActionLabelText")); - UIManager.put("FileChooser.refreshActionLabelText", AppStrings.translate("FileChooser.refreshActionLabelText")); - UIManager.put("FileChooser.sortMenuLabelText", AppStrings.translate("FileChooser.sortMenuLabelText")); - UIManager.put("FileChooser.viewMenuLabelText", AppStrings.translate("FileChooser.viewMenuLabelText")); - UIManager.put("FileChooser.fileSizeKiloBytes", AppStrings.translate("FileChooser.fileSizeKiloBytes")); - UIManager.put("FileChooser.fileSizeMegaBytes", AppStrings.translate("FileChooser.fileSizeMegaBytes")); - UIManager.put("FileChooser.fileSizeGigaBytes", AppStrings.translate("FileChooser.fileSizeGigaBytes")); - UIManager.put("FileChooser.folderNameLabelText", AppStrings.translate("FileChooser.folderNameLabelText")); - - UIManager.put("ColorChooser.okText", AppStrings.translate("ColorChooser.okText")); - UIManager.put("ColorChooser.cancelText", AppStrings.translate("ColorChooser.cancelText")); - UIManager.put("ColorChooser.resetText", AppStrings.translate("ColorChooser.resetText")); - UIManager.put("ColorChooser.previewText", AppStrings.translate("ColorChooser.previewText")); - UIManager.put("ColorChooser.swatchesNameText", AppStrings.translate("ColorChooser.swatchesNameText")); - UIManager.put("ColorChooser.swatchesRecentText", AppStrings.translate("ColorChooser.swatchesRecentText")); - UIManager.put("ColorChooser.sampleText", AppStrings.translate("ColorChooser.sampleText")); - - } - - public static void initLang() { - if (!Configuration.locale.hasValue()) { - if (Platform.isWindows()) { - //Load from Installer - String uninstKey = "{E618D276-6596-41F4-8A98-447D442A77DB}_is1"; - uninstKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + uninstKey; - try { - if (Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, uninstKey)) { - if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, uninstKey, "NSIS: Language")) { - String installedLoc = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, uninstKey, "NSIS: Language"); - int lcid = Integer.parseInt(installedLoc); - char[] buf = new char[9]; - int cnt = Kernel32.INSTANCE.GetLocaleInfo(lcid, Kernel32.LOCALE_SISO639LANGNAME, buf, 9); - String langCode = new String(buf, 0, cnt).trim().toLowerCase(); - - cnt = Kernel32.INSTANCE.GetLocaleInfo(lcid, Kernel32.LOCALE_SISO3166CTRYNAME, buf, 9); - String countryCode = new String(buf, 0, cnt).trim().toLowerCase(); - - List langs = Arrays.asList(SelectLanguageDialog.getAvailableLanguages()); - for (int i = 0; i < langs.size(); i++) { - langs.set(i, langs.get(i).toLowerCase()); - } - - String selectedLang = null; - - if (langs.contains(langCode + "-" + countryCode)) { - selectedLang = SelectLanguageDialog.getAvailableLanguages()[langs.indexOf(langCode + "-" + countryCode)]; - } else if (langs.contains(langCode)) { - selectedLang = SelectLanguageDialog.getAvailableLanguages()[langs.indexOf(langCode)]; - } - if (selectedLang != null) { - Configuration.locale.set(selectedLang); - } - } - } - } catch (Exception ex) { - //ignore - } - } - } - Locale.setDefault(Locale.forLanguageTag(Configuration.locale.get())); - AppStrings.updateLanguage(); - - Helper.decompilationErrorAdd = AppStrings.translate(Configuration.autoDeobfuscate.get() ? "deobfuscation.comment.failed" : "deobfuscation.comment.tryenable"); - } - - /** - * Clear old FFDec/JavactiveX temp files - */ - private static void clearTemp() { - String tempDirPath = System.getProperty("java.io.tmpdir"); - if (tempDirPath == null) { - return; - } - File tempDir = new File(tempDirPath); - if (!tempDir.exists()) { - return; - } - File[] delFiles = tempDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.matches("ffdec_cache.*\\.tmp") || name.matches("javactivex_.*\\.exe") || name.matches("temp[0-9]+\\.swf") || name.matches("ffdec_view_.*\\.swf"); - } - }); - - if (delFiles != null) { - for (File f : delFiles) { - try { - f.delete(); - } catch (Exception ex) { - //ignore - } - } - } - } - - /** - * @param args the command line arguments - * @throws IOException On error - */ - public static void main(String[] args) throws IOException { - setSessionLoaded(false); - clearTemp(); - - try { - SWFDecompilerPlugin.loadPlugins(); - } catch (Throwable ex) { - logger.log(Level.SEVERE, "Failed to load plugins", ex); - } - - AppStrings.setResourceClass(MainFrame.class); - initLogging(Configuration._debugMode.get()); - - initLang(); - - if (Configuration.cacheOnDisk.get()) { - Cache.setStorageType(Cache.STORAGE_FILES); - } else { - Cache.setStorageType(Cache.STORAGE_MEMORY); - } - - if (args.length == 0) { - initGui(); - checkLibraryVersion(); - View.execInEventDispatch(() -> { - if (Configuration.allowOnlyOneInstance.get() && FirstInstance.focus()) { //Try to focus first instance - Main.exit(); - } else { - showModeFrame(); - reloadLastSession(); - } - }); - } else { - checkLibraryVersion(); - setSessionLoaded(true); - String[] filesToOpen = CommandLineArgumentParser.parseArguments(args); - if (filesToOpen != null && filesToOpen.length > 0) { - View.execInEventDispatch(() -> { - initGui(); - shouldCloseWhenClosingLoadingDialog = true; - if (Configuration.allowOnlyOneInstance.get() && FirstInstance.openFiles(Arrays.asList(filesToOpen))) { //Try to open in first instance - Main.exit(); - } else { - for (String fileToOpen : filesToOpen) { - openFile(fileToOpen, null); - } - } - }); - } - } - } - - private static void checkLibraryVersion() { - if (!ApplicationInfo.version.equals("unknown") && !ApplicationInfo.libraryVersion.equals("unknown") - && !Objects.equals(ApplicationInfo.version, ApplicationInfo.libraryVersion)) { - logger.log(Level.WARNING, "Application version is different from library version. FFDec may not work properly."); - } - } - - private static void reloadLastSession() { - boolean openingFiles = false; - if (Configuration.saveSessionOnExit.get()) { - String lastSession = Configuration.lastSessionFiles.get(); - if (lastSession != null && lastSession.length() > 0) { - String[] filesToOpen = lastSession.split(File.pathSeparator, -1); - List exfiles = new ArrayList<>(); - List extitles = new ArrayList<>(); - String lastSessionTitles = Configuration.lastSessionFileTitles.get(); - String[] fileTitles = new String[0]; - if (lastSessionTitles != null && !lastSessionTitles.isEmpty()) { - fileTitles = lastSessionTitles.split(File.pathSeparator, -1); - } - for (int i = 0; i < filesToOpen.length; i++) { - if (new File(filesToOpen[i]).exists()) { - exfiles.add(filesToOpen[i]); - if (fileTitles.length > i) { - extitles.add(fileTitles[i]); - } else { - extitles.add(null); - } - } - } - SWFSourceInfo[] sourceInfos = new SWFSourceInfo[exfiles.size()]; - for (int i = 0; i < exfiles.size(); i++) { - String extitle = extitles.get(i); - sourceInfos[i] = new SWFSourceInfo(null, exfiles.get(i), extitle == null || extitle.isEmpty() ? null : extitle); - } - if (sourceInfos.length > 0) { - openingFiles = true; - openFile(sourceInfos, () -> { - mainFrame.getPanel().tagTree.setSelectionPathString(Configuration.lastSessionSelection.get()); - setSessionLoaded(true); - }); - } - } - } - - if (!openingFiles) { - setSessionLoaded(true); - } - } - - public static String tempFile(String url) throws IOException { - File f = new File(Configuration.getFFDecHome() + "saved" + File.separator); - Path.createDirectorySafe(f); - return Configuration.getFFDecHome() + "saved" + File.separator + "asdec_" + Integer.toHexString(url.hashCode()) + ".tmp"; - } - - public static void removeTrayIcon() { - if (SystemTray.isSupported()) { - SystemTray tray = SystemTray.getSystemTray(); - if (trayIcon != null) { - tray.remove(trayIcon); - trayIcon = null; - } - } - } - - public static void switchProxy() { - proxyFrame.switchState(); - if (stopMenuItem != null) { - if (proxyFrame.isRunning()) { - stopMenuItem.setLabel(AppStrings.translate("proxy.stop")); - } else { - stopMenuItem.setLabel(AppStrings.translate("proxy.start")); - } - } - } - - public static void addTrayIcon() { - if (trayIcon != null) { - return; - } - if (SystemTray.isSupported()) { - SystemTray tray = SystemTray.getSystemTray(); - trayIcon = new TrayIcon(View.loadImage("proxy16"), ApplicationInfo.VENDOR + " " + ApplicationInfo.SHORT_APPLICATION_NAME + " " + AppStrings.translate("proxy")); - trayIcon.setImageAutoSize(true); - PopupMenu trayPopup = new PopupMenu(); - - ActionListener trayListener = new ActionListener() { - /** - * Invoked when an action occurs. - */ - @Override - public void actionPerformed(ActionEvent e) { - if (e.getActionCommand().equals("EXIT")) { - Main.exit(); - } - if (e.getActionCommand().equals("SHOW")) { - Main.showProxy(); - } - if (e.getActionCommand().equals("SWITCH")) { - Main.switchProxy(); - } - } - }; - - MenuItem showMenuItem = new MenuItem(AppStrings.translate("proxy.show")); - showMenuItem.setActionCommand("SHOW"); - showMenuItem.addActionListener(trayListener); - trayPopup.add(showMenuItem); - stopMenuItem = new MenuItem(AppStrings.translate("proxy.start")); - stopMenuItem.setActionCommand("SWITCH"); - stopMenuItem.addActionListener(trayListener); - trayPopup.add(stopMenuItem); - trayPopup.addSeparator(); - MenuItem exitMenuItem = new MenuItem(AppStrings.translate("exit")); - exitMenuItem.setActionCommand("EXIT"); - exitMenuItem.addActionListener(trayListener); - trayPopup.add(exitMenuItem); - - trayIcon.setPopupMenu(trayPopup); - trayIcon.addMouseListener(new MouseAdapter() { - /** - * {@inheritDoc} - */ - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - Main.showProxy(); - } - } - }); - try { - tray.add(trayIcon); - } catch (AWTException ex) { - } - } - } - - public static void exit() { - Configuration.saveConfig(); - if (mainFrame != null && mainFrame.getPanel() != null) { - mainFrame.getPanel().unloadFlashPlayer(); - mainFrame.dispose(); - } - if (fileTxt != null) { - try { - fileTxt.flush(); - fileTxt.close(); - } catch (Exception ex) { - //ignore - } - } - System.exit(0); - } - - public static void about() { - (new AboutDialog()).setVisible(true); - } - - public static void advancedSettings() { - advancedSettings(null); - } - - public static void advancedSettings(String category) { - (new AdvancedSettingsDialog(category)).setVisible(true); - } - - public static void autoCheckForUpdates() { - if (Configuration.checkForUpdatesAuto.get()) { - Calendar lastUpdatesCheckDate = Configuration.lastUpdatesCheckDate.get(); - if ((lastUpdatesCheckDate == null) || (lastUpdatesCheckDate.getTime().getTime() < Calendar.getInstance().getTime().getTime() - Configuration.checkForUpdatesDelay.get())) { - new SwingWorker() { - @Override - protected Object doInBackground() throws Exception { - checkForUpdates(); - return null; - } - }.execute(); - } - } - } - - public static boolean checkForUpdates() { - String currentVersion = ApplicationInfo.version; - if (currentVersion.equals("unknown")) { - // sometimes during development the version information is not available - return false; - } - - List accepted = new ArrayList<>(); - if (Configuration.checkForUpdatesStable.get()) { - accepted.add("stable"); - } - if (Configuration.checkForUpdatesNightly.get()) { - accepted.add("nightly"); - } - - if (accepted.isEmpty()) { - return false; - } - - String acceptVersions = String.join(",", accepted); - try { - String proxyAddress = Configuration.updateProxyAddress.get(); - URL url = new URL(ApplicationInfo.updateCheckUrl); - - URLConnection uc; - if (proxyAddress != null && !proxyAddress.isEmpty()) { - int port = 8080; - if (proxyAddress.contains(":")) { - String[] parts = proxyAddress.split(":"); - port = Integer.parseInt(parts[1]); - proxyAddress = parts[0]; - } - - uc = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, port))); - } else { - uc = url.openConnection(); - } - uc.setRequestProperty("X-Accept-Versions", acceptVersions); - uc.setRequestProperty("X-Update-Major", "" + UPDATE_SYSTEM_MAJOR); - uc.setRequestProperty("X-Update-Minor", "" + UPDATE_SYSTEM_MINOR); - uc.setRequestProperty("User-Agent", ApplicationInfo.shortApplicationVerName); - String currentLoc = Configuration.locale.get("en"); - uc.setRequestProperty("Accept-Language", currentLoc + ("en".equals(currentLoc) ? "" : ", en;q=0.8")); - - uc.connect(); - - BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream())); - String s; - final java.util.List versions = new ArrayList<>(); - String header = ""; - Pattern headerPat = Pattern.compile("\\[([a-zA-Z0-9]+)\\]"); - int updateMajor; - int updateMinor; - Version ver = null; - while ((s = br.readLine()) != null) { - - Matcher m = headerPat.matcher(s); - if (m.matches()) { - header = m.group(1); - if (header.equals("version")) { - ver = new Version(); - versions.add(ver); - } - if (header.equals("noversion")) { - break; - } - } else if (s.contains("=")) { - String key = s.substring(0, s.indexOf('=')); - String val = s.substring(s.indexOf('=') + 1); - if ("updateSystem".equals(header)) { - if (key.equals("majorVersion")) { - updateMajor = Integer.parseInt(val); - if (updateMajor > UPDATE_SYSTEM_MAJOR) { - break; - } - } - if (key.equals("minorVersion")) { - updateMinor = Integer.parseInt(val); - } - } - if ("version".equals(header) && (ver != null)) { - if (key.equals("versionId")) { - ver.versionId = Integer.parseInt(val); - } - if (key.equals("versionName")) { - ver.versionName = val; - } - if (key.equals("nightly")) { - ver.nightly = val.equals("true"); - } - if (key.equals("revision")) { - ver.revision = val; - } - if (key.equals("build")) { - ver.build = Integer.parseInt(val); - } - if (key.equals("major")) { - ver.major = Integer.parseInt(val); - } - if (key.equals("minor")) { - ver.minor = Integer.parseInt(val); - } - if (key.equals("release")) { - ver.release = Integer.parseInt(val); - } - if (key.equals("longVersionName")) { - ver.longVersionName = val; - } - if (key.equals("releaseDate")) { - ver.releaseDate = val; - } - if (key.equals("appName")) { - ver.appName = val; - } - if (key.equals("appFullName")) { - ver.appFullName = val; - } - if (key.equals("updateLink")) { - ver.updateLink = val; - } - if (key.equals("change[]")) { - String changeType = val.substring(0, val.indexOf('|')); - String change = val.substring(val.indexOf('|') + 1); - if (!ver.changes.containsKey(changeType)) { - ver.changes.put(changeType, new ArrayList<>()); - } - List chlist = ver.changes.get(changeType); - chlist.add(change); - } - } - } - } - - if (!versions.isEmpty()) { - View.execInEventDispatch(() -> { - NewVersionDialog newVersionDialog = new NewVersionDialog(versions); - newVersionDialog.setVisible(true); - Configuration.lastUpdatesCheckDate.set(Calendar.getInstance()); - }); - - return true; - } - } catch (IOException | NumberFormatException ex) { - return false; - } - Configuration.lastUpdatesCheckDate.set(Calendar.getInstance()); - return false; - } - - private static FileHandler fileTxt; - - public static void clearLogFile() { - Logger logger = Logger.getLogger(""); - - FileHandler oldFileTxt = fileTxt; - fileTxt = null; - if (oldFileTxt != null) { - logger.removeHandler(fileTxt); - oldFileTxt.flush(); - oldFileTxt.close(); - } - - String fileName = null; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); - - try { - fileName = Configuration.getFFDecHome() + "logs" + File.separator; - if (Configuration.useDetailedLogging.get()) { - fileName += "log-" + sdf.format(new Date()) + ".txt"; - } else { - fileName += "log.txt"; - } - File f = new File(fileName).getParentFile(); - if (!f.exists()) { - f.mkdir(); - } - fileTxt = new FileHandler(fileName); - } catch (IOException | SecurityException ex) { - //cannot get lock error - if (ex.getMessage().contains("lock for")) { - //remove all old log files and their .lck - for (int i = 0; i <= 100; i++) { - File flog = new File(fileName + (i == 0 ? "" : "." + i)); - File flog_lock = new File(fileName + (i == 0 ? "" : "." + i) + ".lck"); - flog.delete(); - flog_lock.delete(); - } - try { - fileTxt = new FileHandler(fileName); - } catch (IOException | SecurityException ex1) { - logger.log(Level.SEVERE, "Cannot initialize logging", ex); - } - } else { - logger.log(Level.SEVERE, "Cannot initialize logging", ex); - } - } - - Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - logger.log(Level.SEVERE, "Uncaught exception in thread: " + t.getName(), e); - if (e instanceof OutOfMemoryError || !Helper.is64BitJre() && Helper.is64BitOs()) { - View.showMessageDialog(null, AppStrings.translate("message.warning.outOfMemory32BitJre"), AppStrings.translate("message.warning"), JOptionPane.WARNING_MESSAGE); - } - } - }); - - Formatter formatterTxt = new LogFormatter(); - if (fileTxt != null) { - fileTxt.setFormatter(formatterTxt); - logger.addHandler(fileTxt); - } - - if (!GraphicsEnvironment.isHeadless() && ErrorLogFrame.hasInstance()) { - ErrorLogFrame.getInstance().clearErrorState(); - } - - sdf = new SimpleDateFormat("yyyy-MM-dd"); - logger.log(Level.INFO, "Date: {0}", sdf.format(new Date())); - logger.log(Level.INFO, ApplicationInfo.applicationVerName); - logger.log(Level.INFO, "{0} {1} {2}", new Object[]{ - System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")}); - logger.log(Level.INFO, "{0} {1} {2}", new Object[]{ - System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("os.arch")}); - } - - public static void initLogging(boolean debug) { - try { - Logger logger = Logger.getLogger(""); - logger.setLevel(Configuration.logLevel); - - Handler[] handlers = logger.getHandlers(); - for (int i = handlers.length - 1; i >= 0; i--) { - logger.removeHandler(handlers[i]); - } - - ConsoleHandler conHan = new ConsoleHandler(); - conHan.setLevel(debug ? Level.CONFIG : Level.WARNING); - SimpleFormatter formatterTxt = new SimpleFormatter(); - conHan.setFormatter(formatterTxt); - logger.addHandler(conHan); - clearLogFile(); - - } catch (Exception ex) { - throw new RuntimeException("Problems with creating the log files"); - } - } -} +/* + * Copyright (C) 2010-2016 JPEXS + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.jpexs.decompiler.flash.gui; + +import com.jpexs.debugger.flash.Debugger; +import com.jpexs.debugger.flash.DebuggerCommands; +import com.jpexs.debugger.flash.Variable; +import com.jpexs.debugger.flash.VariableType; +import com.jpexs.debugger.flash.messages.in.InCallFunction; +import com.jpexs.decompiler.flash.ApplicationInfo; +import com.jpexs.decompiler.flash.EventListener; +import com.jpexs.decompiler.flash.SWF; +import com.jpexs.decompiler.flash.SWFBundle; +import com.jpexs.decompiler.flash.SWFSourceInfo; +import com.jpexs.decompiler.flash.SearchMode; +import com.jpexs.decompiler.flash.SwfOpenException; +import com.jpexs.decompiler.flash.UrlResolver; +import com.jpexs.decompiler.flash.Version; +import com.jpexs.decompiler.flash.abc.avm2.AVM2Code; +import com.jpexs.decompiler.flash.abc.avm2.parser.script.Reference; +import com.jpexs.decompiler.flash.configuration.Configuration; +import com.jpexs.decompiler.flash.configuration.SwfSpecificConfiguration; +import com.jpexs.decompiler.flash.console.CommandLineArgumentParser; +import com.jpexs.decompiler.flash.console.ContextMenuTools; +import com.jpexs.decompiler.flash.exporters.modes.ExeExportMode; +import com.jpexs.decompiler.flash.gui.debugger.DebugListener; +import com.jpexs.decompiler.flash.gui.debugger.DebuggerTools; +import com.jpexs.decompiler.flash.gui.pipes.FirstInstance; +import com.jpexs.decompiler.flash.gui.proxy.ProxyFrame; +import com.jpexs.decompiler.flash.helpers.SWFDecompilerPlugin; +import com.jpexs.decompiler.flash.tags.Tag; +import com.jpexs.decompiler.flash.tags.base.FontTag; +import com.jpexs.decompiler.flash.tags.base.ImportTag; +import com.jpexs.decompiler.flash.treeitems.SWFList; +import com.jpexs.helpers.Cache; +import com.jpexs.helpers.CancellableWorker; +import com.jpexs.helpers.Helper; +import com.jpexs.helpers.Path; +import com.jpexs.helpers.ProgressListener; +import com.jpexs.helpers.Stopwatch; +import com.jpexs.helpers.streams.SeekableInputStream; +import com.sun.jna.Platform; +import com.sun.jna.platform.win32.Advapi32Util; +import com.sun.jna.platform.win32.Kernel32; +import com.sun.jna.platform.win32.WinReg; +import java.awt.AWTException; +import java.awt.Frame; +import java.awt.GraphicsEnvironment; +import java.awt.MenuItem; +import java.awt.PopupMenu; +import java.awt.SystemTray; +import java.awt.TrayIcon; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.logging.ConsoleHandler; +import java.util.logging.FileHandler; +import java.util.logging.Formatter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.logging.SimpleFormatter; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.SwingWorker; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.filechooser.FileFilter; +import org.pushingpixels.substance.api.SubstanceLookAndFeel; + +/** + * Main executable class + * + * @author JPEXS + */ +public class Main { + + protected static ProxyFrame proxyFrame; + + private static List sourceInfos = new ArrayList<>(); + + public static LoadingDialog loadingDialog; + + private static boolean working = false; + + private static TrayIcon trayIcon; + + private static MenuItem stopMenuItem; + + private static volatile MainFrame mainFrame; + + public static final int UPDATE_SYSTEM_MAJOR = 1; + + public static final int UPDATE_SYSTEM_MINOR = 3; + + private static LoadFromMemoryFrame loadFromMemoryFrame; + + private static LoadFromCacheFrame loadFromCacheFrame; + + private static final Logger logger = Logger.getLogger(Main.class.getName()); + + public static DebugLogDialog debugDialog; + + public static boolean shouldCloseWhenClosingLoadingDialog; + + private static Debugger flashDebugger; + + private static DebuggerHandler debugHandler = null; + + //private static int ip = 0; + //private static String ipClass = null; + private static Process runProcess; + + private static boolean runProcessDebug; + + private static boolean runProcessDebugPCode; + + private static boolean inited = false; + + private static File runTempFile; + + private static List runTempFiles = new ArrayList<>(); + + public static void freeRun() { + synchronized (Main.class) { + if (runTempFile != null) { + runTempFile.delete(); + runTempFile = null; + } + for (File f : runTempFiles) { + f.delete(); + } + runTempFiles.clear(); + + runProcess = null; + } + if (mainFrame != null && mainFrame.getPanel() != null) { + mainFrame.getPanel().clearDebuggerColors(); + } + if (runProcessDebug) { + Main.getDebugHandler().disconnect(); + } + } + + public static synchronized boolean isDebugPaused() { + return runProcess != null && runProcessDebug && getDebugHandler().isPaused(); + } + + public static synchronized boolean isDebugRunning() { + return runProcess != null && runProcessDebug; + } + + public static synchronized boolean isDebugPCode() { + return runProcessDebugPCode; + } + + public static synchronized boolean isDebugConnected() { + return getDebugHandler().isConnected(); + } + + public static synchronized boolean isRunning() { + return runProcess != null && !runProcessDebug; + } + + /** + * FIXME! + * + * @param v + */ + public static synchronized void dumpBytes(Variable v) { + InCallFunction icf; + try { + long objectId = 0l; + if ((v.vType == VariableType.OBJECT || v.vType == VariableType.MOVIECLIP)) { + objectId = (Long) v.value; + } + Object oldPos = getDebugHandler().getVariable(objectId, "position", true).parent.value; + getDebugHandler().setVariable(objectId, "position", VariableType.NUMBER, 0); + icf = getDebugHandler().callFunction(false, "readUTF", v, new ArrayList<>()); + System.out.println("Result=" + icf.variables.get(0).value); + getDebugHandler().setVariable(objectId, "position", VariableType.NUMBER, oldPos); + } catch (DebuggerHandler.ActionScriptException ex) { + Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); + } + + } + + public static synchronized boolean addWatch(Variable v, long v_id, boolean watchRead, boolean watchWrite) { + DebuggerCommands.Watch w = getDebugHandler().addWatch(v, v_id, watchRead, watchWrite); + return w != null; + } + + public static void runPlayer(String title, final String exePath, String file, String flashVars) { + if (!new File(file).exists()) { + return; + } + if (flashVars != null && !flashVars.isEmpty()) { + file += "?" + flashVars; + } + final String ffile = file; + + CancellableWorker runWorker = new CancellableWorker() { + @Override + protected Object doInBackground() throws Exception { + Process proc; + try { + proc = Runtime.getRuntime().exec(new String[]{exePath, ffile}); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + return null; + } + boolean isDebug; + + synchronized (Main.class) { + runProcess = proc; + isDebug = runProcessDebug; + } + if (isDebug) { + mainFrame.getMenu().hilightPath("/debugging"); + } + mainFrame.getMenu().updateComponents(); + try { + if (proc != null) { + proc.waitFor(); + } + } catch (InterruptedException ex) { + if (proc != null) { + try { + proc.destroy(); + } catch (Exception ex2) { + //ignore + } + } + } + freeRun(); + stopDebugger(); + mainFrame.getMenu().updateComponents(); + return null; + } + + @Override + protected void done() { + Main.stopWork(); + } + + @Override + public void workerCancelled() { + Main.stopWork(); + synchronized (Main.class) { + if (runProcess != null) { + try { + runProcess.destroy(); + } catch (Exception ex) { + + } + } + } + freeRun(); + mainFrame.getMenu().updateComponents(); + } + }; + + mainFrame.getMenu().updateComponents(); + Main.startWork(title + "...", runWorker); + runWorker.execute(); + } + + public static void stopRun() { + + synchronized (Main.class) { + if (runProcess != null) { + runProcess.destroy(); + } + } + freeRun(); + stopDebugger(); + mainFrame.getMenu().updateComponents(); + } + + private static interface SwfPreparation { + + public SWF prepare(SWF swf); + } + + private static class SwfRunPrepare implements SwfPreparation { + + @Override + public SWF prepare(SWF swf) { + if (Configuration.autoOpenLoadedSWFs.get()) { + if (!DebuggerTools.hasDebugger(swf)) { + DebuggerTools.switchDebugger(swf); + } + DebuggerTools.injectDebugLoader(swf); + } + return swf; + } + } + + private static class SwfDebugPrepare extends SwfRunPrepare { + + private boolean doPCode; + + public SwfDebugPrepare(boolean doPCode) { + this.doPCode = doPCode; + } + + @Override + public SWF prepare(SWF instrSWF) { + instrSWF = super.prepare(instrSWF); + try { + File fTempFile = new File(instrSWF.getFile()); + instrSWF.enableDebugging(true, new File("."), true, doPCode); + FileOutputStream fos = new FileOutputStream(fTempFile); + instrSWF.saveTo(fos); + fos.close(); + if (!instrSWF.isAS3()) { + //Read again, because line file offsets changed with adding debug tags + //TODO: handle somehow without rereading? + instrSWF = null; + try (FileInputStream fis = new FileInputStream(fTempFile)) { + instrSWF = new SWF(fis, false, false); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, null, ex); + } + if (instrSWF != null) { + String swfFileName = fTempFile.getAbsolutePath(); + if (swfFileName.toLowerCase().endsWith(".swf")) { + swfFileName = swfFileName.substring(0, swfFileName.length() - 4) + ".swd"; + } else { + swfFileName = swfFileName + ".swd"; + } + File swdFile = new File(swfFileName); + if (doPCode) { + instrSWF.generatePCodeSwdFile(swdFile, getPackBreakPoints(true)); + } else { + instrSWF.generateSwdFile(swdFile, getPackBreakPoints(true)); + } + } + } + } catch (IOException ex) { + //ignore, return instrSWF + } + return instrSWF; + } + } + + private static void prepareSwf(SwfPreparation prep, File toPrepareFile, File origFile, List tempFiles) throws IOException { + SWF instrSWF = null; + try (FileInputStream fis = new FileInputStream(toPrepareFile)) { + instrSWF = new SWF(fis, toPrepareFile.getAbsolutePath(), origFile.getName(), false); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, null, ex); + } + if (instrSWF != null) { + for (Tag t : instrSWF.getLocalTags()) { + if (t instanceof ImportTag) { + ImportTag it = (ImportTag) t; + String url = it.getUrl(); + File importedFile = new File(origFile.getParentFile(), url); + if (importedFile.exists()) { + File newTempFile = File.createTempFile("ffdec_run_import_", ".swf"); + it.setUrl("./" + newTempFile.getName()); + byte[] impData = Helper.readFile(importedFile.getAbsolutePath()); + Helper.writeFile(newTempFile.getAbsolutePath(), impData); + tempFiles.add(newTempFile); + prepareSwf(prep, newTempFile, importedFile, tempFiles); + } + } + } + if (prep != null) { + instrSWF = prep.prepare(instrSWF); + } + try (FileOutputStream fos = new FileOutputStream(toPrepareFile)) { + instrSWF.saveTo(fos); + } + } + } + + public static void run(SWF swf) { + String flashVars = "";//key=val&key2=val2 + String playerLocation = Configuration.playerLocation.get(); + if (playerLocation.isEmpty() || (!new File(playerLocation).exists())) { + View.showMessageDialog(null, AppStrings.translate("message.playerpath.notset"), AppStrings.translate("error"), JOptionPane.ERROR_MESSAGE); + advancedSettings("paths"); + return; + } + if (swf == null) { + return; + } + File tempFile; + List tempFiles = new ArrayList<>(); + try { + tempFile = File.createTempFile("ffdec_run_", ".swf"); + + try (FileOutputStream fos = new FileOutputStream(tempFile)) { + swf.saveTo(fos); + } + + prepareSwf(new SwfRunPrepare(), tempFile, new File(swf.getFile()), tempFiles); + + } catch (IOException ex) { + return; + + } + if (tempFile != null) { + synchronized (Main.class) { + runTempFile = tempFile; + runTempFiles = tempFiles; + runProcessDebug = false; + } + runPlayer(AppStrings.translate("work.running"), playerLocation, tempFile.getAbsolutePath(), flashVars); + } + } + + public static void runDebug(SWF swf, final boolean doPCode) { + String flashVars = "";//key=val&key2=val2 + String playerLocation = Configuration.playerDebugLocation.get(); + if (playerLocation.isEmpty() || (!new File(playerLocation).exists())) { + View.showMessageDialog(null, AppStrings.translate("message.playerpath.debug.notset"), AppStrings.translate("error"), JOptionPane.ERROR_MESSAGE); + Main.advancedSettings("paths"); + return; + } + if (swf == null) { + return; + } + File tempFile = null; + + try { + tempFile = File.createTempFile("ffdec_debug_", ".swf"); + } catch (Exception ex) { + + } + + if (tempFile != null) { + final File fTempFile = tempFile; + final List tempFiles = new ArrayList<>(); + CancellableWorker instrumentWorker = new CancellableWorker() { + @Override + protected Object doInBackground() throws Exception { + + try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(fTempFile))) { + swf.saveTo(fos); + } + prepareSwf(new SwfDebugPrepare(doPCode), fTempFile, new File(swf.getFile()), tempFiles); + return null; + } + + @Override + public void workerCancelled() { + Main.stopWork(); + } + + @Override + protected void done() { + synchronized (Main.class) { + runTempFile = fTempFile; + runProcessDebug = true; + runProcessDebugPCode = doPCode; + runTempFiles = tempFiles; + } + Main.stopWork(); + Main.startDebugger(); + runPlayer(AppStrings.translate("work.debugging.wait"), playerLocation, fTempFile.getAbsolutePath(), flashVars); + } + }; + + Main.startWork(AppStrings.translate("work.debugging.instrumenting"), instrumentWorker); + instrumentWorker.execute(); + } + } + + /* public static void debuggerNotSuspended() { + + }*/ + public static boolean isDebugging() { + return isDebugRunning(); + } + + public synchronized static int getIp(Object pack) { + return getDebugHandler().getBreakIp(); + } + + public synchronized static String getIpClass() { + return getDebugHandler().getBreakScriptName(); + } + + public static synchronized boolean isBreakPointValid(String scriptName, int line) { + return !getDebugHandler().isBreakpointInvalid(scriptName, line); + } + + public synchronized static void addBreakPoint(String scriptName, int line) { + getDebugHandler().addBreakPoint(scriptName, line); + } + + public synchronized static void removeBreakPoint(String scriptName, int line) { + getDebugHandler().removeBreakPoint(scriptName, line); + } + + public synchronized static boolean toggleBreakPoint(String scriptName, int line) { + if (getDebugHandler().isBreakpointToAdd(scriptName, line) || getDebugHandler().isBreakpointConfirmed(scriptName, line) || getDebugHandler().isBreakpointInvalid(scriptName, line)) { + getDebugHandler().removeBreakPoint(scriptName, line); + return false; + } else { + getDebugHandler().addBreakPoint(scriptName, line); + return true; + } + } + + public synchronized static Map> getPackBreakPoints(boolean validOnly) { + return getDebugHandler().getAllBreakPoints(validOnly); + } + + public synchronized static Set getScriptBreakPoints(String pack, boolean onlyValid) { + return getDebugHandler().getBreakPoints(pack, onlyValid); + } + + public static DebuggerHandler getDebugHandler() { + return debugHandler; + } + + public static void ensureMainFrame() { + if (mainFrame == null) { + synchronized (Main.class) { + if (mainFrame == null) { + MainFrame frame; + if (Configuration.useRibbonInterface.get()) { + frame = new MainFrameRibbon(); + } else { + frame = new MainFrameClassic(); + } + frame.getPanel().setErrorState(ErrorLogFrame.getInstance().getErrorState()); + mainFrame = frame; + } + } + } + } + + public static MainFrame getMainFrame() { + return mainFrame; + } + + public static void loadFromCache() { + if (loadFromCacheFrame == null) { + loadFromCacheFrame = new LoadFromCacheFrame(); + } + loadFromCacheFrame.setVisible(true); + } + + public static void loadFromMemory() { + if (loadFromMemoryFrame == null) { + loadFromMemoryFrame = new LoadFromMemoryFrame(mainFrame); + } + loadFromMemoryFrame.setVisible(true); + } + + public static void setVariable(long parentId, String varName, int valueType, Object value) { + getDebugHandler().setVariable(parentId, varName, valueType, value); + } + + public static void setSubLimiter(boolean value) { + if (value) { + AVM2Code.toSourceLimit = Configuration.sublimiter.get(); + } else { + AVM2Code.toSourceLimit = -1; + } + } + + public synchronized static boolean isInited() { + return inited; + } + + public synchronized static void setSessionLoaded(boolean v) { + inited = v; + } + + public static boolean isWorking() { + return working; + } + + public static void startProxy(int port) { + if (proxyFrame == null) { + proxyFrame = new ProxyFrame(mainFrame); + } + + proxyFrame.setPort(port); + addTrayIcon(); + switchProxy(); + } + + public static void showProxy() { + if (proxyFrame == null) { + proxyFrame = new ProxyFrame(mainFrame); + } + proxyFrame.setVisible(true); + proxyFrame.setState(Frame.NORMAL); + } + + public static void startWork(String name, CancellableWorker worker) { + startWork(name, -1, worker); + } + + public static void startWork(final String name, final int percent, final CancellableWorker worker) { + working = true; + View.execInEventDispatchLater(() -> { + if (mainFrame != null) { + mainFrame.getPanel().setWorkStatus(name, worker); + if (percent == -1) { + mainFrame.getPanel().hidePercent(); + } else { + mainFrame.getPanel().setPercent(percent); + } + } + if (loadingDialog != null) { + loadingDialog.setDetail(name); + loadingDialog.setPercent(percent); + } + if (CommandLineArgumentParser.isCommandLineMode()) { + System.out.println(name); + } + }); + } + + public static void stopWork() { + working = false; + View.execInEventDispatchLater(() -> { + if (mainFrame != null) { + mainFrame.getPanel().setWorkStatus("", null); + } + if (loadingDialog != null) { + loadingDialog.setDetail(""); + } + }); + } + + public static SWFList parseSWF(SWFSourceInfo sourceInfo) throws Exception { + SWFList result = new SWFList(); + + InputStream inputStream = sourceInfo.getInputStream(); + SWFBundle bundle = null; + FileInputStream fis = null; + if (inputStream == null) { + inputStream = new BufferedInputStream(fis = new FileInputStream(sourceInfo.getFile())); + bundle = sourceInfo.getBundle(false, SearchMode.ALL); + logger.log(Level.INFO, "Load file: {0}", sourceInfo.getFile()); + } else if (inputStream instanceof SeekableInputStream + || inputStream instanceof BufferedInputStream) { + try { + inputStream.reset(); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } + logger.log(Level.INFO, "Load stream: {0}", sourceInfo.getFileTitle()); + } + + Stopwatch sw = Stopwatch.startNew(); + if (bundle != null) { + result.bundle = bundle; + result.name = new File(sourceInfo.getFileTitleOrName()).getName(); + for (Entry streamEntry : bundle.getAll().entrySet()) { + InputStream stream = streamEntry.getValue(); + stream.reset(); + CancellableWorker worker = new CancellableWorker() { + @Override + public SWF doInBackground() throws Exception { + final CancellableWorker worker = this; + SWF swf = new SWF(stream, null, streamEntry.getKey(), new ProgressListener() { + @Override + public void progress(int p) { + startWork(AppStrings.translate("work.reading.swf"), p, worker); + } + }, Configuration.parallelSpeedUp.get()); + return swf; + } + }; + loadingDialog.setWroker(worker); + worker.execute(); + + try { + result.add(worker.get()); + } catch (CancellationException ex) { + logger.log(Level.WARNING, "Loading SWF {0} was cancelled.", streamEntry.getKey()); + } + } + } else { + InputStream fInputStream = inputStream; + + final String[] yesno = new String[]{AppStrings.translate("button.yes"), AppStrings.translate("button.no"), AppStrings.translate("button.yes.all"), AppStrings.translate("button.no.all")}; + + CancellableWorker worker = new CancellableWorker() { + private boolean yestoall = false; + + private boolean notoall = false; + + private SWF open(InputStream is, String file, String fileTitle) throws IOException, InterruptedException { + final CancellableWorker worker = this; + + SWF swf = new SWF(is, file, fileTitle, new ProgressListener() { + @Override + public void progress(int p) { + startWork(AppStrings.translate("work.reading.swf"), p, worker); + } + }, Configuration.parallelSpeedUp.get(), false, true, new UrlResolver() { + @Override + public SWF resolveUrl(final String url) { + int opt = -1; + if (!(yestoall || notoall)) { + opt = View.showOptionDialog(null, AppStrings.translate("message.imported.swf").replace("%url%", url), AppStrings.translate("message.warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, yesno, AppStrings.translate("button.yes")); + if (opt == 2) { + yestoall = true; + } + if (opt == 3) { + notoall = true; + } + } + + if (yestoall) { + opt = 0; // yes + } else if (notoall) { + opt = 1; // no + } + + if (opt == 1) //no + { + return null; + } + + if (url.startsWith("http://") || url.startsWith("https://")) { + try { + URL u = new URL(url); + return open(u.openStream(), null, url); //? + } catch (Exception ex) { + //ignore + } + } else { + File f = new File(new File(file).getParentFile(), url); + if (f.exists()) { + try { + return open(new FileInputStream(f), f.getAbsolutePath(), f.getName()); + } catch (Exception ex) { + //ignore + } + } + } + Reference ret = new Reference<>(null); + View.execInEventDispatch(new Runnable() { + @Override + public void run() { + + while (JOptionPane.YES_OPTION == View.showConfirmDialog(null, AppStrings.translate("message.imported.swf.manually").replace("%url%", url), AppStrings.translate("error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE)) { + + JFileChooser fc = new JFileChooser(); + fc.setCurrentDirectory(new File(Configuration.lastOpenDir.get())); + FileFilter allSupportedFilter = new FileFilter() { + private final String[] supportedExtensions = new String[]{".swf", ".gfx"}; + + @Override + public boolean accept(File f) { + String name = f.getName().toLowerCase(); + for (String ext : supportedExtensions) { + if (name.endsWith(ext)) { + return true; + } + } + return f.isDirectory(); + } + + @Override + public String getDescription() { + String exts = Helper.joinStrings(supportedExtensions, "*%s", "; "); + return AppStrings.translate("filter.supported") + " (" + exts + ")"; + } + }; + fc.setFileFilter(allSupportedFilter); + FileFilter swfFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".swf")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.swf"); + } + }; + fc.addChoosableFileFilter(swfFilter); + + FileFilter gfxFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".gfx")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.gfx"); + } + }; + fc.addChoosableFileFilter(gfxFilter); + fc.setAcceptAllFileFilterUsed(false); + JFrame f = new JFrame(); + View.setWindowIcon(f); + int returnVal = fc.showOpenDialog(f); + if (returnVal == JFileChooser.APPROVE_OPTION) { + Configuration.lastOpenDir.set(Helper.fixDialogFile(fc.getSelectedFile()).getParentFile().getAbsolutePath()); + File selFile = Helper.fixDialogFile(fc.getSelectedFile()); + try { + ret.setVal(open(new FileInputStream(selFile), selFile.getAbsolutePath(), selFile.getName())); + break; + } catch (Exception ex) { + //ignore; + } + } else { + break; + } + } + } + }); + return ret.getVal(); + } + }); + return swf; + } + + @Override + public SWF doInBackground() throws Exception { + return open(fInputStream, sourceInfo.getFile(), sourceInfo.getFileTitle()); + } + }; + if (loadingDialog != null) { + loadingDialog.setWroker(worker); + } + worker.execute(); + + try { + result.add(worker.get()); + } catch (CancellationException ex) { + logger.log(Level.WARNING, "Loading SWF {0} was cancelled.", sourceInfo.getFileTitleOrName()); + } + } + + if (fis != null) { + logger.log(Level.INFO, "File loaded in {0} seconds.", (sw.getElapsedMilliseconds() / 1000)); + fis.close(); + } else { + logger.log(Level.INFO, "Stream loaded in {0} seconds.", (sw.getElapsedMilliseconds() / 1000)); + } + + result.sourceInfo = sourceInfo; + for (SWF swf : result) { + logger.log(Level.INFO, ""); + logger.log(Level.INFO, "== File information =="); + logger.log(Level.INFO, "Size: {0}", Helper.formatFileSize(swf.fileSize)); + logger.log(Level.INFO, "Flash version: {0}", swf.version); + int width = (int) ((swf.displayRect.Xmax - swf.displayRect.Xmin) / SWF.unitDivisor); + int height = (int) ((swf.displayRect.Ymax - swf.displayRect.Ymin) / SWF.unitDivisor); + logger.log(Level.INFO, "Width: {0}", width); + logger.log(Level.INFO, "Height: {0}", height); + + swf.swfList = result; + swf.addEventListener(new EventListener() { + @Override + public void handleExportingEvent(String type, int index, int count, Object data) { + String text = AppStrings.translate("work.exporting"); + if (type != null && type.length() > 0) { + text += " " + type; + } + + startWork(text + " " + index + "/" + count + " " + data, null); + } + + @Override + public void handleExportedEvent(String type, int index, int count, Object data) { + String text = AppStrings.translate("work.exported"); + if (type != null && type.length() > 0) { + text += " " + type; + } + + startWork(text + " " + index + "/" + count + " " + data, null); + } + + @Override + public void handleEvent(String event, Object data) { + if (event.equals("exporting") || event.equals("exported")) { + throw new Error("Event is not supported by this handler."); + } + if (event.equals("getVariables")) { + startWork(AppStrings.translate("work.gettingvariables") + "..." + (String) data, null); + } + if (event.equals("deobfuscate")) { + startWork(AppStrings.translate("work.deobfuscating") + "..." + (String) data, null); + } + if (event.equals("rename")) { + startWork(AppStrings.translate("work.renaming") + "..." + (String) data, null); + } + } + }); + } + + return result; + } + + public static void saveFile(SWF swf, String outfile) throws IOException { + saveFile(swf, outfile, SaveFileMode.SAVE, null); + } + + public static void saveFile(SWF swf, String outfile, SaveFileMode mode, ExeExportMode exeExportMode) throws IOException { + if (mode == SaveFileMode.SAVEAS && !swf.swfList.isBundle()) { + swf.setFile(outfile); + swf.swfList.sourceInfo.setFile(outfile); + } + File outfileF = new File(outfile); + File tmpFile = new File(outfile + ".tmp"); + try (FileOutputStream fos = new FileOutputStream(tmpFile); + BufferedOutputStream bos = new BufferedOutputStream(fos)) { + if (mode == SaveFileMode.EXE) { + switch (exeExportMode) { + case WRAPPER: + InputStream exeStream = View.class.getClassLoader().getResourceAsStream("com/jpexs/helpers/resource/Swf2Exe.bin"); + Helper.copyStream(exeStream, bos); + int width = swf.displayRect.Xmax - swf.displayRect.Xmin; + int height = swf.displayRect.Ymax - swf.displayRect.Ymin; + bos.write(width & 0xff); + bos.write((width >> 8) & 0xff); + bos.write((width >> 16) & 0xff); + bos.write((width >> 24) & 0xff); + bos.write(height & 0xff); + bos.write((height >> 8) & 0xff); + bos.write((height >> 16) & 0xff); + bos.write((height >> 24) & 0xff); + bos.write(Configuration.saveAsExeScaleMode.get()); + break; + case PROJECTOR_WIN: + case PROJECTOR_MAC: + case PROJECTOR_LINUX: + File projectorFile = Configuration.getProjectorFile(exeExportMode); + if (projectorFile == null) { + String message = "Projector not found, please place it to " + Configuration.getProjectorPath(); + logger.log(Level.SEVERE, message); + throw new IOException(message); + } + Helper.copyStream(new FileInputStream(projectorFile), bos); + bos.flush(); + break; + } + } + + long pos = fos.getChannel().position(); + swf.saveTo(bos); + + if (mode == SaveFileMode.EXE) { + switch (exeExportMode) { + case PROJECTOR_WIN: + case PROJECTOR_MAC: + case PROJECTOR_LINUX: + bos.flush(); + int swfSize = (int) (fos.getChannel().position() - pos); + + // write magic number + bos.write(0x56); + bos.write(0x34); + bos.write(0x12); + bos.write(0xfa); + + bos.write(swfSize & 0xff); + bos.write((swfSize >> 8) & 0xff); + bos.write((swfSize >> 16) & 0xff); + bos.write((swfSize >> 24) & 0xff); + } + } + } + if (tmpFile.exists()) { + if (tmpFile.length() > 0) { + outfileF.delete(); + if (!tmpFile.renameTo(outfileF)) { + tmpFile.delete(); + throw new IOException("Cannot access " + outfile); + } + } else { + throw new IOException("Output is empty"); + } + } else { + throw new IOException("Output not found"); + } + } + + private static class OpenFileWorker extends SwingWorker { + + private final SWFSourceInfo[] sourceInfos; + + private final Runnable executeAfterOpen; + + private final int[] reloadIndices; + + public OpenFileWorker(SWFSourceInfo sourceInfo) { + this(sourceInfo, -1); + } + + public OpenFileWorker(SWFSourceInfo sourceInfo, int reloadIndex) { + this(sourceInfo, null, reloadIndex); + } + + public OpenFileWorker(SWFSourceInfo sourceInfo, Runnable executeAfterOpen) { + this(sourceInfo, executeAfterOpen, -1); + } + + public OpenFileWorker(SWFSourceInfo sourceInfo, Runnable executeAfterOpen, int reloadIndex) { + this.sourceInfos = new SWFSourceInfo[]{sourceInfo}; + this.executeAfterOpen = executeAfterOpen; + this.reloadIndices = new int[]{reloadIndex}; + } + + public OpenFileWorker(SWFSourceInfo[] sourceInfos) { + this(sourceInfos, null, null); + } + + public OpenFileWorker(SWFSourceInfo[] sourceInfos, Runnable executeAfterOpen) { + this(sourceInfos, executeAfterOpen, null); + } + + public OpenFileWorker(SWFSourceInfo[] sourceInfos, Runnable executeAfterOpen, int[] reloadIndices) { + this.sourceInfos = sourceInfos; + this.executeAfterOpen = executeAfterOpen; + int[] indices = new int[sourceInfos.length]; + for (int i = 0; i < indices.length; i++) { + indices[i] = -1; + } + this.reloadIndices = reloadIndices == null ? indices : reloadIndices; + } + + @Override + protected Object doInBackground() throws Exception { + boolean first = true; + SWF firstSWF = null; + for (int index = 0; index < sourceInfos.length; index++) { + SWFSourceInfo sourceInfo = sourceInfos[index]; + SWFList swfs = null; + try { + Main.startWork(AppStrings.translate("work.reading.swf") + "...", null); + try { + swfs = parseSWF(sourceInfo); + } catch (ExecutionException ex) { + Throwable cause = ex.getCause(); + if (cause instanceof SwfOpenException) { + throw (SwfOpenException) cause; + } + + throw ex; + } + } catch (OutOfMemoryError ex) { + logger.log(Level.SEVERE, null, ex); + View.showMessageDialog(null, "Cannot load SWF file. Out of memory."); + continue; + } catch (SwfOpenException ex) { + logger.log(Level.SEVERE, null, ex); + View.showMessageDialog(null, ex.getMessage()); + continue; + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + View.showMessageDialog(null, "Cannot load SWF file."); + continue; + } + + final SWFList swfs1 = swfs; + final boolean first1 = first; + first = false; + if (firstSWF == null && swfs1.size() > 0) { + firstSWF = swfs1.get(0); + } + + final int findex = index; + try { + View.execInEventDispatch(() -> { + Main.startWork(AppStrings.translate("work.creatingwindow") + "...", null); + ensureMainFrame(); + if (reloadIndices[findex] > -1) { + mainFrame.getPanel().loadSwfAtPos(swfs1, reloadIndices[findex]); + } else { + mainFrame.getPanel().load(swfs1, first1); + } + }); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + } + + loadingDialog.setVisible(false); + shouldCloseWhenClosingLoadingDialog = false; + + final SWF fswf = firstSWF; + View.execInEventDispatch(() -> { + if (mainFrame != null) { + mainFrame.setVisible(true); + } + + Main.stopWork(); + + if (mainFrame != null && Configuration.gotoMainClassOnStartup.get()) { + mainFrame.getPanel().gotoDocumentClass(fswf); + } + + if (mainFrame != null && fswf != null) { + SwfSpecificConfiguration swfConf = Configuration.getSwfSpecificConfiguration(fswf.getShortFileName()); + if (swfConf != null) { + String pathStr = swfConf.lastSelectedPath; + mainFrame.getPanel().tagTree.setSelectionPathString(pathStr); + } + } + + if (executeAfterOpen != null) { + executeAfterOpen.run(); + } + }); + + return true; + } + } + + public static boolean reloadSWFs() { + CancellableWorker.cancelBackgroundThreads(); + if (Main.sourceInfos.isEmpty()) { + Helper.freeMem(); + showModeFrame(); + return true; + } else { + SWFSourceInfo[] sourceInfosCopy = new SWFSourceInfo[sourceInfos.size()]; + sourceInfos.toArray(sourceInfosCopy); + sourceInfos.clear(); + openFile(sourceInfosCopy); + return true; + } + } + + public static void reloadApp() { + if (debugDialog != null) { + debugDialog.setVisible(false); + debugDialog.dispose(); + debugDialog = null; + } + if (loadingDialog != null) { + synchronized (Main.class) { + if (loadingDialog != null) { + loadingDialog.setVisible(false); + loadingDialog.dispose(); + loadingDialog = null; + } + } + } + if (proxyFrame != null) { + proxyFrame.setVisible(false); + proxyFrame.dispose(); + proxyFrame = null; + } + if (loadFromMemoryFrame != null) { + loadFromMemoryFrame.setVisible(false); + loadFromMemoryFrame.dispose(); + loadFromMemoryFrame = null; + } + if (loadFromCacheFrame != null) { + loadFromCacheFrame.setVisible(false); + loadFromCacheFrame.dispose(); + loadFromCacheFrame = null; + } + if (mainFrame != null) { + mainFrame.setVisible(false); + mainFrame.getPanel().closeAll(false); + mainFrame.dispose(); + mainFrame = null; + } + FontTag.reload(); + Cache.clearAll(); + initGui(); + reloadSWFs(); + } + + public static OpenFileResult openFile(String swfFile, String fileTitle) { + return openFile(swfFile, fileTitle, null); + } + + public static OpenFileResult openFile(String swfFile, String fileTitle, Runnable executeAfterOpen) { + try { + File file = new File(swfFile); + if (!file.exists()) { + View.showMessageDialog(null, AppStrings.translate("open.error.fileNotFound"), AppStrings.translate("open.error"), JOptionPane.ERROR_MESSAGE); + return OpenFileResult.NOT_FOUND; + } + swfFile = file.getCanonicalPath(); + SWFSourceInfo sourceInfo = new SWFSourceInfo(null, swfFile, fileTitle); + OpenFileResult openResult = openFile(sourceInfo); + return openResult; + } catch (IOException ex) { + View.showMessageDialog(null, AppStrings.translate("open.error.cannotOpen"), AppStrings.translate("open.error"), JOptionPane.ERROR_MESSAGE); + return OpenFileResult.ERROR; + } + } + + public static OpenFileResult openFile(SWFSourceInfo sourceInfo) { + return openFile(new SWFSourceInfo[]{sourceInfo}); + } + + public static OpenFileResult openFile(SWFSourceInfo sourceInfo, Runnable executeAfterOpen) { + return openFile(new SWFSourceInfo[]{sourceInfo}, executeAfterOpen); + } + + public static OpenFileResult openFile(SWFSourceInfo sourceInfo, Runnable executeAfterOpen, int reloadIndex) { + return openFile(new SWFSourceInfo[]{sourceInfo}, executeAfterOpen, new int[]{reloadIndex}); + } + + public static OpenFileResult openFile(SWFSourceInfo[] newSourceInfos) { + return openFile(newSourceInfos, null); + } + + public static OpenFileResult openFile(SWFSourceInfo[] newSourceInfos, Runnable executeAfterOpen) { + return openFile(newSourceInfos, executeAfterOpen, null); + } + + public static OpenFileResult openFile(SWFSourceInfo[] newSourceInfos, Runnable executeAfterOpen, int[] reloadIndices) { + if (mainFrame != null && !Configuration.openMultipleFiles.get()) { + sourceInfos.clear(); + mainFrame.getPanel().closeAll(false); + mainFrame.setVisible(false); + Helper.freeMem(); + reloadIndices = null; + } + + loadingDialog.setVisible(true); + + for (int i = 0; i < sourceInfos.size(); i++) { + SWFSourceInfo si = newSourceInfos[i]; + String fileName = si.getFile(); + if (fileName != null) { + Configuration.addRecentFile(fileName); + } + } + + OpenFileWorker wrk = new OpenFileWorker(newSourceInfos, executeAfterOpen, reloadIndices); + wrk.execute(); + if (reloadIndices == null) { + sourceInfos.addAll(Arrays.asList(newSourceInfos)); + } else { + for (int i = 0; i < reloadIndices.length; i++) { + sourceInfos.set(reloadIndices[i], newSourceInfos[i]); + } + } + return OpenFileResult.OK; + } + + public static void closeFile(SWFList swf) { + sourceInfos.remove(swf.sourceInfo); + mainFrame.getPanel().close(swf); + } + + public static void reloadFile(SWFList swf) { + //mainFrame.getPanel().close(swf); + openFile(swf.sourceInfo, null, sourceInfos.indexOf(swf.sourceInfo)); + } + + public static boolean closeAll() { + boolean closeResult = mainFrame.getPanel().closeAll(true); + if (closeResult) { + sourceInfos.clear(); + } + + return closeResult; + } + + public static boolean saveFileDialog(SWF swf, final SaveFileMode mode) { + JFileChooser fc = new JFileChooser(); + fc.setCurrentDirectory(new File(Configuration.lastSaveDir.get())); + String ext = ".swf"; + switch (mode) { + case SAVE: + case SAVEAS: + if (swf.getFile() != null) { + ext = Path.getExtension(swf.getFile()); + } + break; + case EXE: + ext = ".exe"; + break; + } + + FileFilter swfFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".swf")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.swf"); + } + }; + + FileFilter gfxFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".gfx")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.gfx"); + } + }; + + ExeExportMode exeExportMode = null; + if (mode == SaveFileMode.EXE) { + exeExportMode = Configuration.exeExportMode.get(); + if (exeExportMode == null) { + exeExportMode = ExeExportMode.WRAPPER; + } + String filterDescription = null; + switch (exeExportMode) { + case WRAPPER: + case PROJECTOR_WIN: + ext = ".exe"; + filterDescription = "filter.exe"; + break; + case PROJECTOR_MAC: + ext = ".dmg"; + filterDescription = "filter.dmg"; + break; + case PROJECTOR_LINUX: + // linux projector is compressed with tar.gz + // todo: decompress + ext = ""; + filterDescription = "filter.linuxExe"; + break; + } + + String fext = ext; + String ffilterDescription = filterDescription; + FileFilter exeFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(fext)) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate(ffilterDescription); + } + }; + fc.setFileFilter(exeFilter); + } else if (swf.gfx) { + fc.addChoosableFileFilter(swfFilter); + fc.setFileFilter(gfxFilter); + } else { + fc.setFileFilter(swfFilter); + fc.addChoosableFileFilter(gfxFilter); + } + final String extension = ext; + fc.setAcceptAllFileFilterUsed(false); + JFrame f = new JFrame(); + View.setWindowIcon(f); + if (fc.showSaveDialog(f) == JFileChooser.APPROVE_OPTION) { + File file = Helper.fixDialogFile(fc.getSelectedFile()); + FileFilter selFilter = fc.getFileFilter(); + try { + String fileName = file.getAbsolutePath(); + if (selFilter == swfFilter) { + if (!fileName.toLowerCase().endsWith(extension)) { + fileName += extension; + } + swf.gfx = false; + } + if (selFilter == gfxFilter) { + if (!fileName.toLowerCase().endsWith(".gfx")) { + fileName += ".gfx"; + } + swf.gfx = true; + } + Main.saveFile(swf, fileName, mode, exeExportMode); + Configuration.lastSaveDir.set(file.getParentFile().getAbsolutePath()); + return true; + } catch (IOException ex) { + View.showMessageDialog(null, AppStrings.translate("error.file.write")); + } + } + return false; + } + + public static boolean openFileDialog() { + JFileChooser fc = new JFileChooser(); + if (Configuration.openMultipleFiles.get()) { + fc.setMultiSelectionEnabled(true); + } + fc.setCurrentDirectory(new File(Configuration.lastOpenDir.get())); + FileFilter allSupportedFilter = new FileFilter() { + private final String[] supportedExtensions = new String[]{".swf", ".gfx", ".swc", ".zip"}; + + @Override + public boolean accept(File f) { + String name = f.getName().toLowerCase(); + for (String ext : supportedExtensions) { + if (name.endsWith(ext)) { + return true; + } + } + return f.isDirectory(); + } + + @Override + public String getDescription() { + String exts = Helper.joinStrings(supportedExtensions, "*%s", "; "); + return AppStrings.translate("filter.supported") + " (" + exts + ")"; + } + }; + fc.setFileFilter(allSupportedFilter); + FileFilter swfFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".swf")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.swf"); + } + }; + fc.addChoosableFileFilter(swfFilter); + + FileFilter swcFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".swc")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.swc"); + } + }; + fc.addChoosableFileFilter(swcFilter); + + FileFilter gfxFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".gfx")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.gfx"); + } + }; + fc.addChoosableFileFilter(gfxFilter); + + FileFilter zipFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return (f.getName().toLowerCase().endsWith(".zip")) || (f.isDirectory()); + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.zip"); + } + }; + fc.addChoosableFileFilter(zipFilter); + + FileFilter binaryFilter = new FileFilter() { + @Override + public boolean accept(File f) { + return true; + } + + @Override + public String getDescription() { + return AppStrings.translate("filter.binary"); + } + }; + fc.addChoosableFileFilter(binaryFilter); + + fc.setAcceptAllFileFilterUsed(false); + JFrame f = new JFrame(); + View.setWindowIcon(f); + int returnVal = fc.showOpenDialog(f); + if (returnVal == JFileChooser.APPROVE_OPTION) { + Configuration.lastOpenDir.set(Helper.fixDialogFile(fc.getSelectedFile()).getParentFile().getAbsolutePath()); + File[] selFiles = fc.getSelectedFiles(); + for (File file : selFiles) { + File selfile = Helper.fixDialogFile(file); + Main.openFile(selfile.getAbsolutePath(), null); + } + return true; + } else { + return false; + } + } + + public static void displayErrorFrame() { + ErrorLogFrame.getInstance().setVisible(true); + } + + private static String md5(byte data[]) { + try { + java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); + byte[] array = md.digest(data); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < array.length; ++i) { + sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); + } + return sb.toString(); + } catch (java.security.NoSuchAlgorithmException e) { + } + return null; + } + + private static void initGui() { + if (GraphicsEnvironment.isHeadless()) { + System.err.println("Error: Your system does not support Graphic User Interface"); + exit(); + } + + System.setProperty("sun.java2d.d3d", "false"); + System.setProperty("sun.java2d.noddraw", "true"); + + if (Configuration.hwAcceleratedGraphics.get()) { + System.setProperty("sun.java2d.opengl", Configuration._debugMode.get() ? "True" : "true"); + } else { + System.setProperty("sun.java2d.opengl", "false"); + } + + initUiLang(); + + if (Configuration.useRibbonInterface.get()) { + View.setLookAndFeel(); + } else { + try { + UIManager.put(SubstanceLookAndFeel.COLORIZATION_FACTOR, null); + UIManager.put("Tree.expandedIcon", null); + UIManager.put("Tree.collapsedIcon", null); + UIManager.put("ColorChooserUI", null); + UIManager.put("ColorChooser.swatchesRecentSwatchSize", null); + UIManager.put("ColorChooser.swatchesSwatchSize", null); + UIManager.put("RibbonApplicationMenuPopupPanelUI", null); + UIManager.put("RibbonApplicationMenuButtonUI", null); + UIManager.put("ProgressBarUI", null); + UIManager.put("TextField.background", null); + UIManager.put("FormattedTextField.background", null); + UIManager.put("CommandButtonUI", null); + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + + View.execInEventDispatch(() -> { + ErrorLogFrame.createNewInstance(); + + autoCheckForUpdates(); + offerAssociation(); + loadingDialog = new LoadingDialog(); + + DebuggerTools.initDebugger().addMessageListener(new DebugListener() { + @Override + public void onMessage(String clientId, String msg) { + } + + @Override + public void onLoaderURL(String clientId, String url) { + } + + @Override + public void onLoaderBytes(String clientId, byte[] data) { + String hash = md5(data); + for (SWFList sl : Main.getMainFrame().getPanel().getSwfs()) { + for (int s = 0; s < sl.size(); s++) { + String t = sl.get(s).getFileTitle(); + if (t == null) { + t = ""; + } + if (t.endsWith(":" + hash)) { //this one is already opened + return; + } + } + } + SWF swf = Main.getMainFrame().getPanel().getCurrentSwf(); + + String title = swf == null ? "?" : swf.getFileTitle(); + title = title + ":" + hash; + String tfile; + try { + tfile = tempFile(title); + Helper.writeFile(tfile, data); + openFile(new SWFSourceInfo(null, tfile, title)); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Cannot create tempfile"); + } + } + + @Override + public void onFinish(String clientId) { + } + }); + + try { + flashDebugger = new Debugger(); + debugHandler = new DebuggerHandler(); + debugHandler.addBreakListener(new DebuggerHandler.BreakListener() { + @Override + public void doContinue() { + mainFrame.getPanel().clearDebuggerColors(); + } + + @Override + public void breakAt(String scriptName, int line, final int classIndex, final int traitIndex, final int methodIndex) { + View.execInEventDispatch(new Runnable() { + @Override + public void run() { + mainFrame.getPanel().gotoScriptLine(getMainFrame().getPanel().getCurrentSwf(), scriptName, line, classIndex, traitIndex, methodIndex); + } + }); + } + }); + debugHandler.addConnectionListener(new DebuggerHandler.ConnectionListener() { + @Override + public void connected() { + Main.mainFrame.getMenu().updateComponents(); + } + + @Override + public void disconnected() { + if (Main.mainFrame != null && Main.mainFrame.getPanel() != null) { + Main.mainFrame.getPanel().refreshBreakPoints(); + } + } + }); + flashDebugger.addConnectionListener(debugHandler); + } catch (IOException ex) { + logger.log(Level.SEVERE, "eeex", ex); + } + }); + } + + public static void startDebugger() { + flashDebugger.startDebugger(); + } + + public static void stopDebugger() { + flashDebugger.stopDebugger(); + } + + public static void showModeFrame() { + ensureMainFrame(); + mainFrame.setVisible(true); + } + + private static void offerAssociation() { + boolean offered = Configuration.offeredAssociation.get(); + if (!offered) { + if (Platform.isWindows()) { + if ((!ContextMenuTools.isAddedToContextMenu()) && View.showConfirmDialog(null, "Do you want to add FFDec to context menu of SWF files?\n(Can be changed later from main menu)", "Context menu", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { + ContextMenuTools.addToContextMenu(true, false); + } + } + + Configuration.offeredAssociation.set(true); + } + } + + public static void initUiLang() { + if (GraphicsEnvironment.isHeadless()) { //No GUI in OS + return; + } + try { + Class cl = Class.forName("org.pushingpixels.substance.api.SubstanceLookAndFeel"); + Field field = cl.getDeclaredField("LABEL_BUNDLE"); + field.setAccessible(true); + field.set(null, null); + } catch (Throwable ex) { + logger.log(Level.SEVERE, null, ex); + } + + UIManager.put("OptionPane.okButtonText", AppStrings.translate("button.ok")); + UIManager.put("OptionPane.yesButtonText", AppStrings.translate("button.yes")); + UIManager.put("OptionPane.noButtonText", AppStrings.translate("button.no")); + UIManager.put("OptionPane.cancelButtonText", AppStrings.translate("button.cancel")); + UIManager.put("OptionPane.messageDialogTitle", AppStrings.translate("dialog.message.title")); + UIManager.put("OptionPane.titleText", AppStrings.translate("dialog.select.title")); + + UIManager.put("FileChooser.acceptAllFileFilterText", AppStrings.translate("FileChooser.acceptAllFileFilterText")); + UIManager.put("FileChooser.lookInLabelText", AppStrings.translate("FileChooser.lookInLabelText")); + UIManager.put("FileChooser.cancelButtonText", AppStrings.translate("button.cancel")); + UIManager.put("FileChooser.cancelButtonToolTipText", AppStrings.translate("button.cancel")); + UIManager.put("FileChooser.openButtonText", AppStrings.translate("FileChooser.openButtonText")); + UIManager.put("FileChooser.openButtonToolTipText", AppStrings.translate("FileChooser.openButtonToolTipText")); + UIManager.put("FileChooser.filesOfTypeLabelText", AppStrings.translate("FileChooser.filesOfTypeLabelText")); + UIManager.put("FileChooser.fileNameLabelText", AppStrings.translate("FileChooser.fileNameLabelText")); + UIManager.put("FileChooser.listViewButtonToolTipText", AppStrings.translate("FileChooser.listViewButtonToolTipText")); + UIManager.put("FileChooser.listViewButtonAccessibleName", AppStrings.translate("FileChooser.listViewButtonAccessibleName")); + UIManager.put("FileChooser.detailsViewButtonToolTipText", AppStrings.translate("FileChooser.detailsViewButtonToolTipText")); + UIManager.put("FileChooser.detailsViewButtonAccessibleName", AppStrings.translate("FileChooser.detailsViewButtonAccessibleName")); + UIManager.put("FileChooser.upFolderToolTipText", AppStrings.translate("FileChooser.upFolderToolTipText")); + UIManager.put("FileChooser.upFolderAccessibleName", AppStrings.translate("FileChooser.upFolderAccessibleName")); + UIManager.put("FileChooser.homeFolderToolTipText", AppStrings.translate("FileChooser.homeFolderToolTipText")); + UIManager.put("FileChooser.homeFolderAccessibleName", AppStrings.translate("FileChooser.homeFolderAccessibleName")); + UIManager.put("FileChooser.fileNameHeaderText", AppStrings.translate("FileChooser.fileNameHeaderText")); + UIManager.put("FileChooser.fileSizeHeaderText", AppStrings.translate("FileChooser.fileSizeHeaderText")); + UIManager.put("FileChooser.fileTypeHeaderText", AppStrings.translate("FileChooser.fileTypeHeaderText")); + UIManager.put("FileChooser.fileDateHeaderText", AppStrings.translate("FileChooser.fileDateHeaderText")); + UIManager.put("FileChooser.fileAttrHeaderText", AppStrings.translate("FileChooser.fileAttrHeaderText")); + UIManager.put("FileChooser.openDialogTitleText", AppStrings.translate("FileChooser.openDialogTitleText")); + UIManager.put("FileChooser.directoryDescriptionText", AppStrings.translate("FileChooser.directoryDescriptionText")); + UIManager.put("FileChooser.directoryOpenButtonText", AppStrings.translate("FileChooser.directoryOpenButtonText")); + UIManager.put("FileChooser.directoryOpenButtonToolTipText", AppStrings.translate("FileChooser.directoryOpenButtonToolTipText")); + UIManager.put("FileChooser.fileDescriptionText", AppStrings.translate("FileChooser.fileDescriptionText")); + UIManager.put("FileChooser.fileNameLabelText", AppStrings.translate("FileChooser.fileNameLabelText")); + UIManager.put("FileChooser.helpButtonText", AppStrings.translate("FileChooser.helpButtonText")); + UIManager.put("FileChooser.helpButtonToolTipText", AppStrings.translate("FileChooser.helpButtonToolTipText")); + UIManager.put("FileChooser.newFolderAccessibleName", AppStrings.translate("FileChooser.newFolderAccessibleName")); + UIManager.put("FileChooser.newFolderErrorText", AppStrings.translate("FileChooser.newFolderErrorText")); + UIManager.put("FileChooser.newFolderToolTipText", AppStrings.translate("FileChooser.newFolderToolTipText")); + UIManager.put("FileChooser.other.newFolder", AppStrings.translate("FileChooser.other.newFolder")); + UIManager.put("FileChooser.other.newFolder.subsequent", AppStrings.translate("FileChooser.other.newFolder.subsequent")); + UIManager.put("FileChooser.win32.newFolder", AppStrings.translate("FileChooser.win32.newFolder")); + UIManager.put("FileChooser.win32.newFolder.subsequent", AppStrings.translate("FileChooser.win32.newFolder.subsequent")); + UIManager.put("FileChooser.saveButtonText", AppStrings.translate("FileChooser.saveButtonText")); + UIManager.put("FileChooser.saveButtonToolTipText", AppStrings.translate("FileChooser.saveButtonToolTipText")); + UIManager.put("FileChooser.saveDialogTitleText", AppStrings.translate("FileChooser.saveDialogTitleText")); + UIManager.put("FileChooser.saveInLabelText", AppStrings.translate("FileChooser.saveInLabelText")); + UIManager.put("FileChooser.updateButtonText", AppStrings.translate("FileChooser.updateButtonText")); + UIManager.put("FileChooser.updateButtonToolTipText", AppStrings.translate("FileChooser.updateButtonToolTipText")); + + UIManager.put("FileChooser.detailsViewActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.detailsViewActionLabel.textAndMnemonic")); + UIManager.put("FileChooser.detailsViewButtonToolTip.textAndMnemonic", AppStrings.translate("FileChooser.detailsViewButtonToolTip.textAndMnemonic")); + UIManager.put("FileChooser.fileAttrHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileAttrHeader.textAndMnemonic")); + UIManager.put("FileChooser.fileDateHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileDateHeader.textAndMnemonic")); + UIManager.put("FileChooser.fileNameHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileNameHeader.textAndMnemonic")); + UIManager.put("FileChooser.fileNameLabel.textAndMnemonic", AppStrings.translate("FileChooser.fileNameLabel.textAndMnemonic")); + UIManager.put("FileChooser.fileSizeHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileSizeHeader.textAndMnemonic")); + UIManager.put("FileChooser.fileTypeHeader.textAndMnemonic", AppStrings.translate("FileChooser.fileTypeHeader.textAndMnemonic")); + UIManager.put("FileChooser.filesOfTypeLabel.textAndMnemonic", AppStrings.translate("FileChooser.filesOfTypeLabel.textAndMnemonic")); + UIManager.put("FileChooser.folderNameLabel.textAndMnemonic", AppStrings.translate("FileChooser.folderNameLabel.textAndMnemonic")); + UIManager.put("FileChooser.homeFolderToolTip.textAndMnemonic", AppStrings.translate("FileChooser.homeFolderToolTip.textAndMnemonic")); + UIManager.put("FileChooser.listViewActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.listViewActionLabel.textAndMnemonic")); + UIManager.put("FileChooser.listViewButtonToolTip.textAndMnemonic", AppStrings.translate("FileChooser.listViewButtonToolTip.textAndMnemonic")); + UIManager.put("FileChooser.lookInLabel.textAndMnemonic", AppStrings.translate("FileChooser.lookInLabel.textAndMnemonic")); + UIManager.put("FileChooser.newFolderActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.newFolderActionLabel.textAndMnemonic")); + UIManager.put("FileChooser.newFolderToolTip.textAndMnemonic", AppStrings.translate("FileChooser.newFolderToolTip.textAndMnemonic")); + UIManager.put("FileChooser.refreshActionLabel.textAndMnemonic", AppStrings.translate("FileChooser.refreshActionLabel.textAndMnemonic")); + UIManager.put("FileChooser.saveInLabel.textAndMnemonic", AppStrings.translate("FileChooser.saveInLabel.textAndMnemonic")); + UIManager.put("FileChooser.upFolderToolTip.textAndMnemonic", AppStrings.translate("FileChooser.upFolderToolTip.textAndMnemonic")); + UIManager.put("FileChooser.viewMenuButtonAccessibleName", AppStrings.translate("FileChooser.viewMenuButtonAccessibleName")); + UIManager.put("FileChooser.viewMenuButtonToolTipText", AppStrings.translate("FileChooser.viewMenuButtonToolTipText")); + UIManager.put("FileChooser.viewMenuLabel.textAndMnemonic", AppStrings.translate("FileChooser.viewMenuLabel.textAndMnemonic")); + UIManager.put("FileChooser.newFolderActionLabelText", AppStrings.translate("FileChooser.newFolderActionLabelText")); + UIManager.put("FileChooser.listViewActionLabelText", AppStrings.translate("FileChooser.listViewActionLabelText")); + UIManager.put("FileChooser.detailsViewActionLabelText", AppStrings.translate("FileChooser.detailsViewActionLabelText")); + UIManager.put("FileChooser.refreshActionLabelText", AppStrings.translate("FileChooser.refreshActionLabelText")); + UIManager.put("FileChooser.sortMenuLabelText", AppStrings.translate("FileChooser.sortMenuLabelText")); + UIManager.put("FileChooser.viewMenuLabelText", AppStrings.translate("FileChooser.viewMenuLabelText")); + UIManager.put("FileChooser.fileSizeKiloBytes", AppStrings.translate("FileChooser.fileSizeKiloBytes")); + UIManager.put("FileChooser.fileSizeMegaBytes", AppStrings.translate("FileChooser.fileSizeMegaBytes")); + UIManager.put("FileChooser.fileSizeGigaBytes", AppStrings.translate("FileChooser.fileSizeGigaBytes")); + UIManager.put("FileChooser.folderNameLabelText", AppStrings.translate("FileChooser.folderNameLabelText")); + + UIManager.put("ColorChooser.okText", AppStrings.translate("ColorChooser.okText")); + UIManager.put("ColorChooser.cancelText", AppStrings.translate("ColorChooser.cancelText")); + UIManager.put("ColorChooser.resetText", AppStrings.translate("ColorChooser.resetText")); + UIManager.put("ColorChooser.previewText", AppStrings.translate("ColorChooser.previewText")); + UIManager.put("ColorChooser.swatchesNameText", AppStrings.translate("ColorChooser.swatchesNameText")); + UIManager.put("ColorChooser.swatchesRecentText", AppStrings.translate("ColorChooser.swatchesRecentText")); + UIManager.put("ColorChooser.sampleText", AppStrings.translate("ColorChooser.sampleText")); + + } + + public static void initLang() { + if (!Configuration.locale.hasValue()) { + if (Platform.isWindows()) { + //Load from Installer + String uninstKey = "{E618D276-6596-41F4-8A98-447D442A77DB}_is1"; + uninstKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + uninstKey; + try { + if (Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, uninstKey)) { + if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, uninstKey, "NSIS: Language")) { + String installedLoc = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, uninstKey, "NSIS: Language"); + int lcid = Integer.parseInt(installedLoc); + char[] buf = new char[9]; + int cnt = Kernel32.INSTANCE.GetLocaleInfo(lcid, Kernel32.LOCALE_SISO639LANGNAME, buf, 9); + String langCode = new String(buf, 0, cnt).trim().toLowerCase(); + + cnt = Kernel32.INSTANCE.GetLocaleInfo(lcid, Kernel32.LOCALE_SISO3166CTRYNAME, buf, 9); + String countryCode = new String(buf, 0, cnt).trim().toLowerCase(); + + List langs = Arrays.asList(SelectLanguageDialog.getAvailableLanguages()); + for (int i = 0; i < langs.size(); i++) { + langs.set(i, langs.get(i).toLowerCase()); + } + + String selectedLang = null; + + if (langs.contains(langCode + "-" + countryCode)) { + selectedLang = SelectLanguageDialog.getAvailableLanguages()[langs.indexOf(langCode + "-" + countryCode)]; + } else if (langs.contains(langCode)) { + selectedLang = SelectLanguageDialog.getAvailableLanguages()[langs.indexOf(langCode)]; + } + if (selectedLang != null) { + Configuration.locale.set(selectedLang); + } + } + } + } catch (Exception ex) { + //ignore + } + } + } + Locale.setDefault(Locale.forLanguageTag(Configuration.locale.get())); + AppStrings.updateLanguage(); + + Helper.decompilationErrorAdd = AppStrings.translate(Configuration.autoDeobfuscate.get() ? "deobfuscation.comment.failed" : "deobfuscation.comment.tryenable"); + } + + /** + * Clear old FFDec/JavactiveX temp files + */ + private static void clearTemp() { + String tempDirPath = System.getProperty("java.io.tmpdir"); + if (tempDirPath == null) { + return; + } + File tempDir = new File(tempDirPath); + if (!tempDir.exists()) { + return; + } + File[] delFiles = tempDir.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.matches("ffdec_cache.*\\.tmp") || name.matches("javactivex_.*\\.exe") || name.matches("temp[0-9]+\\.swf") || name.matches("ffdec_view_.*\\.swf"); + } + }); + + if (delFiles != null) { + for (File f : delFiles) { + try { + f.delete(); + } catch (Exception ex) { + //ignore + } + } + } + } + + /** + * @param args the command line arguments + * @throws IOException On error + */ + public static void main(String[] args) throws IOException { + setSessionLoaded(false); + clearTemp(); + + try { + SWFDecompilerPlugin.loadPlugins(); + } catch (Throwable ex) { + logger.log(Level.SEVERE, "Failed to load plugins", ex); + } + + AppStrings.setResourceClass(MainFrame.class); + initLogging(Configuration._debugMode.get()); + + initLang(); + + if (Configuration.cacheOnDisk.get()) { + Cache.setStorageType(Cache.STORAGE_FILES); + } else { + Cache.setStorageType(Cache.STORAGE_MEMORY); + } + + if (args.length == 0) { + initGui(); + checkLibraryVersion(); + View.execInEventDispatch(() -> { + if (Configuration.allowOnlyOneInstance.get() && FirstInstance.focus()) { //Try to focus first instance + Main.exit(); + } else { + showModeFrame(); + reloadLastSession(); + } + }); + } else { + checkLibraryVersion(); + setSessionLoaded(true); + String[] filesToOpen = CommandLineArgumentParser.parseArguments(args); + if (filesToOpen != null && filesToOpen.length > 0) { + View.execInEventDispatch(() -> { + initGui(); + shouldCloseWhenClosingLoadingDialog = true; + if (Configuration.allowOnlyOneInstance.get() && FirstInstance.openFiles(Arrays.asList(filesToOpen))) { //Try to open in first instance + Main.exit(); + } else { + for (String fileToOpen : filesToOpen) { + openFile(fileToOpen, null); + } + } + }); + } + } + } + + private static void checkLibraryVersion() { + if (!ApplicationInfo.version.equals("unknown") && !ApplicationInfo.libraryVersion.equals("unknown") + && !Objects.equals(ApplicationInfo.version, ApplicationInfo.libraryVersion)) { + logger.log(Level.WARNING, "Application version is different from library version. FFDec may not work properly."); + } + } + + private static void reloadLastSession() { + boolean openingFiles = false; + if (Configuration.saveSessionOnExit.get()) { + String lastSession = Configuration.lastSessionFiles.get(); + if (lastSession != null && lastSession.length() > 0) { + String[] filesToOpen = lastSession.split(File.pathSeparator, -1); + List exfiles = new ArrayList<>(); + List extitles = new ArrayList<>(); + String lastSessionTitles = Configuration.lastSessionFileTitles.get(); + String[] fileTitles = new String[0]; + if (lastSessionTitles != null && !lastSessionTitles.isEmpty()) { + fileTitles = lastSessionTitles.split(File.pathSeparator, -1); + } + for (int i = 0; i < filesToOpen.length; i++) { + if (new File(filesToOpen[i]).exists()) { + exfiles.add(filesToOpen[i]); + if (fileTitles.length > i) { + extitles.add(fileTitles[i]); + } else { + extitles.add(null); + } + } + } + SWFSourceInfo[] sourceInfos = new SWFSourceInfo[exfiles.size()]; + for (int i = 0; i < exfiles.size(); i++) { + String extitle = extitles.get(i); + sourceInfos[i] = new SWFSourceInfo(null, exfiles.get(i), extitle == null || extitle.isEmpty() ? null : extitle); + } + if (sourceInfos.length > 0) { + openingFiles = true; + openFile(sourceInfos, () -> { + mainFrame.getPanel().tagTree.setSelectionPathString(Configuration.lastSessionSelection.get()); + setSessionLoaded(true); + }); + } + } + } + + if (!openingFiles) { + setSessionLoaded(true); + } + } + + public static String tempFile(String url) throws IOException { + File f = new File(Configuration.getFFDecHome() + "saved" + File.separator); + Path.createDirectorySafe(f); + return Configuration.getFFDecHome() + "saved" + File.separator + "asdec_" + Integer.toHexString(url.hashCode()) + ".tmp"; + } + + public static void removeTrayIcon() { + if (SystemTray.isSupported()) { + SystemTray tray = SystemTray.getSystemTray(); + if (trayIcon != null) { + tray.remove(trayIcon); + trayIcon = null; + } + } + } + + public static void switchProxy() { + proxyFrame.switchState(); + if (stopMenuItem != null) { + if (proxyFrame.isRunning()) { + stopMenuItem.setLabel(AppStrings.translate("proxy.stop")); + } else { + stopMenuItem.setLabel(AppStrings.translate("proxy.start")); + } + } + } + + public static void addTrayIcon() { + if (trayIcon != null) { + return; + } + if (SystemTray.isSupported()) { + SystemTray tray = SystemTray.getSystemTray(); + trayIcon = new TrayIcon(View.loadImage("proxy16"), ApplicationInfo.VENDOR + " " + ApplicationInfo.SHORT_APPLICATION_NAME + " " + AppStrings.translate("proxy")); + trayIcon.setImageAutoSize(true); + PopupMenu trayPopup = new PopupMenu(); + + ActionListener trayListener = new ActionListener() { + /** + * Invoked when an action occurs. + */ + @Override + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("EXIT")) { + Main.exit(); + } + if (e.getActionCommand().equals("SHOW")) { + Main.showProxy(); + } + if (e.getActionCommand().equals("SWITCH")) { + Main.switchProxy(); + } + } + }; + + MenuItem showMenuItem = new MenuItem(AppStrings.translate("proxy.show")); + showMenuItem.setActionCommand("SHOW"); + showMenuItem.addActionListener(trayListener); + trayPopup.add(showMenuItem); + stopMenuItem = new MenuItem(AppStrings.translate("proxy.start")); + stopMenuItem.setActionCommand("SWITCH"); + stopMenuItem.addActionListener(trayListener); + trayPopup.add(stopMenuItem); + trayPopup.addSeparator(); + MenuItem exitMenuItem = new MenuItem(AppStrings.translate("exit")); + exitMenuItem.setActionCommand("EXIT"); + exitMenuItem.addActionListener(trayListener); + trayPopup.add(exitMenuItem); + + trayIcon.setPopupMenu(trayPopup); + trayIcon.addMouseListener(new MouseAdapter() { + /** + * {@inheritDoc} + */ + @Override + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + Main.showProxy(); + } + } + }); + try { + tray.add(trayIcon); + } catch (AWTException ex) { + } + } + } + + public static void exit() { + Configuration.saveConfig(); + if (mainFrame != null && mainFrame.getPanel() != null) { + mainFrame.getPanel().unloadFlashPlayer(); + mainFrame.dispose(); + } + if (fileTxt != null) { + try { + fileTxt.flush(); + fileTxt.close(); + } catch (Exception ex) { + //ignore + } + } + System.exit(0); + } + + public static void about() { + (new AboutDialog()).setVisible(true); + } + + public static void advancedSettings() { + advancedSettings(null); + } + + public static void advancedSettings(String category) { + (new AdvancedSettingsDialog(category)).setVisible(true); + } + + public static void autoCheckForUpdates() { + if (Configuration.checkForUpdatesAuto.get()) { + Calendar lastUpdatesCheckDate = Configuration.lastUpdatesCheckDate.get(); + if ((lastUpdatesCheckDate == null) || (lastUpdatesCheckDate.getTime().getTime() < Calendar.getInstance().getTime().getTime() - Configuration.checkForUpdatesDelay.get())) { + new SwingWorker() { + @Override + protected Object doInBackground() throws Exception { + checkForUpdates(); + return null; + } + }.execute(); + } + } + } + + public static boolean checkForUpdates() { + String currentVersion = ApplicationInfo.version; + if (currentVersion.equals("unknown")) { + // sometimes during development the version information is not available + return false; + } + + List accepted = new ArrayList<>(); + if (Configuration.checkForUpdatesStable.get()) { + accepted.add("stable"); + } + if (Configuration.checkForUpdatesNightly.get()) { + accepted.add("nightly"); + } + + if (accepted.isEmpty()) { + return false; + } + + String acceptVersions = String.join(",", accepted); + try { + String proxyAddress = Configuration.updateProxyAddress.get(); + URL url = new URL(ApplicationInfo.updateCheckUrl); + + URLConnection uc; + if (proxyAddress != null && !proxyAddress.isEmpty()) { + int port = 8080; + if (proxyAddress.contains(":")) { + String[] parts = proxyAddress.split(":"); + port = Integer.parseInt(parts[1]); + proxyAddress = parts[0]; + } + + uc = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, port))); + } else { + uc = url.openConnection(); + } + uc.setRequestProperty("X-Accept-Versions", acceptVersions); + uc.setRequestProperty("X-Update-Major", "" + UPDATE_SYSTEM_MAJOR); + uc.setRequestProperty("X-Update-Minor", "" + UPDATE_SYSTEM_MINOR); + uc.setRequestProperty("User-Agent", ApplicationInfo.shortApplicationVerName); + String currentLoc = Configuration.locale.get("en"); + uc.setRequestProperty("Accept-Language", currentLoc + ("en".equals(currentLoc) ? "" : ", en;q=0.8")); + + uc.connect(); + + BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream())); + String s; + final java.util.List versions = new ArrayList<>(); + String header = ""; + Pattern headerPat = Pattern.compile("\\[([a-zA-Z0-9]+)\\]"); + int updateMajor; + int updateMinor; + Version ver = null; + while ((s = br.readLine()) != null) { + + Matcher m = headerPat.matcher(s); + if (m.matches()) { + header = m.group(1); + if (header.equals("version")) { + ver = new Version(); + versions.add(ver); + } + if (header.equals("noversion")) { + break; + } + } else if (s.contains("=")) { + String key = s.substring(0, s.indexOf('=')); + String val = s.substring(s.indexOf('=') + 1); + if ("updateSystem".equals(header)) { + if (key.equals("majorVersion")) { + updateMajor = Integer.parseInt(val); + if (updateMajor > UPDATE_SYSTEM_MAJOR) { + break; + } + } + if (key.equals("minorVersion")) { + updateMinor = Integer.parseInt(val); + } + } + if ("version".equals(header) && (ver != null)) { + if (key.equals("versionId")) { + ver.versionId = Integer.parseInt(val); + } + if (key.equals("versionName")) { + ver.versionName = val; + } + if (key.equals("nightly")) { + ver.nightly = val.equals("true"); + } + if (key.equals("revision")) { + ver.revision = val; + } + if (key.equals("build")) { + ver.build = Integer.parseInt(val); + } + if (key.equals("major")) { + ver.major = Integer.parseInt(val); + } + if (key.equals("minor")) { + ver.minor = Integer.parseInt(val); + } + if (key.equals("release")) { + ver.release = Integer.parseInt(val); + } + if (key.equals("longVersionName")) { + ver.longVersionName = val; + } + if (key.equals("releaseDate")) { + ver.releaseDate = val; + } + if (key.equals("appName")) { + ver.appName = val; + } + if (key.equals("appFullName")) { + ver.appFullName = val; + } + if (key.equals("updateLink")) { + ver.updateLink = val; + } + if (key.equals("change[]")) { + String changeType = val.substring(0, val.indexOf('|')); + String change = val.substring(val.indexOf('|') + 1); + if (!ver.changes.containsKey(changeType)) { + ver.changes.put(changeType, new ArrayList<>()); + } + List chlist = ver.changes.get(changeType); + chlist.add(change); + } + } + } + } + + if (!versions.isEmpty()) { + View.execInEventDispatch(() -> { + NewVersionDialog newVersionDialog = new NewVersionDialog(versions); + newVersionDialog.setVisible(true); + Configuration.lastUpdatesCheckDate.set(Calendar.getInstance()); + }); + + return true; + } + } catch (IOException | NumberFormatException ex) { + return false; + } + Configuration.lastUpdatesCheckDate.set(Calendar.getInstance()); + return false; + } + + private static FileHandler fileTxt; + + public static void clearLogFile() { + Logger logger = Logger.getLogger(""); + + FileHandler oldFileTxt = fileTxt; + fileTxt = null; + if (oldFileTxt != null) { + logger.removeHandler(fileTxt); + oldFileTxt.flush(); + oldFileTxt.close(); + } + + String fileName = null; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); + + try { + fileName = Configuration.getFFDecHome() + "logs" + File.separator; + if (Configuration.useDetailedLogging.get()) { + fileName += "log-" + sdf.format(new Date()) + ".txt"; + } else { + fileName += "log.txt"; + } + File f = new File(fileName).getParentFile(); + if (!f.exists()) { + f.mkdir(); + } + fileTxt = new FileHandler(fileName); + } catch (IOException | SecurityException ex) { + //cannot get lock error + if (ex.getMessage().contains("lock for")) { + //remove all old log files and their .lck + for (int i = 0; i <= 100; i++) { + File flog = new File(fileName + (i == 0 ? "" : "." + i)); + File flog_lock = new File(fileName + (i == 0 ? "" : "." + i) + ".lck"); + flog.delete(); + flog_lock.delete(); + } + try { + fileTxt = new FileHandler(fileName); + } catch (IOException | SecurityException ex1) { + logger.log(Level.SEVERE, "Cannot initialize logging", ex); + } + } else { + logger.log(Level.SEVERE, "Cannot initialize logging", ex); + } + } + + Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + logger.log(Level.SEVERE, "Uncaught exception in thread: " + t.getName(), e); + if (e instanceof OutOfMemoryError || !Helper.is64BitJre() && Helper.is64BitOs()) { + View.showMessageDialog(null, AppStrings.translate("message.warning.outOfMemory32BitJre"), AppStrings.translate("message.warning"), JOptionPane.WARNING_MESSAGE); + } + } + }); + + Formatter formatterTxt = new LogFormatter(); + if (fileTxt != null) { + fileTxt.setFormatter(formatterTxt); + logger.addHandler(fileTxt); + } + + if (!GraphicsEnvironment.isHeadless() && ErrorLogFrame.hasInstance()) { + ErrorLogFrame.getInstance().clearErrorState(); + } + + sdf = new SimpleDateFormat("yyyy-MM-dd"); + logger.log(Level.INFO, "Date: {0}", sdf.format(new Date())); + logger.log(Level.INFO, ApplicationInfo.applicationVerName); + logger.log(Level.INFO, "{0} {1} {2}", new Object[]{ + System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")}); + logger.log(Level.INFO, "{0} {1} {2}", new Object[]{ + System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("os.arch")}); + } + + public static void initLogging(boolean debug) { + try { + Logger logger = Logger.getLogger(""); + logger.setLevel(Configuration.logLevel); + + Handler[] handlers = logger.getHandlers(); + for (int i = handlers.length - 1; i >= 0; i--) { + logger.removeHandler(handlers[i]); + } + + ConsoleHandler conHan = new ConsoleHandler(); + conHan.setLevel(debug ? Level.CONFIG : Level.WARNING); + SimpleFormatter formatterTxt = new SimpleFormatter(); + conHan.setFormatter(formatterTxt); + logger.addHandler(conHan); + clearLogFile(); + + } catch (Exception ex) { + throw new RuntimeException("Problems with creating the log files"); + } + } +} diff --git a/src/com/jpexs/decompiler/flash/gui/MainPanel.java b/src/com/jpexs/decompiler/flash/gui/MainPanel.java index c45bc048b..717970b20 100644 --- a/src/com/jpexs/decompiler/flash/gui/MainPanel.java +++ b/src/com/jpexs/decompiler/flash/gui/MainPanel.java @@ -1,3681 +1,3681 @@ -/* - * Copyright (C) 2010-2016 JPEXS - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.jpexs.decompiler.flash.gui; - -import com.jpexs.decompiler.flash.AbortRetryIgnoreHandler; -import com.jpexs.decompiler.flash.ApplicationInfo; -import com.jpexs.decompiler.flash.EventListener; -import com.jpexs.decompiler.flash.ReadOnlyTagList; -import com.jpexs.decompiler.flash.SWF; -import com.jpexs.decompiler.flash.SWFBundle; -import com.jpexs.decompiler.flash.SWFSourceInfo; -import com.jpexs.decompiler.flash.abc.ABC; -import com.jpexs.decompiler.flash.abc.RenameType; -import com.jpexs.decompiler.flash.abc.ScriptPack; -import com.jpexs.decompiler.flash.abc.avm2.AVM2ConstantPool; -import com.jpexs.decompiler.flash.abc.avm2.deobfuscation.AbcMultiNameCollisionFixer; -import com.jpexs.decompiler.flash.abc.avm2.deobfuscation.DeobfuscationLevel; -import com.jpexs.decompiler.flash.abc.types.traits.Trait; -import com.jpexs.decompiler.flash.configuration.Configuration; -import com.jpexs.decompiler.flash.configuration.ConfigurationItem; -import com.jpexs.decompiler.flash.configuration.SwfSpecificConfiguration; -import com.jpexs.decompiler.flash.dumpview.DumpInfo; -import com.jpexs.decompiler.flash.dumpview.DumpInfoSwfNode; -import com.jpexs.decompiler.flash.exporters.BinaryDataExporter; -import com.jpexs.decompiler.flash.exporters.FontExporter; -import com.jpexs.decompiler.flash.exporters.FrameExporter; -import com.jpexs.decompiler.flash.exporters.ImageExporter; -import com.jpexs.decompiler.flash.exporters.MorphShapeExporter; -import com.jpexs.decompiler.flash.exporters.MovieExporter; -import com.jpexs.decompiler.flash.exporters.ShapeExporter; -import com.jpexs.decompiler.flash.exporters.SoundExporter; -import com.jpexs.decompiler.flash.exporters.SymbolClassExporter; -import com.jpexs.decompiler.flash.exporters.TextExporter; -import com.jpexs.decompiler.flash.exporters.modes.BinaryDataExportMode; -import com.jpexs.decompiler.flash.exporters.modes.ButtonExportMode; -import com.jpexs.decompiler.flash.exporters.modes.FontExportMode; -import com.jpexs.decompiler.flash.exporters.modes.FrameExportMode; -import com.jpexs.decompiler.flash.exporters.modes.ImageExportMode; -import com.jpexs.decompiler.flash.exporters.modes.MorphShapeExportMode; -import com.jpexs.decompiler.flash.exporters.modes.MovieExportMode; -import com.jpexs.decompiler.flash.exporters.modes.ScriptExportMode; -import com.jpexs.decompiler.flash.exporters.modes.ShapeExportMode; -import com.jpexs.decompiler.flash.exporters.modes.SoundExportMode; -import com.jpexs.decompiler.flash.exporters.modes.SpriteExportMode; -import com.jpexs.decompiler.flash.exporters.modes.SymbolClassExportMode; -import com.jpexs.decompiler.flash.exporters.modes.TextExportMode; -import com.jpexs.decompiler.flash.exporters.script.AS2ScriptExporter; -import com.jpexs.decompiler.flash.exporters.script.AS3ScriptExporter; -import com.jpexs.decompiler.flash.exporters.settings.BinaryDataExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.ButtonExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.FontExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.FrameExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.ImageExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.MorphShapeExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.MovieExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.ScriptExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.ShapeExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.SoundExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.SpriteExportSettings; -import com.jpexs.decompiler.flash.exporters.settings.TextExportSettings; -import com.jpexs.decompiler.flash.exporters.swf.SwfJavaExporter; -import com.jpexs.decompiler.flash.exporters.swf.SwfXmlExporter; -import com.jpexs.decompiler.flash.flexsdk.MxmlcAs3ScriptReplacer; -import com.jpexs.decompiler.flash.gui.abc.ABCPanel; -import com.jpexs.decompiler.flash.gui.abc.ABCPanelSearchResult; -import com.jpexs.decompiler.flash.gui.abc.ClassesListTreeModel; -import com.jpexs.decompiler.flash.gui.abc.DecompiledEditorPane; -import com.jpexs.decompiler.flash.gui.abc.DeobfuscationDialog; -import com.jpexs.decompiler.flash.gui.action.ActionPanel; -import com.jpexs.decompiler.flash.gui.action.ActionSearchResult; -import com.jpexs.decompiler.flash.gui.controls.JPersistentSplitPane; -import com.jpexs.decompiler.flash.gui.dumpview.DumpTree; -import com.jpexs.decompiler.flash.gui.dumpview.DumpTreeModel; -import com.jpexs.decompiler.flash.gui.dumpview.DumpViewPanel; -import com.jpexs.decompiler.flash.gui.editor.LineMarkedEditorPane; -import com.jpexs.decompiler.flash.gui.helpers.ObservableList; -import com.jpexs.decompiler.flash.gui.player.FlashPlayerPanel; -import com.jpexs.decompiler.flash.gui.tagtree.TagTree; -import com.jpexs.decompiler.flash.gui.tagtree.TagTreeModel; -import com.jpexs.decompiler.flash.gui.timeline.TimelineViewPanel; -import com.jpexs.decompiler.flash.helpers.FileTextWriter; -import com.jpexs.decompiler.flash.helpers.Freed; -import com.jpexs.decompiler.flash.importers.AS2ScriptImporter; -import com.jpexs.decompiler.flash.importers.AS3ScriptImporter; -import com.jpexs.decompiler.flash.importers.As3ScriptReplacerFactory; -import com.jpexs.decompiler.flash.importers.As3ScriptReplacerInterface; -import com.jpexs.decompiler.flash.importers.BinaryDataImporter; -import com.jpexs.decompiler.flash.importers.FFDecAs3ScriptReplacer; -import com.jpexs.decompiler.flash.importers.ImageImporter; -import com.jpexs.decompiler.flash.importers.ShapeImporter; -import com.jpexs.decompiler.flash.importers.SwfXmlImporter; -import com.jpexs.decompiler.flash.importers.SymbolClassImporter; -import com.jpexs.decompiler.flash.importers.TextImporter; -import com.jpexs.decompiler.flash.importers.svg.SvgImporter; -import com.jpexs.decompiler.flash.tags.ABCContainerTag; -import com.jpexs.decompiler.flash.tags.DefineBinaryDataTag; -import com.jpexs.decompiler.flash.tags.DefineBitsJPEG3Tag; -import com.jpexs.decompiler.flash.tags.DefineBitsJPEG4Tag; -import com.jpexs.decompiler.flash.tags.DefineSoundTag; -import com.jpexs.decompiler.flash.tags.DefineSpriteTag; -import com.jpexs.decompiler.flash.tags.DoActionTag; -import com.jpexs.decompiler.flash.tags.DoInitActionTag; -import com.jpexs.decompiler.flash.tags.FileAttributesTag; -import com.jpexs.decompiler.flash.tags.MetadataTag; -import com.jpexs.decompiler.flash.tags.Tag; -import com.jpexs.decompiler.flash.tags.TagInfo; -import com.jpexs.decompiler.flash.tags.base.ASMSource; -import com.jpexs.decompiler.flash.tags.base.BoundedTag; -import com.jpexs.decompiler.flash.tags.base.ButtonTag; -import com.jpexs.decompiler.flash.tags.base.CharacterTag; -import com.jpexs.decompiler.flash.tags.base.DrawableTag; -import com.jpexs.decompiler.flash.tags.base.FontTag; -import com.jpexs.decompiler.flash.tags.base.ImageTag; -import com.jpexs.decompiler.flash.tags.base.MissingCharacterHandler; -import com.jpexs.decompiler.flash.tags.base.MorphShapeTag; -import com.jpexs.decompiler.flash.tags.base.ShapeTag; -import com.jpexs.decompiler.flash.tags.base.SoundStreamHeadTypeTag; -import com.jpexs.decompiler.flash.tags.base.SoundTag; -import com.jpexs.decompiler.flash.tags.base.SymbolClassTypeTag; -import com.jpexs.decompiler.flash.tags.base.TextImportErrorHandler; -import com.jpexs.decompiler.flash.tags.base.TextTag; -import com.jpexs.decompiler.flash.tags.text.TextAlign; -import com.jpexs.decompiler.flash.tags.text.TextParseException; -import com.jpexs.decompiler.flash.timeline.DepthState; -import com.jpexs.decompiler.flash.timeline.Frame; -import com.jpexs.decompiler.flash.timeline.TagScript; -import com.jpexs.decompiler.flash.timeline.Timeline; -import com.jpexs.decompiler.flash.timeline.Timelined; -import com.jpexs.decompiler.flash.treeitems.FolderItem; -import com.jpexs.decompiler.flash.treeitems.HeaderItem; -import com.jpexs.decompiler.flash.treeitems.SWFList; -import com.jpexs.decompiler.flash.treeitems.TreeItem; -import com.jpexs.decompiler.flash.types.MATRIX; -import com.jpexs.decompiler.flash.types.RECT; -import com.jpexs.decompiler.flash.types.sound.SoundFormat; -import com.jpexs.decompiler.flash.xfl.FLAVersion; -import com.jpexs.helpers.CancellableWorker; -import com.jpexs.helpers.Helper; -import com.jpexs.helpers.Path; -import com.jpexs.helpers.ProgressListener; -import com.jpexs.helpers.SerializableImage; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Desktop; -import java.awt.FlowLayout; -import java.awt.Font; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.awt.dnd.DnDConstants; -import java.awt.dnd.DragGestureEvent; -import java.awt.dnd.DragGestureListener; -import java.awt.dnd.DragSource; -import java.awt.dnd.DragSourceDragEvent; -import java.awt.dnd.DragSourceDropEvent; -import java.awt.dnd.DragSourceEvent; -import java.awt.dnd.DragSourceListener; -import java.awt.dnd.DropTarget; -import java.awt.dnd.DropTargetDropEvent; -import java.awt.event.ActionEvent; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.CancellationException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.sound.sampled.LineUnavailableException; -import javax.sound.sampled.UnsupportedAudioFileException; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.Icon; -import javax.swing.JColorChooser; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.SwingConstants; -import javax.swing.UIManager; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.filechooser.FileFilter; -import javax.swing.plaf.basic.BasicTreeUI; -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreePath; -import jsyntaxpane.DefaultSyntaxKit; - -/** - * - * @author JPEXS - */ -public final class MainPanel extends JPanel implements TreeSelectionListener, SearchListener, Freed { - - private final MainFrame mainFrame; - - private final ObservableList swfs; - - private final JPanel welcomePanel; - - private final TimelineViewPanel timelineViewPanel; - - private final MainFrameStatusPanel statusPanel; - - private final MainFrameMenu mainMenu; - - private final JProgressBar progressBar = new JProgressBar(0, 100); - - public TagTree tagTree; - - public DumpTree dumpTree; - - private final FlashPlayerPanel flashPanel; - - private final FlashPlayerPanel flashPanel2; - - private final JPanel contentPanel; - - private final JPanel displayPanel; - - public FolderPreviewPanel folderPreviewPanel; - - private boolean isWelcomeScreen = true; - - private static final String CARDPREVIEWPANEL = "Preview card"; - - private static final String CARDFOLDERPREVIEWPANEL = "Folder preview card"; - - private static final String CARDEMPTYPANEL = "Empty card"; - - private static final String CARDDUMPVIEW = "Dump view"; - - private static final String CARDACTIONSCRIPTPANEL = "ActionScript card"; - - private static final String CARDACTIONSCRIPT3PANEL = "ActionScript3 card"; - - private static final String CARDHEADER = "Header card"; - - private static final String DETAILCARDAS3NAVIGATOR = "Traits list"; - - private static final String DETAILCARDTAGINFO = "Tag information"; - - private static final String DETAILCARDEMPTYPANEL = "Empty card"; - - private static final String SPLIT_PANE1 = "SPLITPANE1"; - - private static final String WELCOME_PANEL = "WELCOMEPANEL"; - - private static final String TIMELINE_PANEL = "TIMELINEPANEL"; - - private static final String RESOURCES_VIEW = "RESOURCES"; - - private static final String DUMP_VIEW = "DUMP"; - - private static final String TIMELINE_VIEW = "TIMELINE"; - - private final JPersistentSplitPane splitPane1; - - private final JPersistentSplitPane splitPane2; - - private JPanel detailPanel; - - private JTextField filterField = new MyTextField(""); - - private JPanel searchPanel; - - private ABCPanel abcPanel; - - private ActionPanel actionPanel; - - private final PreviewPanel previewPanel; - - private final HeaderInfoPanel headerPanel; - - private DumpViewPanel dumpViewPanel; - - private final JPanel treePanel; - - private final PreviewPanel dumpPreviewPanel; - - private final TagInfoPanel tagInfoPanel; - - private TreePanelMode treePanelMode; - - private CancellableWorker setSourceWorker; - - public TreeItem oldItem; - - // play morph shape in 2 second(s) - public static final int MORPH_SHAPE_ANIMATION_LENGTH = 2; - - public static final int MORPH_SHAPE_ANIMATION_FRAME_RATE = 30; - - private static final Logger logger = Logger.getLogger(MainPanel.class.getName()); - - public void setPercent(int percent) { - progressBar.setValue(percent); - progressBar.setVisible(true); - } - - public void hidePercent() { - if (progressBar.isVisible()) { - progressBar.setVisible(false); - } - } - - public MainFrame getMainFrame() { - return mainFrame; - } - - static { - try { - File.createTempFile("temp", ".swf").delete(); //First call to this is slow, so make it first - } catch (IOException ex) { - logger.log(Level.SEVERE, null, ex); - } - } - - public void updateMenu() { - mainMenu.updateComponents(); - } - - private static void addTab(JTabbedPane tabbedPane, Component tab, String title, Icon icon) { - tabbedPane.add(tab); - - JLabel lbl = new JLabel(title); - lbl.setIcon(icon); - lbl.setIconTextGap(5); - lbl.setHorizontalTextPosition(SwingConstants.RIGHT); - - tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, lbl); - } - - public void setStatus(String s) { - statusPanel.setStatus(s); - } - - public void setWorkStatus(String s, CancellableWorker worker) { - statusPanel.setWorkStatus(s, worker); - mainMenu.updateComponents(); - } - - private JPanel createWelcomePanel() { - JPanel welcomePanel = new JPanel(); - welcomePanel.setLayout(new BoxLayout(welcomePanel, BoxLayout.Y_AXIS)); - JLabel welcomeToLabel = new JLabel(translate("startup.welcometo")); - welcomeToLabel.setFont(welcomeToLabel.getFont().deriveFont(40)); - welcomeToLabel.setAlignmentX(0.5f); - JPanel appNamePanel = new JPanel(new FlowLayout()); - JLabel jpLabel = new JLabel("JPEXS "); - jpLabel.setAlignmentX(0.5f); - jpLabel.setForeground(new Color(0, 0, 160)); - jpLabel.setFont(new Font("Tahoma", Font.BOLD, 50)); - jpLabel.setHorizontalAlignment(SwingConstants.CENTER); - appNamePanel.add(jpLabel); - - JLabel ffLabel = new JLabel("Free Flash "); - ffLabel.setAlignmentX(0.5f); - ffLabel.setFont(new Font("Tahoma", Font.BOLD, 50)); - ffLabel.setHorizontalAlignment(SwingConstants.CENTER); - appNamePanel.add(ffLabel); - - JLabel decLabel = new JLabel("Decompiler"); - decLabel.setAlignmentX(0.5f); - decLabel.setForeground(Color.red); - decLabel.setFont(new Font("Tahoma", Font.BOLD, 50)); - decLabel.setHorizontalAlignment(SwingConstants.CENTER); - appNamePanel.add(decLabel); - appNamePanel.setAlignmentX(0.5f); - welcomePanel.add(Box.createGlue()); - welcomePanel.add(welcomeToLabel); - welcomePanel.add(appNamePanel); - JLabel startLabel = new JLabel(translate("startup.selectopen")); - startLabel.setAlignmentX(0.5f); - startLabel.setFont(startLabel.getFont().deriveFont(30)); - welcomePanel.add(startLabel); - welcomePanel.add(Box.createGlue()); - return welcomePanel; - } - - private JPanel createFolderPreviewCard() { - JPanel folderPreviewCard = new JPanel(new BorderLayout()); - folderPreviewPanel = new FolderPreviewPanel(this, new ArrayList<>()); - folderPreviewCard.add(new JScrollPane(folderPreviewPanel), BorderLayout.CENTER); - - return folderPreviewCard; - } - - private JPanel createDumpPreviewCard() { - JPanel dumpViewCard = new JPanel(new BorderLayout()); - dumpViewPanel = new DumpViewPanel(dumpTree); - dumpViewCard.add(new JScrollPane(dumpViewPanel), BorderLayout.CENTER); - - return dumpViewCard; - } - - public String translate(String key) { - return mainFrame.translate(key); - } - - public MainPanel(MainFrame mainFrame, MainFrameMenu mainMenu, FlashPlayerPanel flashPanel, FlashPlayerPanel previewFlashPanel) { - super(); - - this.mainFrame = mainFrame; - this.mainMenu = mainMenu; - this.flashPanel = flashPanel; - this.flashPanel2 = previewFlashPanel; - - mainFrame.setTitle(ApplicationInfo.applicationVerName); - - setLayout(new BorderLayout()); - swfs = new ObservableList<>(); - - detailPanel = new JPanel(); - detailPanel.setLayout(new CardLayout()); - - JPanel whitePanel = new JPanel(); - whitePanel.setBackground(Color.white); - detailPanel.add(whitePanel, DETAILCARDEMPTYPANEL); - - tagInfoPanel = new TagInfoPanel(this); - detailPanel.add(tagInfoPanel, DETAILCARDTAGINFO); - - UIManager.getDefaults().put("TreeUI", BasicTreeUI.class.getName()); - tagTree = new TagTree(null, this); - tagTree.addTreeSelectionListener(this); - tagTree.setSelectionModel(new DefaultTreeSelectionModel() { - private boolean isModified() { - if (abcPanel != null && abcPanel.isEditing()) { - abcPanel.tryAutoSave(); - } - - if (actionPanel != null && actionPanel.isEditing()) { - actionPanel.tryAutoSave(); - } - - if (previewPanel.isEditing()) { - previewPanel.tryAutoSave(); - } - - if (headerPanel.isEditing()) { - headerPanel.tryAutoSave(); - } - - return (abcPanel != null && abcPanel.isEditing()) - || (actionPanel != null && actionPanel.isEditing()) - || previewPanel.isEditing() || headerPanel.isEditing(); - } - - @Override - public void addSelectionPath(TreePath path) { - if (isModified()) { - return; - } - - super.addSelectionPath(path); - } - - @Override - public void addSelectionPaths(TreePath[] paths) { - if (isModified()) { - return; - } - - super.addSelectionPaths(paths); - } - - @Override - public void setSelectionPath(TreePath path) { - if (isModified()) { - return; - } - - super.setSelectionPath(path); - } - - @Override - public void setSelectionPaths(TreePath[] pPaths) { - if (isModified()) { - return; - } - - super.setSelectionPaths(pPaths); - } - - @Override - public void clearSelection() { - if (isModified()) { - return; - } - - super.clearSelection(); - } - - public void setSelection(TreePath[] selection) { - if (isModified()) { - return; - } - - this.selection = selection; - } - - @Override - public void removeSelectionPath(TreePath path) { - if (isModified()) { - return; - } - - super.removeSelectionPath(path); - } - - @Override - public void removeSelectionPaths(TreePath[] paths) { - if (isModified()) { - return; - } - - super.removeSelectionPaths(paths); - } - }); - - DragSource dragSource = DragSource.getDefaultDragSource(); - dragSource.createDefaultDragGestureRecognizer(tagTree, DnDConstants.ACTION_COPY_OR_MOVE, new DragGestureListener() { - @Override - public void dragGestureRecognized(DragGestureEvent dge) { - dge.startDrag(DragSource.DefaultCopyDrop, new Transferable() { - @Override - public DataFlavor[] getTransferDataFlavors() { - return new DataFlavor[]{DataFlavor.javaFileListFlavor}; - } - - @Override - public boolean isDataFlavorSupported(DataFlavor flavor) { - return flavor.equals(DataFlavor.javaFileListFlavor); - } - - @Override - public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { - if (flavor.equals(DataFlavor.javaFileListFlavor)) { - List files; - String tempDir = System.getProperty("java.io.tmpdir"); - if (!tempDir.endsWith(File.separator)) { - tempDir += File.separator; - } - Random rnd = new Random(); - tempDir += "ffdec" + File.separator + "export" + File.separator + System.currentTimeMillis() + "_" + rnd.nextInt(1000); - File fTempDir = new File(tempDir); - Path.createDirectorySafe(fTempDir); - - File ftemp = new File(tempDir); - ExportDialog exd = new ExportDialog(null); - try { - files = exportSelection(new GuiAbortRetryIgnoreHandler(), tempDir, exd); - } catch (InterruptedException ex) { - logger.log(Level.SEVERE, null, ex); - return null; - } - - files.clear(); - - File[] fs = ftemp.listFiles(); - files.addAll(Arrays.asList(fs)); - - Main.stopWork(); - - for (File f : files) { - f.deleteOnExit(); - } - new File(tempDir).deleteOnExit(); - return files; - - } - return null; - } - }, new DragSourceListener() { - @Override - public void dragEnter(DragSourceDragEvent dsde) { - enableDrop(false); - } - - @Override - public void dragOver(DragSourceDragEvent dsde) { - } - - @Override - public void dropActionChanged(DragSourceDragEvent dsde) { - } - - @Override - public void dragExit(DragSourceEvent dse) { - } - - @Override - public void dragDropEnd(DragSourceDropEvent dsde) { - enableDrop(true); - } - }); - } - }); - - tagTree.createContextMenu(); - - dumpTree = new DumpTree(null, this); - dumpTree.addTreeSelectionListener(this); - dumpTree.createContextMenu(); - - statusPanel = new MainFrameStatusPanel(this); - add(statusPanel, BorderLayout.SOUTH); - - displayPanel = new JPanel(new CardLayout()); - - DefaultSyntaxKit.initKit(); - previewPanel = new PreviewPanel(this, flashPanel); - - dumpPreviewPanel = new PreviewPanel(this, previewFlashPanel); - dumpPreviewPanel.setReadOnly(true); - - displayPanel.add(previewPanel, CARDPREVIEWPANEL); - displayPanel.add(createFolderPreviewCard(), CARDFOLDERPREVIEWPANEL); - displayPanel.add(createDumpPreviewCard(), CARDDUMPVIEW); - - headerPanel = new HeaderInfoPanel(); - displayPanel.add(headerPanel, CARDHEADER); - - displayPanel.add(new JPanel(), CARDEMPTYPANEL); - showCard(CARDEMPTYPANEL); - - searchPanel = new JPanel(); - searchPanel.setLayout(new BorderLayout()); - searchPanel.add(filterField, BorderLayout.CENTER); - searchPanel.add(new JLabel(View.getIcon("search16")), BorderLayout.WEST); - JLabel closeSearchButton = new JLabel(View.getIcon("cancel16")); - closeSearchButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - closeTagTreeSearch(); - } - }); - searchPanel.add(closeSearchButton, BorderLayout.EAST); - searchPanel.setVisible(false); - treePanel = new JPanel(new CardLayout()); - treePanel.add(createResourcesViewCard(), RESOURCES_VIEW); - treePanel.add(createDumpViewCard(), DUMP_VIEW); - //treePanel.add(searchPanel, BorderLayout.SOUTH); - //searchPanel.setVisible(false); - filterField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void changedUpdate(DocumentEvent e) { - warn(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - warn(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - warn(); - } - - public void warn() { - doFilter(); - } - }); - - //displayPanel.setBorder(BorderFactory.createLineBorder(Color.black)); - splitPane2 = new JPersistentSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, detailPanel, Configuration.guiSplitPane2DividerLocationPercent); - splitPane1 = new JPersistentSplitPane(JSplitPane.HORIZONTAL_SPLIT, splitPane2, displayPanel, Configuration.guiSplitPane1DividerLocationPercent); - - welcomePanel = createWelcomePanel(); - add(welcomePanel, BorderLayout.CENTER); - - timelineViewPanel = new TimelineViewPanel(); - - CardLayout cl3 = new CardLayout(); - contentPanel = new JPanel(cl3); - contentPanel.add(welcomePanel, WELCOME_PANEL); - contentPanel.add(splitPane1, SPLIT_PANE1); - contentPanel.add(timelineViewPanel, TIMELINE_PANEL); - add(contentPanel); - cl3.show(contentPanel, WELCOME_PANEL); - - tagTree.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if ((e.getKeyCode() == 'F') && (e.isControlDown())) { - searchPanel.setVisible(true); - filterField.requestFocusInWindow(); - } - } - }); - detailPanel.setVisible(false); - - updateUi(); - - this.swfs.addCollectionChangedListener((e) -> { - TagTreeModel ttm = tagTree.getModel(); - if (ttm != null) { - if (getCurrentSwf() == null) { - tagTree.setSelectionPath(ttm.getTreePath(ttm.getRoot())); - } - ttm.updateSwfs(e); - tagTree.expandRoot(); - tagTree.expandFirstLevelNodes(); - } - - DumpTreeModel dtm = dumpTree.getModel(); - if (dtm != null) { - List> expandedNodes = View.getExpandedNodes(dumpTree); - dtm.updateSwfs(); - View.expandTreeNodes(dumpTree, expandedNodes); - dumpTree.expandRoot(); - dumpTree.expandFirstLevelNodes(); - } - - if (swfs.isEmpty()) { - tagTree.setUI(new BasicTreeUI() { - { - setHashColor(Color.gray); - } - }); - dumpTree.setUI(new BasicTreeUI() { - { - setHashColor(Color.gray); - } - }); - } - }); - - //Opening files with drag&drop to main window - enableDrop(true); - } - - public void closeTagTreeSearch() { - filterField.setText(""); - doFilter(); - searchPanel.setVisible(false); - } - - public void loadSwfAtPos(SWFList newSwfs, int index) { - previewPanel.clear(); - swfs.set(index, newSwfs); - SWF swf = newSwfs.size() > 0 ? newSwfs.get(0) : null; - if (swf != null) { - updateUi(swf); - } - - doFilter(); - reload(false); - } - - public void load(SWFList newSwfs, boolean first) { - - previewPanel.clear(); - - swfs.add(newSwfs); - SWF swf = newSwfs.size() > 0 ? newSwfs.get(0) : null; - if (swf != null) { - updateUi(swf); - } - - doFilter(); - reload(false); - } - - private ABCPanel getABCPanel() { - if (abcPanel == null) { - abcPanel = new ABCPanel(this); - displayPanel.add(abcPanel, CARDACTIONSCRIPT3PANEL); - detailPanel.add(abcPanel.tabbedPane, DETAILCARDAS3NAVIGATOR); - } - - return abcPanel; - } - - private ActionPanel getActionPanel() { - if (actionPanel == null) { - actionPanel = new ActionPanel(MainPanel.this); - displayPanel.add(actionPanel, CARDACTIONSCRIPTPANEL); - } - - return actionPanel; - } - - private void updateUi(final SWF swf) { - - mainFrame.setTitle(ApplicationInfo.applicationVerName + (Configuration.displayFileName.get() ? " - " + swf.getFileTitle() : "")); - - List abcList = swf.getAbcList(); - - boolean hasAbc = !abcList.isEmpty(); - - if (hasAbc) { - getABCPanel().setAbc(abcList.get(0).getABC()); - } - - if (isWelcomeScreen) { - CardLayout cl = (CardLayout) (contentPanel.getLayout()); - cl.show(contentPanel, SPLIT_PANE1); - isWelcomeScreen = false; - } - - mainMenu.updateComponents(swf); - } - - private void updateUi() { - if (!isWelcomeScreen && swfs.isEmpty()) { - CardLayout cl = (CardLayout) (contentPanel.getLayout()); - cl.show(contentPanel, WELCOME_PANEL); - isWelcomeScreen = true; - closeTagTreeSearch(); - } - - mainFrame.setTitle(ApplicationInfo.applicationVerName); - mainMenu.updateComponents(null); - - showView(getCurrentView()); - } - - private boolean closeConfirmation(SWFList swfList) { - String message = swfList == null - ? translate("message.confirm.closeAll") - : translate("message.confirm.close").replace("{swfName}", swfList.toString()); - - return View.showConfirmDialog(this, message, translate("message.warning"), JOptionPane.OK_CANCEL_OPTION, Configuration.showCloseConfirmation, JOptionPane.OK_OPTION) == JOptionPane.OK_OPTION; - } - - public boolean isModified() { - for (SWFList swfList : swfs) { - for (SWF swf : swfList) { - if (swf.isModified()) { - return true; - } - } - } - - return false; - } - - public boolean closeAll(boolean showCloseConfirmation) { - if (showCloseConfirmation && isModified()) { - boolean closeConfirmResult = closeConfirmation(swfs.size() == 1 ? swfs.get(0) : null); - if (!closeConfirmResult) { - return false; - } - } - - List swfsLists = new ArrayList<>(swfs); - swfs.clear(); - oldItem = null; - clear(); - updateUi(); - - for (SWFList swfList : swfsLists) { - List swfs2 = new ArrayList<>(swfList); - for (SWF swf : swfs2) { - swf.clearTagSwfs(); - } - } - - return true; - } - - public boolean close(SWFList swfList) { - boolean modified = false; - for (SWF swf : swfList) { - if (swf.isModified()) { - modified = true; - } - } - - if (modified) { - boolean closeConfirmResult = closeConfirmation(swfList); - if (!closeConfirmResult) { - return false; - } - } - - swfs.remove(swfList); - oldItem = null; - clear(); - updateUi(); - - List swfs2 = new ArrayList<>(swfList); - for (SWF swf : swfs2) { - swf.clearTagSwfs(); - } - - return true; - } - - public void enableDrop(boolean value) { - if (value) { - setDropTarget(new DropTarget() { - @Override - public synchronized void drop(DropTargetDropEvent dtde) { - try { - dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); - @SuppressWarnings("unchecked") - List droppedFiles = (List) dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); - if (!droppedFiles.isEmpty()) { - SWFSourceInfo[] sourceInfos = new SWFSourceInfo[droppedFiles.size()]; - for (int i = 0; i < droppedFiles.size(); i++) { - sourceInfos[i] = new SWFSourceInfo(null, droppedFiles.get(i).getAbsolutePath(), null); - } - Main.openFile(sourceInfos, null); - } - } catch (UnsupportedFlavorException | IOException ex) { - } - } - }); - } else { - setDropTarget(null); - } - } - - public void updateClassesList() { - List nodes = getASTreeNodes(tagTree); - boolean updateNeeded = false; - for (TreeItem n : nodes) { - if (n instanceof ClassesListTreeModel) { - ((ClassesListTreeModel) n).update(); - updateNeeded = true; - } - } - - refreshTree(); - - if (updateNeeded) { - tagTree.updateUI(); - } - } - - public void doFilter() { - List nodes = getASTreeNodes(tagTree); - for (TreeItem n : nodes) { - if (n instanceof ClassesListTreeModel) { - String filterText = filterField.getText(); - ((ClassesListTreeModel) n).setFilter(filterText); - TagTreeModel tm = tagTree.getModel(); - TreePath path = tm.getTreePath(n); - tm.updateNode(path); - if (!filterText.isEmpty()) { - View.expandTreeNodes(tagTree, path, true); - } - } - } - } - - public void renameIdentifier(SWF swf, String identifier) throws InterruptedException { - String oldName = identifier; - String newName = View.showInputDialog(translate("rename.enternew"), oldName); - if (newName != null) { - if (!oldName.equals(newName)) { - swf.renameAS2Identifier(oldName, newName); - View.showMessageDialog(null, translate("rename.finished.identifier")); - updateClassesList(); - reload(true); - } - } - } - - public void renameMultiname(List abcList, int multiNameIndex) { - String oldName = ""; - AVM2ConstantPool constants = getABCPanel().abc.constants; - if (constants.getMultiname(multiNameIndex).name_index > 0) { - oldName = constants.getString(constants.getMultiname(multiNameIndex).name_index); - } - - String newName = View.showInputDialog(translate("rename.enternew"), oldName); - if (newName != null) { - if (!oldName.equals(newName)) { - int mulCount = 0; - for (ABCContainerTag cnt : abcList) { - ABC abc = cnt.getABC(); - for (int m = 1; m < abc.constants.getMultinameCount(); m++) { - int ni = abc.constants.getMultiname(m).name_index; - String n = ""; - if (ni > 0) { - n = abc.constants.getString(ni); - } - if (n.equals(oldName)) { - abc.renameMultiname(m, newName); - mulCount++; - } - } - } - - View.showMessageDialog(null, translate("rename.finished.multiname").replace("%count%", Integer.toString(mulCount))); - if (abcPanel != null) { - abcPanel.reload(); - } - - updateClassesList(); - reload(true); - ABCPanel abcPanel = getABCPanel(); - abcPanel.hilightScript(abcPanel.getSwf(), abcPanel.decompiledTextArea.getScriptLeaf().getClassPath().toRawString()); - } - } - } - - public List getASTreeNodes(TagTree tree) { - List result = new ArrayList<>(); - TagTreeModel tm = (TagTreeModel) tree.getModel(); - if (tm == null) { - return result; - } - TreeItem root = tm.getRoot(); - for (int i = 0; i < tm.getChildCount(root); i++) { - // first level node can be SWF and SWFBundle - TreeItem node = tm.getChild(root, i); - if (node instanceof SWFBundle) { - for (int j = 0; j < tm.getChildCount(node); j++) { - // child of SWFBundle should be SWF - SWF swfNode = (SWF) tm.getChild(node, j); - result.add(tm.getScriptsNode(swfNode)); - } - } else if (node instanceof SWF) { - SWF swfNode = (SWF) tm.getChild(root, i); - result.add(tm.getScriptsNode(swfNode)); - } - } - return result; - } - - public boolean confirmExperimental() { - return View.showConfirmDialog(null, translate("message.confirm.experimental"), translate("message.warning"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION; - } - - public List exportSelection(AbortRetryIgnoreHandler handler, String selFile, ExportDialog export) throws IOException, InterruptedException { - - List ret = new ArrayList<>(); - List sel = folderPreviewPanel.selectedItems.isEmpty() ? tagTree.getAllSelected() : new ArrayList<>(folderPreviewPanel.selectedItems.values()); - - Set usedSwfs = new HashSet<>(); - for (TreeItem d : sel) { - SWF selectedNodeSwf = d.getSwf(); - if (!usedSwfs.contains(selectedNodeSwf)) { - usedSwfs.add(selectedNodeSwf); - } - } - - Map usedSwfsIds = new HashMap<>(); - for (SWF swf : usedSwfs) { - List as3scripts = new ArrayList<>(); - List images = new ArrayList<>(); - List shapes = new ArrayList<>(); - List morphshapes = new ArrayList<>(); - List buttons = new ArrayList<>(); - List movies = new ArrayList<>(); - List sounds = new ArrayList<>(); - List texts = new ArrayList<>(); - List as12scripts = new ArrayList<>(); - List binaryData = new ArrayList<>(); - Map> frames = new HashMap<>(); - List fonts = new ArrayList<>(); - List symbolNames = new ArrayList<>(); - - for (TreeItem d : sel) { - SWF selectedNodeSwf = d.getSwf(); - - if (selectedNodeSwf != swf) { - continue; - } - - if (d instanceof TagScript) { - Tag tag = ((TagScript) d).getTag(); - if (tag instanceof DoActionTag || tag instanceof DoInitActionTag) { - as12scripts.add(d); - } - } - - if (d instanceof Tag || d instanceof ASMSource) { - TreeNodeType nodeType = TagTree.getTreeNodeType(d); - if (nodeType == TreeNodeType.IMAGE) { - images.add((Tag) d); - } - if (nodeType == TreeNodeType.SHAPE) { - shapes.add((Tag) d); - } - if (nodeType == TreeNodeType.BUTTON) { - buttons.add((Tag) d); - } - if (nodeType == TreeNodeType.MORPH_SHAPE) { - morphshapes.add((Tag) d); - } - if (nodeType == TreeNodeType.AS) { - as12scripts.add(d); - } - if (nodeType == TreeNodeType.MOVIE) { - movies.add((Tag) d); - } - if (nodeType == TreeNodeType.SOUND) { - sounds.add((Tag) d); - } - if (nodeType == TreeNodeType.BINARY_DATA) { - binaryData.add((Tag) d); - } - if (nodeType == TreeNodeType.TEXT) { - texts.add((Tag) d); - } - if (nodeType == TreeNodeType.FONT) { - fonts.add((Tag) d); - } - if (nodeType == TreeNodeType.OTHER_TAG) { - if (d instanceof SymbolClassTypeTag) { - symbolNames.add((Tag) d); - } - } - } - - if (d instanceof Frame) { - Frame fn = (Frame) d; - Timelined parent = fn.timeline.timelined; - int frame = fn.frame; - int parentId = 0; - if (parent instanceof CharacterTag) { - parentId = ((CharacterTag) parent).getCharacterId(); - } - if (!frames.containsKey(parentId)) { - frames.put(parentId, new ArrayList<>()); - } - frames.get(parentId).add(frame); - } - if (d instanceof ScriptPack) { - as3scripts.add((ScriptPack) d); - } - } - - String selFile2; - if (usedSwfs.size() > 1) { - selFile2 = selFile + File.separator + Helper.getNextId(swf.getShortFileName(), usedSwfsIds); - } else { - selFile2 = selFile; - } - - EventListener evl = swf.getExportEventListener(); - - if (export.isOptionEnabled(ImageExportMode.class)) { - ret.addAll(new ImageExporter().exportImages(handler, selFile2 + File.separator + ImageExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(images), - new ImageExportSettings(export.getValue(ImageExportMode.class)), evl)); - } - - if (export.isOptionEnabled(ShapeExportMode.class)) { - ret.addAll(new ShapeExporter().exportShapes(handler, selFile2 + File.separator + ShapeExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(shapes), - new ShapeExportSettings(export.getValue(ShapeExportMode.class), export.getZoom()), evl)); - } - - if (export.isOptionEnabled(MorphShapeExportMode.class)) { - ret.addAll(new MorphShapeExporter().exportMorphShapes(handler, selFile2 + File.separator + MorphShapeExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(morphshapes), - new MorphShapeExportSettings(export.getValue(MorphShapeExportMode.class), export.getZoom()), evl)); - } - - if (export.isOptionEnabled(TextExportMode.class)) { - ret.addAll(new TextExporter().exportTexts(handler, selFile2 + File.separator + TextExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(texts), - new TextExportSettings(export.getValue(TextExportMode.class), Configuration.textExportSingleFile.get(), export.getZoom()), evl)); - } - - if (export.isOptionEnabled(MovieExportMode.class)) { - ret.addAll(new MovieExporter().exportMovies(handler, selFile2 + File.separator + MovieExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(movies), - new MovieExportSettings(export.getValue(MovieExportMode.class)), evl)); - } - - if (export.isOptionEnabled(SoundExportMode.class)) { - ret.addAll(new SoundExporter().exportSounds(handler, selFile2 + File.separator + SoundExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(sounds), - new SoundExportSettings(export.getValue(SoundExportMode.class)), evl)); - } - - if (export.isOptionEnabled(BinaryDataExportMode.class)) { - ret.addAll(new BinaryDataExporter().exportBinaryData(handler, selFile2 + File.separator + BinaryDataExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(binaryData), - new BinaryDataExportSettings(export.getValue(BinaryDataExportMode.class)), evl)); - } - - if (export.isOptionEnabled(FontExportMode.class)) { - ret.addAll(new FontExporter().exportFonts(handler, selFile2 + File.separator + FontExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(fonts), - new FontExportSettings(export.getValue(FontExportMode.class)), evl)); - } - - if (export.isOptionEnabled(SymbolClassExportMode.class)) { - ret.addAll(new SymbolClassExporter().exportNames(selFile2, new ReadOnlyTagList(symbolNames), evl)); - } - - FrameExporter frameExporter = new FrameExporter(); - - if (export.isOptionEnabled(FrameExportMode.class)) { - FrameExportSettings fes = new FrameExportSettings(export.getValue(FrameExportMode.class), export.getZoom()); - for (Entry> entry : frames.entrySet()) { - int containerId = entry.getKey(); - if (containerId == 0) { - String subFolder = FrameExportSettings.EXPORT_FOLDER_NAME; - ret.addAll(frameExporter.exportFrames(handler, selFile2 + File.separator + subFolder, swf, containerId, entry.getValue(), fes, evl)); - } - } - } - - if (export.isOptionEnabled(SpriteExportMode.class)) { - SpriteExportSettings ses = new SpriteExportSettings(export.getValue(SpriteExportMode.class), export.getZoom()); - for (Entry> entry : frames.entrySet()) { - int containerId = entry.getKey(); - if (containerId != 0) { - String subFolder = SpriteExportSettings.EXPORT_FOLDER_NAME; - ret.addAll(frameExporter.exportFrames(handler, selFile2 + File.separator + subFolder, swf, containerId, entry.getValue(), ses, evl)); - } - } - } - - if (export.isOptionEnabled(ButtonExportMode.class)) { - ButtonExportSettings bes = new ButtonExportSettings(export.getValue(ButtonExportMode.class), export.getZoom()); - for (Tag tag : buttons) { - ButtonTag button = (ButtonTag) tag; - String subFolder = ButtonExportSettings.EXPORT_FOLDER_NAME; - List frameNums = new ArrayList<>(); - frameNums.add(0); // todo: export all frames - ret.addAll(frameExporter.exportFrames(handler, selFile2 + File.separator + subFolder, swf, button.getCharacterId(), frameNums, bes, evl)); - } - } - - if (export.isOptionEnabled(ScriptExportMode.class)) { - if (as3scripts.size() > 0 || as12scripts.size() > 0) { - boolean parallel = Configuration.parallelSpeedUp.get(); - String scriptsFolder = Path.combine(selFile2, ScriptExportSettings.EXPORT_FOLDER_NAME); - Path.createDirectorySafe(new File(scriptsFolder)); - boolean singleScriptFile = Configuration.scriptExportSingleFile.get(); - if (parallel && singleScriptFile) { - logger.log(Level.WARNING, AppStrings.translate("export.script.singleFilePallelModeWarning")); - singleScriptFile = false; - } - - ScriptExportSettings scriptExportSettings = new ScriptExportSettings(export.getValue(ScriptExportMode.class), singleScriptFile); - String singleFileName = Path.combine(scriptsFolder, swf.getShortFileName() + scriptExportSettings.getFileExtension()); - try (FileTextWriter writer = scriptExportSettings.singleFile ? new FileTextWriter(Configuration.getCodeFormatting(), new FileOutputStream(singleFileName)) : null) { - scriptExportSettings.singleFileWriter = writer; - if (swf.isAS3()) { - ret.addAll(new AS3ScriptExporter().exportActionScript3(swf, handler, scriptsFolder, as3scripts, scriptExportSettings, parallel, evl)); - } else { - Map asmsToExport = swf.getASMs(true, as12scripts, false); - ret.addAll(new AS2ScriptExporter().exportAS2Scripts(handler, scriptsFolder, asmsToExport, scriptExportSettings, parallel, evl)); - } - } - } - } - } - - return ret; - } - - public void exportAll(SWF swf, AbortRetryIgnoreHandler handler, String selFile, ExportDialog export) throws IOException, InterruptedException { - boolean exportAll = false; - if (exportAll) { - exportAllDebug(swf, handler, selFile, export); - return; - } - - EventListener evl = swf.getExportEventListener(); - - if (export.isOptionEnabled(ImageExportMode.class)) { - new ImageExporter().exportImages(handler, Path.combine(selFile, ImageExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new ImageExportSettings(export.getValue(ImageExportMode.class)), evl); - } - - if (export.isOptionEnabled(ShapeExportMode.class)) { - new ShapeExporter().exportShapes(handler, Path.combine(selFile, ShapeExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new ShapeExportSettings(export.getValue(ShapeExportMode.class), export.getZoom()), evl); - } - - if (export.isOptionEnabled(MorphShapeExportMode.class)) { - new MorphShapeExporter().exportMorphShapes(handler, Path.combine(selFile, MorphShapeExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new MorphShapeExportSettings(export.getValue(MorphShapeExportMode.class), export.getZoom()), evl); - } - - if (export.isOptionEnabled(TextExportMode.class)) { - new TextExporter().exportTexts(handler, Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new TextExportSettings(export.getValue(TextExportMode.class), Configuration.textExportSingleFile.get(), export.getZoom()), evl); - } - - if (export.isOptionEnabled(MovieExportMode.class)) { - new MovieExporter().exportMovies(handler, Path.combine(selFile, MovieExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new MovieExportSettings(export.getValue(MovieExportMode.class)), evl); - } - - if (export.isOptionEnabled(SoundExportMode.class)) { - new SoundExporter().exportSounds(handler, Path.combine(selFile, SoundExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new SoundExportSettings(export.getValue(SoundExportMode.class)), evl); - } - - if (export.isOptionEnabled(BinaryDataExportMode.class)) { - new BinaryDataExporter().exportBinaryData(handler, Path.combine(selFile, BinaryDataExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new BinaryDataExportSettings(export.getValue(BinaryDataExportMode.class)), evl); - } - - if (export.isOptionEnabled(FontExportMode.class)) { - new FontExporter().exportFonts(handler, Path.combine(selFile, FontExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), - new FontExportSettings(export.getValue(FontExportMode.class)), evl); - } - - if (export.isOptionEnabled(SymbolClassExportMode.class)) { - new SymbolClassExporter().exportNames(selFile, swf.getTags(), evl); - } - - FrameExporter frameExporter = new FrameExporter(); - - if (export.isOptionEnabled(FrameExportMode.class)) { - FrameExportSettings fes = new FrameExportSettings(export.getValue(FrameExportMode.class), export.getZoom()); - frameExporter.exportFrames(handler, Path.combine(selFile, FrameExportSettings.EXPORT_FOLDER_NAME), swf, 0, null, fes, evl); - } - - if (export.isOptionEnabled(SpriteExportMode.class)) { - SpriteExportSettings ses = new SpriteExportSettings(export.getValue(SpriteExportMode.class), export.getZoom()); - for (CharacterTag c : swf.getCharacters().values()) { - if (c instanceof DefineSpriteTag) { - frameExporter.exportFrames(handler, Path.combine(selFile, SpriteExportSettings.EXPORT_FOLDER_NAME), swf, c.getCharacterId(), null, ses, evl); - } - } - } - - if (export.isOptionEnabled(ButtonExportMode.class)) { - ButtonExportSettings bes = new ButtonExportSettings(export.getValue(ButtonExportMode.class), export.getZoom()); - for (CharacterTag c : swf.getCharacters().values()) { - if (c instanceof ButtonTag) { - List frameNums = new ArrayList<>(); - frameNums.add(0); // todo: export all frames - frameExporter.exportFrames(handler, Path.combine(selFile, ButtonExportSettings.EXPORT_FOLDER_NAME), swf, c.getCharacterId(), frameNums, bes, evl); - } - } - } - - if (export.isOptionEnabled(ScriptExportMode.class)) { - boolean parallel = Configuration.parallelSpeedUp.get(); - String scriptsFolder = Path.combine(selFile, ScriptExportSettings.EXPORT_FOLDER_NAME); - Path.createDirectorySafe(new File(scriptsFolder)); - boolean singleScriptFile = Configuration.scriptExportSingleFile.get(); - if (parallel && singleScriptFile) { - logger.log(Level.WARNING, AppStrings.translate("export.script.singleFilePallelModeWarning")); - singleScriptFile = false; - } - - ScriptExportSettings scriptExportSettings = new ScriptExportSettings(export.getValue(ScriptExportMode.class), singleScriptFile); - String singleFileName = Path.combine(scriptsFolder, swf.getShortFileName() + scriptExportSettings.getFileExtension()); - try (FileTextWriter writer = scriptExportSettings.singleFile ? new FileTextWriter(Configuration.getCodeFormatting(), new FileOutputStream(singleFileName)) : null) { - scriptExportSettings.singleFileWriter = writer; - swf.exportActionScript(handler, scriptsFolder, scriptExportSettings, parallel, evl); - } - } - } - - public void exportAllDebug(SWF swf, AbortRetryIgnoreHandler handler, String selFile, ExportDialog export) throws IOException, InterruptedException { - EventListener evl = swf.getExportEventListener(); - - if (export.isOptionEnabled(ImageExportMode.class)) { - for (ImageExportMode exportMode : ImageExportMode.values()) { - new ImageExporter().exportImages(handler, Path.combine(selFile, ImageExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new ImageExportSettings(exportMode), evl); - } - } - - if (export.isOptionEnabled(ShapeExportMode.class)) { - for (ShapeExportMode exportMode : ShapeExportMode.values()) { - new ShapeExporter().exportShapes(handler, Path.combine(selFile, ShapeExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new ShapeExportSettings(exportMode, export.getZoom()), evl); - } - } - - if (export.isOptionEnabled(MorphShapeExportMode.class)) { - for (MorphShapeExportMode exportMode : MorphShapeExportMode.values()) { - new MorphShapeExporter().exportMorphShapes(handler, Path.combine(selFile, MorphShapeExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new MorphShapeExportSettings(exportMode, export.getZoom()), evl); - } - } - - if (export.isOptionEnabled(TextExportMode.class)) { - for (TextExportMode exportMode : TextExportMode.values()) { - new TextExporter().exportTexts(handler, Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new TextExportSettings(exportMode, Configuration.textExportSingleFile.get(), export.getZoom()), evl); - } - } - - if (export.isOptionEnabled(MovieExportMode.class)) { - for (MovieExportMode exportMode : MovieExportMode.values()) { - new MovieExporter().exportMovies(handler, Path.combine(selFile, MovieExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new MovieExportSettings(exportMode), evl); - } - } - - if (export.isOptionEnabled(SoundExportMode.class)) { - for (SoundExportMode exportMode : SoundExportMode.values()) { - new SoundExporter().exportSounds(handler, Path.combine(selFile, SoundExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new SoundExportSettings(exportMode), evl); - } - } - - if (export.isOptionEnabled(BinaryDataExportMode.class)) { - for (BinaryDataExportMode exportMode : BinaryDataExportMode.values()) { - new BinaryDataExporter().exportBinaryData(handler, Path.combine(selFile, BinaryDataExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new BinaryDataExportSettings(exportMode), evl); - } - } - - if (export.isOptionEnabled(FontExportMode.class)) { - for (FontExportMode exportMode : FontExportMode.values()) { - new FontExporter().exportFonts(handler, Path.combine(selFile, FontExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), - new FontExportSettings(exportMode), evl); - } - } - - if (export.isOptionEnabled(SymbolClassExportMode.class)) { - for (SymbolClassExportMode exportMode : SymbolClassExportMode.values()) { - new SymbolClassExporter().exportNames(selFile, swf.getTags(), evl); - } - } - - FrameExporter frameExporter = new FrameExporter(); - - if (export.isOptionEnabled(FrameExportMode.class)) { - for (FrameExportMode exportMode : FrameExportMode.values()) { - FrameExportSettings fes = new FrameExportSettings(exportMode, export.getZoom()); - frameExporter.exportFrames(handler, Path.combine(selFile, FrameExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf, 0, null, fes, evl); - } - } - - if (export.isOptionEnabled(SpriteExportMode.class)) { - for (SpriteExportMode exportMode : SpriteExportMode.values()) { - SpriteExportSettings ses = new SpriteExportSettings(exportMode, export.getZoom()); - for (CharacterTag c : swf.getCharacters().values()) { - if (c instanceof DefineSpriteTag) { - frameExporter.exportFrames(handler, Path.combine(selFile, SpriteExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf, c.getCharacterId(), null, ses, evl); - } - } - } - } - - if (export.isOptionEnabled(ButtonExportMode.class)) { - for (ButtonExportMode exportMode : ButtonExportMode.values()) { - ButtonExportSettings bes = new ButtonExportSettings(exportMode, export.getZoom()); - for (CharacterTag c : swf.getCharacters().values()) { - if (c instanceof ButtonTag) { - List frameNums = new ArrayList<>(); - frameNums.add(0); // todo: export all frames - frameExporter.exportFrames(handler, Path.combine(selFile, ButtonExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf, c.getCharacterId(), frameNums, bes, evl); - } - } - } - } - - if (export.isOptionEnabled(ScriptExportMode.class)) { - boolean parallel = Configuration.parallelSpeedUp.get(); - for (ScriptExportMode exportMode : ScriptExportMode.values()) { - String scriptsFolder = Path.combine(selFile, ScriptExportSettings.EXPORT_FOLDER_NAME, exportMode.name()); - Path.createDirectorySafe(new File(scriptsFolder)); - boolean singleScriptFile = Configuration.scriptExportSingleFile.get(); - if (parallel && singleScriptFile) { - logger.log(Level.WARNING, AppStrings.translate("export.script.singleFilePallelModeWarning")); - singleScriptFile = false; - } - - ScriptExportSettings scriptExportSettings = new ScriptExportSettings(exportMode, singleScriptFile); - String singleFileName = Path.combine(scriptsFolder, swf.getShortFileName() + scriptExportSettings.getFileExtension()); - try (FileTextWriter writer = scriptExportSettings.singleFile ? new FileTextWriter(Configuration.getCodeFormatting(), new FileOutputStream(singleFileName)) : null) { - scriptExportSettings.singleFileWriter = writer; - swf.exportActionScript(handler, scriptsFolder, scriptExportSettings, parallel, evl); - } - } - } - } - - public List getSwfs() { - return swfs; - } - - public SWFList getCurrentSwfList() { - SWF swf = getCurrentSwf(); - if (swf == null) { - return null; - } - - return swf.swfList; - } - - public SWF getCurrentSwf() { - if (swfs == null || swfs.isEmpty()) { - return null; - } - - if (treePanelMode == TreePanelMode.TAG_TREE) { - TreeItem treeNode = (TreeItem) tagTree.getLastSelectedPathComponent(); - if (treeNode == null || treeNode instanceof SWFList) { - return null; - } - - return treeNode.getSwf(); - } else if (treePanelMode == TreePanelMode.DUMP_TREE) { - DumpInfo dumpInfo = (DumpInfo) dumpTree.getLastSelectedPathComponent(); - - if (dumpInfo == null) { - return null; - } - - return DumpInfoSwfNode.getSwfNode(dumpInfo).getSwf(); - } - - return null; - } - - public void gotoFrame(int frame) { - TreeItem treeItem = (TreeItem) tagTree.getLastSelectedPathComponent(); - if (treeItem == null) { - return; - } - if (treeItem instanceof Timelined) { - Timelined t = (Timelined) treeItem; - Frame f = tagTree.getModel().getFrame(treeItem.getSwf(), t, frame); - if (f != null) { - setTagTreeSelectedNode(f); - } - } - } - - public void gotoScriptLine(SWF swf, String scriptName, int line, int classIndex, int traitIndex, int methodIndex) { - gotoScriptName(swf, scriptName); - if (abcPanel != null) { - if (Main.isDebugPCode()) { - if (classIndex != -1) { - boolean classChanged = false; - if (abcPanel.decompiledTextArea.getClassIndex() != classIndex) { - abcPanel.decompiledTextArea.setClassIndex(classIndex); - classChanged = true; - } - if (traitIndex != -10 && (classChanged || abcPanel.decompiledTextArea.lastTraitIndex != traitIndex)) { - abcPanel.decompiledTextArea.gotoTrait(traitIndex); - } - } - abcPanel.detailPanel.methodTraitPanel.methodCodePanel.gotoInstrLine(line); - } else { - abcPanel.decompiledTextArea.gotoLine(line); - } - } else if (actionPanel != null) { - if (Main.isDebugPCode()) { - actionPanel.editor.gotoLine(line); - } else { - actionPanel.decompiledEditor.gotoLine(line); - } - } - refreshBreakPoints(); - - } - - public void refreshBreakPoints() { - if (abcPanel != null) { - abcPanel.decompiledTextArea.refreshMarkers(); - abcPanel.detailPanel.methodTraitPanel.methodCodePanel.refreshMarkers(); - } - if (actionPanel != null) { - actionPanel.decompiledEditor.refreshMarkers(); - actionPanel.editor.refreshMarkers(); - } - } - - /* - public void debuggerBreakAt(SWF swf, String cls, int line) { - View.execInEventDispatchLater(new Runnable() { - - @Override - public void run() { - gotoClassLine(swf, cls, line); - if (abcPanel != null) { - abcPanel.decompiledTextArea.addColorMarker(line, DecompiledEditorPane.FG_IP_COLOR, DecompiledEditorPane.BG_IP_COLOR, DecompiledEditorPane.PRIORITY_IP); - } - } - }); - - }*/ - public void gotoScriptName(SWF swf, String scriptName) { - if (swf == null) { - return; - } - if (swf.isAS3()) { - String rawScriptName = scriptName; - if (rawScriptName.startsWith("#PCODE ")) { - rawScriptName = rawScriptName.substring(rawScriptName.indexOf(';') + 1); - } - - List abcList = swf.getAbcList(); - if (!abcList.isEmpty()) { - ABCPanel abcPanel = getABCPanel(); - abcPanel.setAbc(abcList.get(0).getABC()); - abcPanel.hilightScript(swf, rawScriptName); - } - } else { - String rawScriptName = scriptName; - if (rawScriptName.startsWith("#PCODE ")) { - rawScriptName = rawScriptName.substring("#PCODE ".length()); - } - Map asms = swf.getASMs(true); - if (actionPanel != null && asms.containsKey(rawScriptName)) { - actionPanel.setSource(asms.get(rawScriptName), true); - } - } - } - - public void gotoDocumentClass(SWF swf) { - if (swf == null) { - return; - } - - String documentClass = swf.getDocumentClass(); - if (documentClass != null && !Configuration.dumpView.get()) { - List abcList = swf.getAbcList(); - if (!abcList.isEmpty()) { - ABCPanel abcPanel = getABCPanel(); - for (ABCContainerTag c : abcList) { - if (c.getABC().findClassByName(documentClass) > -1) { - abcPanel.setAbc(c.getABC()); - abcPanel.hilightScript(swf, documentClass); - break; - } - } - } - } - } - - public void disableDecompilationChanged() { - clearAllScriptCache(); - - if (abcPanel != null) { - abcPanel.reload(); - } - - updateClassesList(); - } - - private void clearAllScriptCache() { - for (SWFList swfList : swfs) { - for (SWF swf : swfList) { - swf.clearScriptCache(); - } - } - } - - public void searchInActionScriptOrText(Boolean searchInText, SWF swf) { - SearchDialog searchDialog = new SearchDialog(getMainFrame().getWindow(), false); - if (searchInText != null) { - if (searchInText) { - searchDialog.searchInTextsRadioButton.setSelected(true); - } else { - searchDialog.searchInASRadioButton.setSelected(true); - } - } - - if (searchDialog.showDialog() == AppDialog.OK_OPTION) { - final String txt = searchDialog.searchField.getText(); - if (!txt.isEmpty()) { - if (swf.isAS3()) { - getABCPanel(); - } else { - getActionPanel(); - } - - boolean ignoreCase = searchDialog.ignoreCaseCheckBox.isSelected(); - boolean regexp = searchDialog.regexpCheckBox.isSelected(); - - if (searchDialog.searchInASRadioButton.isSelected()) { - new CancellableWorker() { - @Override - protected Void doInBackground() throws Exception { - List abcResult = null; - List actionResult = null; - if (swf.isAS3()) { - abcResult = getABCPanel().search(swf, txt, ignoreCase, regexp, this); - } else { - actionResult = getActionPanel().search(swf, txt, ignoreCase, regexp, this); - } - - List fAbcResult = abcResult; - List fActionResult = actionResult; - View.execInEventDispatch(() -> { - boolean found = false; - if (fAbcResult != null) { - found = true; - getABCPanel().searchPanel.setSearchText(txt); - SearchResultsDialog sr = new SearchResultsDialog<>(getMainFrame().getWindow(), txt, getABCPanel()); - sr.setResults(fAbcResult); - sr.setVisible(true); - } else if (fActionResult != null) { - found = true; - getActionPanel().searchPanel.setSearchText(txt); - - SearchResultsDialog sr = new SearchResultsDialog<>(getMainFrame().getWindow(), txt, getActionPanel()); - sr.setResults(fActionResult); - sr.setVisible(true); - } - - if (!found) { - View.showMessageDialog(null, translate("message.search.notfound").replace("%searchtext%", txt), translate("message.search.notfound.title"), JOptionPane.INFORMATION_MESSAGE); - } - - Main.stopWork(); - }); - - return null; - } - - @Override - protected void done() { - View.execInEventDispatch(() -> { - Main.stopWork(); - }); - - } - }.execute(); - } else if (searchDialog.searchInTextsRadioButton.isSelected()) { - new CancellableWorker() { - @Override - protected Void doInBackground() throws Exception { - List textResult; - SearchPanel textSearchPanel = previewPanel.getTextPanel().getSearchPanel(); - textSearchPanel.setOptions(ignoreCase, regexp); - textResult = searchText(txt, ignoreCase, regexp, swf); - - List fTextResult = textResult; - View.execInEventDispatch(() -> { - textSearchPanel.setSearchText(txt); - boolean found = textSearchPanel.setResults(fTextResult); - if (!found) { - View.showMessageDialog(null, translate("message.search.notfound").replace("%searchtext%", txt), translate("message.search.notfound.title"), JOptionPane.INFORMATION_MESSAGE); - } - - Main.stopWork(); - }); - - return null; - } - - @Override - protected void done() { - View.execInEventDispatch(() -> { - Main.stopWork(); - }); - - } - }.execute(); - } - } - } - } - - public void replaceText() { - SearchDialog replaceDialog = new SearchDialog(getMainFrame().getWindow(), true); - if (replaceDialog.showDialog() == AppDialog.OK_OPTION) { - final String txt = replaceDialog.searchField.getText(); - if (!txt.isEmpty()) { - final SWF swf = getCurrentSwf(); - - new CancellableWorker() { - @Override - protected Void doInBackground() throws Exception { - int findCount = 0; - boolean ignoreCase = replaceDialog.ignoreCaseCheckBox.isSelected(); - boolean regexp = replaceDialog.regexpCheckBox.isSelected(); - String replacement = replaceDialog.replaceField.getText(); - if (!regexp) { - replacement = Matcher.quoteReplacement(replacement); - } - Pattern pat; - if (regexp) { - pat = Pattern.compile(txt, ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); - } else { - pat = Pattern.compile(Pattern.quote(txt), ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); - } - List textTags = new ArrayList<>(); - for (Tag tag : swf.getTags()) { - if (tag instanceof TextTag) { - textTags.add((TextTag) tag); - } - } - for (TextTag textTag : textTags) { - if (!replaceDialog.replaceInParametersCheckBox.isSelected()) { - List texts = textTag.getTexts(); - boolean found = false; - for (int i = 0; i < texts.size(); i++) { - String text = texts.get(i); - if (pat.matcher(text).find()) { - texts.set(i, text.replaceAll(txt, replacement)); - found = true; - findCount++; - } - } - if (found) { - String[] textArray = texts.toArray(new String[texts.size()]); - textTag.setFormattedText(getMissingCharacterHandler(), textTag.getFormattedText(false).text, textArray); - } - } else { - String text = textTag.getFormattedText(false).text; - if (pat.matcher(text).find()) { - textTag.setFormattedText(getMissingCharacterHandler(), text.replaceAll(txt, replacement), null); - findCount++; - } - } - } - - if (findCount > 0) { - swf.clearImageCache(); - repaintTree(); - } - - return null; - } - }.execute(); - } - } - } - - private List searchText(String txt, boolean ignoreCase, boolean regexp, SWF swf) { - if (txt != null && !txt.isEmpty()) { - List found = new ArrayList<>(); - Pattern pat; - if (regexp) { - pat = Pattern.compile(txt, ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); - } else { - pat = Pattern.compile(Pattern.quote(txt), ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); - } - for (Tag tag : swf.getTags()) { - if (tag instanceof TextTag) { - TextTag textTag = (TextTag) tag; - if (pat.matcher(textTag.getFormattedText(false).text).find()) { - found.add(textTag); - } - } - } - - return found; - } - - return null; - } - - @Override - public void updateSearchPos(TextTag item) { - setTagTreeSelectedNode(item); - previewPanel.getTextPanel().updateSearchPos(); - } - - private void setDumpTreeSelectedNode(DumpInfo dumpInfo) { - DumpTreeModel dtm = (DumpTreeModel) dumpTree.getModel(); - TreePath tp = dtm.getDumpInfoPath(dumpInfo); - if (tp != null) { - dumpTree.setSelectionPath(tp); - dumpTree.scrollPathToVisible(tp); - } else { - showCard(CARDEMPTYPANEL); - } - } - - public void setTagTreeSelectedNode(TreeItem treeItem) { - TagTreeModel ttm = tagTree.getModel(); - TreePath tp = ttm.getTreePath(treeItem); - if (tp != null) { - tagTree.setSelectionPath(tp); - tagTree.scrollPathToVisible(tp); - } else { - showCard(CARDEMPTYPANEL); - } - } - - public void autoDeobfuscateChanged() { - Helper.decompilationErrorAdd = AppStrings.translate(Configuration.autoDeobfuscate.get() ? "deobfuscation.comment.failed" : "deobfuscation.comment.tryenable"); - clearAllScriptCache(); - if (abcPanel != null) { - abcPanel.reload(); - } - reload(true); - updateClassesList(); - } - - public void renameColliding(final SWF swf) { - if (swf == null) { - return; - } - if (confirmExperimental()) { - new CancellableWorker() { - @Override - protected Integer doInBackground() throws Exception { - AbcMultiNameCollisionFixer fixer = new AbcMultiNameCollisionFixer(); - return fixer.fixCollisions(swf); - } - - @Override - protected void onStart() { - Main.startWork(translate("work.renaming.identifiers") + "...", this); - } - - @Override - protected void done() { - View.execInEventDispatch(() -> { - try { - int cnt = get(); - Main.stopWork(); - View.showMessageDialog(null, translate("message.rename.renamed").replace("%count%", Integer.toString(cnt))); - swf.assignClassesToSymbols(); - swf.clearScriptCache(); - if (abcPanel != null) { - abcPanel.reload(); - } - updateClassesList(); - reload(true); - } catch (Exception ex) { - logger.log(Level.SEVERE, "Error during renaming identifiers", ex); - Main.stopWork(); - View.showMessageDialog(null, translate("error.occured").replace("%error%", ex.getClass().getSimpleName())); - } - }); - } - }.execute(); - } - } - - public void renameOneIdentifier(final SWF swf) { - if (swf == null) { - return; - } - - FileAttributesTag fileAttributes = swf.getFileAttributes(); - if (fileAttributes != null && fileAttributes.actionScript3) { - final int multiName = getABCPanel().decompiledTextArea.getMultinameUnderCaret(); - final List abcList = swf.getAbcList(); - if (multiName > 0) { - new CancellableWorker() { - @Override - public Void doInBackground() throws Exception { - renameMultiname(abcList, multiName); - return null; - } - - @Override - protected void onStart() { - Main.startWork(translate("work.renaming") + "...", this); - } - - @Override - protected void done() { - Main.stopWork(); - } - }.execute(); - - } else { - View.showMessageDialog(null, translate("message.rename.notfound.multiname"), translate("message.rename.notfound.title"), JOptionPane.INFORMATION_MESSAGE); - } - } else { - final String identifier = getActionPanel().getStringUnderCursor(); - if (identifier != null) { - new CancellableWorker() { - @Override - public Void doInBackground() throws Exception { - try { - renameIdentifier(swf, identifier); - } catch (InterruptedException ex) { - logger.log(Level.SEVERE, null, ex); - } - return null; - } - - @Override - protected void onStart() { - Main.startWork(translate("work.renaming") + "...", this); - } - - @Override - protected void done() { - Main.stopWork(); - } - }.execute(); - } else { - View.showMessageDialog(null, translate("message.rename.notfound.identifier"), translate("message.rename.notfound.title"), JOptionPane.INFORMATION_MESSAGE); - } - } - } - - public void exportFla(final SWF swf) { - if (swf == null) { - return; - } - JFileChooser fc = new JFileChooser(); - String selDir = Configuration.lastOpenDir.get(); - fc.setCurrentDirectory(new File(selDir)); - if (!selDir.endsWith(File.separator)) { - selDir += File.separator; - } - String fileName = new File(swf.getFile()).getName(); - fileName = fileName.substring(0, fileName.length() - 4) + ".fla"; - fc.setSelectedFile(new File(selDir + fileName)); - List flaFilters = new ArrayList<>(); - List xflFilters = new ArrayList<>(); - List versions = new ArrayList<>(); - boolean isAS3 = swf.isAS3(); - for (int i = FLAVersion.values().length - 1; i >= 0; i--) { - final FLAVersion v = FLAVersion.values()[i]; - if (!isAS3 && v.minASVersion() > 2) { - // This version does not support AS1/2 - } else { - versions.add(v); - FileFilter f = new FileFilter() { - @Override - public boolean accept(File f) { - return f.isDirectory() || (f.getName().toLowerCase().endsWith(".fla")); - } - - @Override - public String getDescription() { - return translate("filter.fla").replace("%version%", v.applicationName()); - } - }; - if (v == FLAVersion.CS6) { - fc.setFileFilter(f); - } else { - fc.addChoosableFileFilter(f); - } - flaFilters.add(f); - f = new FileFilter() { - @Override - public boolean accept(File f) { - return f.isDirectory() || (f.getName().toLowerCase().endsWith(".xfl")); - } - - @Override - public String getDescription() { - return translate("filter.xfl").replace("%version%", v.applicationName()); - } - }; - fc.addChoosableFileFilter(f); - xflFilters.add(f); - } - } - - fc.setAcceptAllFileFilterUsed(false); - JFrame f = new JFrame(); - View.setWindowIcon(f); - if (fc.showSaveDialog(f) == JFileChooser.APPROVE_OPTION) { - Configuration.lastOpenDir.set(Helper.fixDialogFile(fc.getSelectedFile()).getParentFile().getAbsolutePath()); - File sf = Helper.fixDialogFile(fc.getSelectedFile()); - - FileFilter selectedFilter = fc.getFileFilter(); - final boolean compressed = flaFilters.contains(selectedFilter); - String path = sf.getAbsolutePath(); - if (path.endsWith(".fla") || path.endsWith(".xfl")) { - path = path.substring(0, path.length() - 4); - } - path += compressed ? ".fla" : ".xfl"; - final FLAVersion selectedVersion = versions.get(compressed ? flaFilters.indexOf(selectedFilter) : xflFilters.indexOf(selectedFilter)); - final File selfile = new File(path); - new CancellableWorker() { - @Override - protected Void doInBackground() throws Exception { - Helper.freeMem(); - try { - AbortRetryIgnoreHandler errorHandler = new GuiAbortRetryIgnoreHandler(); - if (compressed) { - swf.exportFla(errorHandler, selfile.getAbsolutePath(), new File(swf.getFile()).getName(), ApplicationInfo.APPLICATION_NAME, ApplicationInfo.applicationVerName, ApplicationInfo.version, Configuration.parallelSpeedUp.get(), selectedVersion); - } else { - swf.exportXfl(errorHandler, selfile.getAbsolutePath(), new File(swf.getFile()).getName(), ApplicationInfo.APPLICATION_NAME, ApplicationInfo.applicationVerName, ApplicationInfo.version, Configuration.parallelSpeedUp.get(), selectedVersion); - } - } catch (Exception ex) { - logger.log(Level.SEVERE, "FLA export error", ex); - View.showMessageDialog(null, translate("error.export") + ": " + ex.getClass().getName() + " " + ex.getLocalizedMessage(), translate("error"), JOptionPane.ERROR_MESSAGE); - } - Helper.freeMem(); - return null; - } - - @Override - protected void onStart() { - Main.startWork(translate("work.exporting.fla") + "...", this); - } - - @Override - protected void done() { - if (Configuration.openFolderAfterFlaExport.get()) { - try { - Desktop.getDesktop().open(selfile.getAbsoluteFile().getParentFile()); - } catch (IOException ex) { - logger.log(Level.SEVERE, null, ex); - } - } - - Main.stopWork(); - } - }.execute(); - } - } - - public void importText(final SWF swf) { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); - chooser.setDialogTitle(translate("import.select.directory")); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); - File textsFile = new File(Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME, TextExporter.TEXT_EXPORT_FILENAME_FORMATTED)); - TextImporter textImporter = new TextImporter(getMissingCharacterHandler(), new TextImportErrorHandler() { - // "configuration items" for the current replace only - private final ConfigurationItem showAgainImportError = new ConfigurationItem<>("showAgainImportError", true, true); - - private final ConfigurationItem showAgainInvalidText = new ConfigurationItem<>("showAgainInvalidText", true, true); - - private String getTextTagInfo(TextTag textTag) { - StringBuilder ret = new StringBuilder(); - if (textTag != null) { - ret.append(" TextId: ").append(textTag.getCharacterId()).append(" (").append(String.join(", ", textTag.getTexts())).append(")"); - } - - return ret.toString(); - } - - @Override - public boolean handle(TextTag textTag) { - String msg = translate("error.text.import"); - logger.log(Level.SEVERE, msg + getTextTagInfo(textTag)); - return View.showConfirmDialog(MainPanel.this, msg, translate("error"), JOptionPane.OK_CANCEL_OPTION, showAgainImportError, JOptionPane.OK_OPTION) != JOptionPane.OK_OPTION; - } - - @Override - public boolean handle(TextTag textTag, String message, long line) { - String msg = translate("error.text.invalid.continue").replace("%text%", message).replace("%line%", Long.toString(line)); - logger.log(Level.SEVERE, msg + getTextTagInfo(textTag)); - return View.showConfirmDialog(MainPanel.this, msg, translate("error"), JOptionPane.OK_CANCEL_OPTION, showAgainInvalidText, JOptionPane.OK_OPTION) != JOptionPane.OK_OPTION; - } - }); - - // try to import formatted texts - if (textsFile.exists()) { - textImporter.importTextsSingleFileFormatted(textsFile, swf); - } else { - textsFile = new File(Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME, TextExporter.TEXT_EXPORT_FILENAME_PLAIN)); - // try to import plain texts - if (textsFile.exists()) { - textImporter.importTextsSingleFile(textsFile, swf); - } else { - textImporter.importTextsMultipleFiles(selFile, swf); - } - } - - swf.clearImageCache(); - reload(true); - } - } - - public As3ScriptReplacerInterface getAs3ScriptReplacer() { - As3ScriptReplacerInterface r = As3ScriptReplacerFactory.createByConfig(); - if (!r.isAvailable()) { - if (r instanceof MxmlcAs3ScriptReplacer) { - if (View.showConfirmDialog(null, AppStrings.translate("message.flexpath.notset"), AppStrings.translate("error"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) { - Main.advancedSettings("paths"); - } - } else if (r instanceof FFDecAs3ScriptReplacer) { - if (View.showConfirmDialog(this, AppStrings.translate("message.playerpath.lib.notset"), AppStrings.translate("message.action.playerglobal.title"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) { - Main.advancedSettings("paths"); - } - } else { - //Not translated yet - just in case there are more Script replacers in the future. Unused now. - View.showConfirmDialog(this, "Current script replacer is not available", "Script replacer not available", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE); - } - return null; - } - return r; - } - - public void importScript(final SWF swf) { - As3ScriptReplacerInterface as3ScriptReplacer = getAs3ScriptReplacer(); - if (as3ScriptReplacer == null) { - return; - } - String flexLocation = Configuration.flexSdkLocation.get(); - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); - chooser.setDialogTitle(translate("import.select.directory")); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); - String scriptsFolder = Path.combine(selFile, ScriptExportSettings.EXPORT_FOLDER_NAME); - - int countAs2 = new AS2ScriptImporter().importScripts(scriptsFolder, swf.getASMs(true)); - int countAs3 = new AS3ScriptImporter().importScripts(as3ScriptReplacer, scriptsFolder, swf.getAS3Packs()); - - if (countAs3 > 0) { - updateClassesList(); - } - - View.showMessageDialog(this, translate("import.script.result").replace("%count%", Integer.toString(countAs2 + countAs3))); - if (countAs2 != 0 || countAs3 != 0) { - reload(true); - } - } - } - - public void importSymbolClass(final SWF swf) { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); - chooser.setDialogTitle(translate("import.select.directory")); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); - File importFile = new File(Path.combine(selFile, SymbolClassExporter.SYMBOL_CLASS_EXPORT_FILENAME)); - SymbolClassImporter importer = new SymbolClassImporter(); - - if (importFile.exists()) { - importer.importSymbolClasses(importFile, swf); - } - } - } - - private String selectExportDir() { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); - chooser.setDialogTitle(translate("export.select.directory")); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - final String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); - Configuration.lastExportDir.set(Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath()); - return selFile; - } - return null; - } - - public void export(final boolean onlySel) { - - final SWF swf = getCurrentSwf(); - List sel = tagTree.getAllSelected(); - if (!onlySel) { - sel = null; - } else if (sel.isEmpty()) { - return; - } - final ExportDialog export = new ExportDialog(sel); - if (export.showExportDialog() == AppDialog.OK_OPTION) { - final String selFile = selectExportDir(); - if (selFile != null) { - final long timeBefore = System.currentTimeMillis(); - - new CancellableWorker() { - @Override - public Void doInBackground() throws Exception { - try { - AbortRetryIgnoreHandler errorHandler = new GuiAbortRetryIgnoreHandler(); - if (onlySel) { - exportSelection(errorHandler, selFile, export); - } else { - exportAll(swf, errorHandler, selFile, export); - } - } catch (Exception ex) { - logger.log(Level.SEVERE, "Error during export", ex); - View.showMessageDialog(null, translate("error.export") + ": " + ex.getClass().getName() + " " + ex.getLocalizedMessage()); - } - return null; - } - - @Override - protected void onStart() { - Main.startWork(translate("work.exporting") + "...", this); - } - - @Override - protected void done() { - Main.stopWork(); - long timeAfter = System.currentTimeMillis(); - final long timeMs = timeAfter - timeBefore; - - View.execInEventDispatchLater(() -> { - setStatus(translate("export.finishedin").replace("%time%", Helper.formatTimeSec(timeMs))); - }); - } - }.execute(); - - } - } - } - - public void exportJavaSource() { - List sel = tagTree.getSelected(); - for (TreeItem item : sel) { - if (item instanceof SWF) { - SWF swf = (SWF) item; - final String selFile = selectExportDir(); - if (selFile != null) { - Main.startWork(translate("work.exporting") + "...", null); - - try { - new SwfJavaExporter().exportJavaCode(swf, selFile); - Main.stopWork(); - } catch (IOException ex) { - logger.log(Level.SEVERE, null, ex); - } - } - } - } - } - - public void exportSwfXml() { - List sel = tagTree.getSelected(); - Set swfs = new HashSet<>(); - - for (TreeItem item : sel) { - swfs.add(item.getSwf()); - } - - for (SWF swf : swfs) { - final String selFile = selectExportDir(); - if (selFile != null) { - Main.startWork(translate("work.exporting") + "...", null); - - try { - File outFile = new File(selFile + File.separator + Helper.makeFileName("swf.xml")); - new SwfXmlExporter().exportXml(swf, outFile); - Main.stopWork(); - } catch (IOException ex) { - logger.log(Level.SEVERE, null, ex); - } - } - } - } - - public void importSwfXml() { - List sel = tagTree.getSelected(); - Set swfs = new HashSet<>(); - for (TreeItem item : sel) { - swfs.add(item.getSwf()); - } - if (swfs.size() > 1) { - return; - } - - for (SWF swf : swfs) { - File selectedFile = showImportFileChooser("filter.xml|*.xml"); - if (selectedFile != null) { - File selfile = Helper.fixDialogFile(selectedFile); - String xml = Helper.readTextFile(selfile.getPath()); - try { - new SwfXmlImporter().importSwf(swf, xml); - swf.clearAllCache(); - swf.assignExportNamesToSymbols(); - swf.assignClassesToSymbols(); - refreshTree(swf); - } catch (IOException ex) { - logger.log(Level.SEVERE, null, ex); - } - } - } - } - - public void renameIdentifiers(final SWF swf) { - if (swf == null) { - return; - } - if (confirmExperimental()) { - RenameDialog renameDialog = new RenameDialog(); - if (renameDialog.showRenameDialog() == AppDialog.OK_OPTION) { - final RenameType renameType = renameDialog.getRenameType(); - new CancellableWorker() { - @Override - protected Integer doInBackground() throws Exception { - int cnt = swf.deobfuscateIdentifiers(renameType); - return cnt; - } - - @Override - protected void onStart() { - Main.startWork(translate("work.renaming.identifiers") + "...", this); - } - - @Override - protected void done() { - View.execInEventDispatch(() -> { - try { - int cnt = get(); - Main.stopWork(); - View.showMessageDialog(null, translate("message.rename.renamed").replace("%count%", Integer.toString(cnt))); - swf.assignClassesToSymbols(); - swf.clearScriptCache(); - if (abcPanel != null) { - abcPanel.reload(); - } - updateClassesList(); - reload(true); - } catch (Exception ex) { - logger.log(Level.SEVERE, "Error during renaming identifiers", ex); - Main.stopWork(); - View.showMessageDialog(null, translate("error.occured").replace("%error%", ex.getClass().getSimpleName())); - } - }); - } - }.execute(); - } - } - } - - public void deobfuscate() { - DeobfuscationDialog deobfuscationDialog = new DeobfuscationDialog(); - if (deobfuscationDialog.showDialog() == AppDialog.OK_OPTION) { - DeobfuscationLevel level = DeobfuscationLevel.getByLevel(deobfuscationDialog.codeProcessingLevel.getValue()); - new CancellableWorker() { - @Override - protected Void doInBackground() throws Exception { - try { - ABCPanel abcPanel = getABCPanel(); - if (deobfuscationDialog.processAllCheckbox.isSelected()) { - SWF swf = abcPanel.getSwf(); - swf.deobfuscate(level); - } else { - int bi = abcPanel.detailPanel.methodTraitPanel.methodCodePanel.getBodyIndex(); - DecompiledEditorPane decompiledTextArea = abcPanel.decompiledTextArea; - Trait t = abcPanel.decompiledTextArea.getCurrentTrait(); - ABC abc = abcPanel.abc; - if (bi != -1) { - int scriptIndex = decompiledTextArea.getScriptLeaf().scriptIndex; - int classIndex = decompiledTextArea.getClassIndex(); - boolean isStatic = decompiledTextArea.getIsStatic(); - abc.bodies.get(bi).deobfuscate(level, t, scriptIndex, classIndex, isStatic, ""/*FIXME*/); - } - abcPanel.detailPanel.methodTraitPanel.methodCodePanel.setBodyIndex(decompiledTextArea.getScriptLeaf().getPathScriptName(), bi, abc, t, abcPanel.detailPanel.methodTraitPanel.methodCodePanel.getScriptIndex()); - } - } catch (Exception ex) { - logger.log(Level.SEVERE, "Deobfuscation error", ex); - } - - return null; - } - - @Override - protected void onStart() { - Main.startWork(translate("work.deobfuscating") + "...", this); - } - - @Override - protected void done() { - View.execInEventDispatch(() -> { - Main.stopWork(); - View.showMessageDialog(null, translate("work.deobfuscating.complete")); - - clearAllScriptCache(); - getABCPanel().reload(); - updateClassesList(); - }); - } - }.execute(); - } - } - - public void removeNonScripts(SWF swf) { - if (swf == null) { - return; - } - - List tags = swf.getTags().toArrayList(); - List toRemove = new ArrayList<>(); - for (Tag tag : tags) { - System.out.println(tag.getClass()); - if (!(tag instanceof ABCContainerTag || tag instanceof ASMSource)) { - toRemove.add(tag); - } - } - - swf.removeTags(toRemove, true); - refreshTree(swf); - } - - public void removeExceptSelected(SWF swf) { - if (swf == null) { - return; - } - - List sel = tagTree.getAllSelected(); - Set needed = new HashSet<>(); - for (TreeItem item : sel) { - if (item instanceof CharacterTag) { - CharacterTag characterTag = (CharacterTag) item; - characterTag.getNeededCharactersDeep(needed); - needed.add(characterTag.getCharacterId()); - } - } - - List tagsToRemove = new ArrayList<>(); - for (Tag tag : swf.getTags()) { - if (tag instanceof CharacterTag) { - CharacterTag characterTag = (CharacterTag) tag; - if (!needed.contains(characterTag.getCharacterId())) { - tagsToRemove.add(tag); - } - } - } - - swf.removeTags(tagsToRemove, true); - refreshTree(swf); - } - - private void clear() { - dumpViewPanel.clear(); - previewPanel.clear(); - headerPanel.clear(); - folderPreviewPanel.clear(); - if (abcPanel != null) { - abcPanel.clearSwf(); - } - if (actionPanel != null) { - actionPanel.clearSource(); - } - } - - public void refreshTree() { - refreshTree(new SWF[0]); - } - - public void refreshTree(SWF swf) { - refreshTree(new SWF[]{swf}); - } - - public void refreshTree(SWF[] swfs) { - clear(); - showCard(CARDEMPTYPANEL); - TreeItem treeItem = tagTree.getCurrentTreeItem(); - - tagTree.updateSwfs(swfs); - - if (treeItem != null) { - SWF treeItemSwf = treeItem.getSwf().getRootSwf(); - if (this.swfs.contains(treeItemSwf.swfList)) { - setTagTreeSelectedNode(treeItem); - } - } - - reload(true); - } - - public void refreshDecompiled() { - clearAllScriptCache(); - if (abcPanel != null) { - abcPanel.reload(); - } - - reload(true); - updateClassesList(); - } - - private MissingCharacterHandler getMissingCharacterHandler() { - return new MissingCharacterHandler() { - // "configuration items" for the current replace only - private final ConfigurationItem showAgainIgnoreMissingCharacters = new ConfigurationItem<>("showAgainIgnoreMissingCharacters", true, true); - - private boolean ignoreMissingCharacters = false; - - @Override - public boolean getIgnoreMissingCharacters() { - return ignoreMissingCharacters; - } - - @Override - public boolean handle(TextTag textTag, final FontTag font, final char character) { - String fontName = font.getSwf().sourceFontNamesMap.get(font.getFontId()); - if (fontName == null) { - fontName = font.getFontName(); - } - final Font f = FontTag.installedFontsByName.get(fontName); - if (f == null || !f.canDisplay(character)) { - String msg = translate("error.font.nocharacter").replace("%char%", "" + character); - logger.log(Level.SEVERE, "{0} FontId: {1} TextId: {2}", new Object[]{msg, font.getCharacterId(), textTag.getCharacterId()}); - ignoreMissingCharacters = View.showConfirmDialog(null, msg, translate("error"), - JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, - showAgainIgnoreMissingCharacters, - ignoreMissingCharacters ? JOptionPane.OK_OPTION : JOptionPane.CANCEL_OPTION) == JOptionPane.OK_OPTION; - return false; - } - - font.addCharacter(character, f); - - return true; - } - }; - } - - public boolean saveText(TextTag textTag, String formattedText, String[] texts, LineMarkedEditorPane editor) { - try { - if (textTag.setFormattedText(getMissingCharacterHandler(), formattedText, texts)) { - return true; - } - } catch (TextParseException ex) { - if (editor != null) { - editor.gotoLine((int) ex.line); - editor.markError(); - } - - View.showMessageDialog(null, translate("error.text.invalid").replace("%text%", ex.text).replace("%line%", Long.toString(ex.line)), translate("error"), JOptionPane.ERROR_MESSAGE); - } - - return false; - } - - public boolean alignText(TextTag textTag, TextAlign textAlign) { - return (textTag.alignText(textAlign)); - } - - public boolean translateText(TextTag textTag, int diff) { - return textTag.translateText(diff); - } - - public boolean previousTag() { - if (getCurrentView() == VIEW_RESOURCES) { - if (tagTree.getSelectionRows().length > 0) { - int row = tagTree.getSelectionRows()[0]; - if (row > 0) { - tagTree.setSelectionRow(row - 1); - tagTree.scrollRowToVisible(row - 1); - previewPanel.focusTextPanel(); - } - } - return true; - } - return false; - } - - public boolean nextTag() { - if (getCurrentView() == VIEW_RESOURCES) { - if (tagTree.getSelectionRows().length > 0) { - int row = tagTree.getSelectionRows()[0]; - if (row < tagTree.getRowCount() - 1) { - tagTree.setSelectionRow(row + 1); - tagTree.scrollRowToVisible(row + 1); - previewPanel.focusTextPanel(); - } - } - return true; - } - return false; - } - - public void selectBkColorButtonActionPerformed(ActionEvent evt) { - Color newColor = JColorChooser.showDialog(null, AppStrings.translate("dialog.selectbkcolor.title"), View.getSwfBackgroundColor()); - if (newColor != null) { - View.setSwfBackgroundColor(newColor); - reload(true); - } - } - - public void replaceButtonActionPerformed(ActionEvent evt) { - TreeItem item = tagTree.getCurrentTreeItem(); - if (item == null) { - return; - } - - if (item instanceof DefineSoundTag) { - File selectedFile = showImportFileChooser("filter.sounds|*.mp3;*.wav|filter.sounds.mp3|*.mp3|filter.sounds.wav|*.wav"); - if (selectedFile != null) { - File selfile = Helper.fixDialogFile(selectedFile); - DefineSoundTag ds = (DefineSoundTag) item; - int soundFormat = SoundFormat.FORMAT_UNCOMPRESSED_LITTLE_ENDIAN; - if (selfile.getName().toLowerCase().endsWith(".mp3")) { - soundFormat = SoundFormat.FORMAT_MP3; - } - - boolean ok = false; - try { - ok = ds.setSound(new FileInputStream(selfile), soundFormat); - ds.getSwf().clearSoundCache(); - } catch (IOException ex) { - //ignore - } - - if (!ok) { - View.showMessageDialog(null, translate("error.sound.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); - } else { - reload(true); - } - } - } - if (item instanceof ImageTag) { - ImageTag it = (ImageTag) item; - if (it.importSupported()) { - File selectedFile = showImportFileChooser("filter.images|*.jpg;*.jpeg;*.gif;*.png;*.bmp"); - if (selectedFile != null) { - File selfile = Helper.fixDialogFile(selectedFile); - byte[] data = Helper.readFile(selfile.getAbsolutePath()); - try { - Tag newTag = new ImageImporter().importImage(it, data); - SWF swf = it.getSwf(); - if (newTag != null) { - refreshTree(swf); - setTagTreeSelectedNode(newTag); - } - swf.clearImageCache(); - } catch (IOException ex) { - logger.log(Level.SEVERE, "Invalid image", ex); - View.showMessageDialog(null, translate("error.image.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); - } - - reload(true); - } - } - } - if (item instanceof ShapeTag) { - ShapeTag st = (ShapeTag) item; - String filter = "filter.images|*.jpg;*.jpeg;*.gif;*.png;*.bmp;*.svg"; - File selectedFile = showImportFileChooser(filter); - if (selectedFile != null) { - File selfile = Helper.fixDialogFile(selectedFile); - byte[] data = null; - String svgText = null; - if (".svg".equals(Path.getExtension(selfile))) { - svgText = Helper.readTextFile(selfile.getAbsolutePath()); - showSvgImportWarning(); - } else { - data = Helper.readFile(selfile.getAbsolutePath()); - } - try { - Tag newTag = svgText != null ? new SvgImporter().importSvg(st, svgText) : new ShapeImporter().importImage(st, data); - SWF swf = st.getSwf(); - if (newTag != null) { - refreshTree(swf); - setTagTreeSelectedNode(newTag); - } - - swf.clearImageCache(); - } catch (IOException ex) { - logger.log(Level.SEVERE, "Invalid image", ex); - View.showMessageDialog(null, translate("error.image.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); - } - reload(true); - } - } - if (item instanceof DefineBinaryDataTag) { - DefineBinaryDataTag bt = (DefineBinaryDataTag) item; - File selectedFile = showImportFileChooser(""); - if (selectedFile != null) { - File selfile = Helper.fixDialogFile(selectedFile); - byte[] data = Helper.readFile(selfile.getAbsolutePath()); - new BinaryDataImporter().importData(bt, data); - refreshTree(bt.getSwf()); - reload(true); - } - } - } - - public void replaceNoFillButtonActionPerformed(ActionEvent evt) { - TreeItem item = tagTree.getCurrentTreeItem(); - if (item == null) { - return; - } - - if (item instanceof ShapeTag) { - ShapeTag st = (ShapeTag) item; - String filter = "filter.images|*.jpg;*.jpeg;*.gif;*.png;*.bmp;*.svg"; - File selectedFile = showImportFileChooser(filter); - if (selectedFile != null) { - File selfile = Helper.fixDialogFile(selectedFile); - byte[] data = null; - String svgText = null; - if (".svg".equals(Path.getExtension(selfile))) { - svgText = Helper.readTextFile(selfile.getAbsolutePath()); - showSvgImportWarning(); - } else { - data = Helper.readFile(selfile.getAbsolutePath()); - } - try { - Tag newTag = svgText != null ? new SvgImporter().importSvg(st, svgText, false) : new ShapeImporter().importImage(st, data, 0, false); - SWF swf = st.getSwf(); - if (newTag != null) { - refreshTree(swf); - setTagTreeSelectedNode(newTag); - } - - swf.clearImageCache(); - } catch (IOException ex) { - logger.log(Level.SEVERE, "Invalid image", ex); - View.showMessageDialog(null, translate("error.image.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); - } - reload(true); - } - } - } - - private void showSvgImportWarning() { - View.showMessageDialog(null, AppStrings.translate("message.warning.svgImportExperimental"), AppStrings.translate("message.warning"), JOptionPane.WARNING_MESSAGE, Configuration.warningSvgImport); - } - - public void replaceAlphaButtonActionPerformed(ActionEvent evt) { - TreeItem item = tagTree.getCurrentTreeItem(); - if (item == null) { - return; - } - - if (item instanceof DefineBitsJPEG3Tag || item instanceof DefineBitsJPEG4Tag) { - ImageTag it = (ImageTag) item; - if (it.importSupported()) { - File selectedFile = showImportFileChooser(""); - if (selectedFile != null) { - File selfile = Helper.fixDialogFile(selectedFile); - byte[] data = Helper.readFile(selfile.getAbsolutePath()); - try { - new ImageImporter().importImageAlpha(it, data); - SWF swf = it.getSwf(); - swf.clearImageCache(); - } catch (IOException ex) { - logger.log(Level.SEVERE, "Invalid alpha channel data", ex); - View.showMessageDialog(null, translate("error.image.alpha.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); - } - - reload(true); - } - } - } - } - - public void exportJavaSourceActionPerformed(ActionEvent evt) { - if (Main.isWorking()) { - return; - } - - exportJavaSource(); - } - - public void exportSwfXmlActionPerformed(ActionEvent evt) { - if (Main.isWorking()) { - return; - } - - exportSwfXml(); - } - - public void importSwfXmlActionPerformed(ActionEvent evt) { - if (Main.isWorking()) { - return; - } - - importSwfXml(); - } - - public void exportSelectionActionPerformed(ActionEvent evt) { - if (Main.isWorking()) { - return; - } - - export(true); - } - - public File showImportFileChooser(String filter) { - String[] filterArray = filter.length() > 0 ? filter.split("\\|") : new String[0]; - - JFileChooser fc = new JFileChooser(); - fc.setCurrentDirectory(new File(Configuration.lastOpenDir.get())); - boolean first = true; - for (int i = 0; i < filterArray.length; i += 2) { - final String filterName = filterArray[i]; - final String[] extensions = filterArray[i + 1].split(";"); - for (int j = 0; j < extensions.length; j++) { - if (extensions[j].startsWith("*.")) { - extensions[j] = extensions[j].substring(1); - } - } - FileFilter ff = new FileFilter() { - @Override - public boolean accept(File f) { - if (f.isDirectory()) { - return true; - } - String fileName = f.getName().toLowerCase(); - for (String ext : extensions) { - if (fileName.endsWith(ext)) { - return true; - } - } - return false; - } - - @Override - public String getDescription() { - StringBuilder extStr = new StringBuilder(); - boolean first = true; - for (String ext : extensions) { - if (first) { - first = false; - } else { - extStr.append(","); - } - - extStr.append("*").append(ext); - } - - return translate(filterName).replace("%extensions%", extStr); - } - }; - if (first) { - fc.setFileFilter(ff); - } else { - fc.addChoosableFileFilter(ff); - } - first = false; - } - - JFrame f = new JFrame(); - View.setWindowIcon(f); - if (fc.showOpenDialog(f) == JFileChooser.APPROVE_OPTION) { - File result = fc.getSelectedFile(); - Configuration.lastOpenDir.set(Helper.fixDialogFile(result).getParentFile().getAbsolutePath()); - return result; - } - - return null; - } - - private void showDetail(String card) { - CardLayout cl = (CardLayout) (detailPanel.getLayout()); - cl.show(detailPanel, card); - if (card.equals(DETAILCARDEMPTYPANEL)) { - if (detailPanel.isVisible()) { - detailPanel.setVisible(false); - } - } else if (!detailPanel.isVisible()) { - detailPanel.setVisible(true); - } - } - - private void showCard(String card) { - CardLayout cl = (CardLayout) (displayPanel.getLayout()); - cl.show(displayPanel, card); - } - - @Override - public void valueChanged(TreeSelectionEvent e) { - Object source = e.getSource(); - TreeItem treeItem = (TreeItem) e.getPath().getLastPathComponent(); - - if (!(treeItem instanceof SWFList)) { - SWF swf = treeItem.getSwf(); - if (swfs.isEmpty()) { - // show welcome panel after closing swfs - updateUi(); - } else { - if (swf == null) { - swf = swfs.get(0).get(0); - } - - updateUi(swf); - } - } else { - updateUi(); - } - - reload(false); - - if (source == dumpTree) { - Tag t = null; - if (treeItem instanceof DumpInfo) { - DumpInfo di = (DumpInfo) treeItem; - t = di.getTag(); - } - - showPreview(t, dumpPreviewPanel); - } - } - - public void unloadFlashPlayer() { - if (flashPanel != null) { - try { - flashPanel.close(); - } catch (IOException ex) { - // ignore - } - } - if (flashPanel2 != null) { - try { - flashPanel2.close(); - } catch (IOException ex) { - // ignore - } - } - } - - public void clearDebuggerColors() { - if (abcPanel != null) { - abcPanel.decompiledTextArea.removeColorMarkerOnAllLines(DecompiledEditorPane.IP_MARKER); - abcPanel.detailPanel.methodTraitPanel.methodCodePanel.clearDebuggerColors(); - } - if (actionPanel != null) { - actionPanel.decompiledEditor.removeColorMarkerOnAllLines(DecompiledEditorPane.IP_MARKER); - actionPanel.editor.removeColorMarkerOnAllLines(DecompiledEditorPane.IP_MARKER); - } - } - - private void stopFlashPlayer() { - if (flashPanel != null) { - if (!flashPanel.isStopped()) { - flashPanel.stopSWF(); - } - } - if (flashPanel2 != null) { - if (!flashPanel2.isStopped()) { - flashPanel2.stopSWF(); - } - } - } - - public boolean isInternalFlashViewerSelected() { - return mainMenu.isInternalFlashViewerSelected(); - } - - public static final int VIEW_RESOURCES = 0; - - public static final int VIEW_DUMP = 1; - - public static final int VIEW_TIMELINE = 2; - - private int getCurrentView() { - return Configuration.dumpView.get() ? VIEW_DUMP : VIEW_RESOURCES; - } - - public void setTreeModel(int view) { - switch (view) { - case VIEW_DUMP: - if (dumpTree.getModel() == null) { - DumpTreeModel dtm = new DumpTreeModel(swfs); - dumpTree.setModel(dtm); - dumpTree.expandFirstLevelNodes(); - } - break; - case VIEW_RESOURCES: - if (tagTree.getModel() == null) { - TagTreeModel ttm = new TagTreeModel(swfs, Configuration.tagTreeShowEmptyFolders.get()); - tagTree.setModel(ttm); - tagTree.expandFirstLevelNodes(); - } - break; - } - } - - private JPanel createDumpViewCard() { - JPanel r = new JPanel(new BorderLayout()); - r.add(new JPersistentSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(dumpTree), dumpPreviewPanel, Configuration.guiDumpSplitPaneDividerLocationPercent), BorderLayout.CENTER); - return r; - } - - private JPanel createResourcesViewCard() { - JPanel r = new JPanel(new BorderLayout()); - r.add(new JScrollPane(tagTree), BorderLayout.CENTER); - r.add(searchPanel, BorderLayout.SOUTH); - return r; - } - - public boolean showView(int view) { - - CardLayout cl = (CardLayout) (contentPanel.getLayout()); - CardLayout cl2 = (CardLayout) (treePanel.getLayout()); - - setTreeModel(view); - switch (view) { - case VIEW_DUMP: - if (!isWelcomeScreen) { - cl.show(contentPanel, SPLIT_PANE1); - } - cl2.show(treePanel, DUMP_VIEW); - treePanelMode = TreePanelMode.DUMP_TREE; - showDetail(DETAILCARDEMPTYPANEL); - reload(true); - return true; - case VIEW_RESOURCES: - if (!isWelcomeScreen) { - cl.show(contentPanel, SPLIT_PANE1); - } - cl2.show(treePanel, RESOURCES_VIEW); - - treePanelMode = TreePanelMode.TAG_TREE; - - treePanel.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - tagTree.scrollPathToVisible(tagTree.getSelectionPath()); - } - }); - - reload(true); - return true; - case VIEW_TIMELINE: - final SWF swf = getCurrentSwf(); - if (swf != null) { - TreeItem item = tagTree.getCurrentTreeItem(); - if (item instanceof TagScript) { - item = ((TagScript) item).getTag(); - } - if (item instanceof Timelined) { - timelineViewPanel.setTimelined((Timelined) item); - } else if (item instanceof Frame) { - timelineViewPanel.setTimelined(((Frame) item).timeline.timelined); - } else { - timelineViewPanel.setTimelined(swf); - } - cl.show(contentPanel, TIMELINE_PANEL); - return true; - } - return false; - } - return false; - - } - - private void dumpViewReload(boolean forceReload) { - showDetail(DETAILCARDEMPTYPANEL); - - DumpInfo dumpInfo = (DumpInfo) dumpTree.getLastSelectedPathComponent(); - if (dumpInfo == null) { - showCard(CARDEMPTYPANEL); - return; - } - - dumpViewPanel.revalidate(); - dumpViewPanel.setSelectedNode(dumpInfo); - showCard(CARDDUMPVIEW); - } - - public void loadFromBinaryTag(final DefineBinaryDataTag binaryDataTag) { - loadFromBinaryTag(Arrays.asList(binaryDataTag)); - } - - public void loadFromBinaryTag(final List binaryDataTags) { - - Main.loadingDialog.setVisible(true); - new CancellableWorker() { - @Override - protected Void doInBackground() throws Exception { - try { - for (DefineBinaryDataTag binaryDataTag : binaryDataTags) { - try { - InputStream is = new ByteArrayInputStream(binaryDataTag.binaryData.getRangeData()); - SWF bswf = new SWF(is, null, "(SWF Data)", new ProgressListener() { - @Override - public void progress(int p) { - Main.loadingDialog.setPercent(p); - } - }, Configuration.parallelSpeedUp.get()); - binaryDataTag.innerSwf = bswf; - bswf.binaryData = binaryDataTag; - } catch (IOException ex) { - //ignore - } - } - } catch (InterruptedException ex) { - //ignore - } - - return null; - } - - @Override - protected void onStart() { - Main.startWork(AppStrings.translate("work.reading.swf") + "...", this); - } - - @Override - protected void done() { - View.execInEventDispatch(() -> { - Main.loadingDialog.setVisible(false); - Main.stopWork(); - }); - } - }.execute(); - } - - private void closeTag() { - previewPanel.closeTag(); - } - - public void showPreview(TreeItem treeItem, PreviewPanel previewPanel) { - previewPanel.clear(); - if (treeItem == null) { - previewPanel.showEmpty(); - return; - } - boolean internalViewer = isInternalFlashViewerSelected(); - if (treeItem instanceof SWF) { - SWF swf = (SWF) treeItem; - if (internalViewer) { - previewPanel.showImagePanel(swf, swf, -1); - } else { - previewPanel.setParametersPanelVisible(false); - if (flashPanel != null) { //same for flashPanel2 - previewPanel.showFlashViewerPanel(); - previewPanel.showSwf(swf); - } - } - } else if (treeItem instanceof MetadataTag) { - MetadataTag metadataTag = (MetadataTag) treeItem; - previewPanel.showMetaDataPanel(metadataTag); - } else if (treeItem instanceof DefineBinaryDataTag) { - DefineBinaryDataTag binaryTag = (DefineBinaryDataTag) treeItem; - previewPanel.showBinaryPanel(binaryTag); - } else if (treeItem instanceof ImageTag) { - ImageTag imageTag = (ImageTag) treeItem; - previewPanel.setImageReplaceButtonVisible(!((Tag) imageTag).isReadOnly() && imageTag.importSupported(), imageTag instanceof DefineBitsJPEG3Tag || imageTag instanceof DefineBitsJPEG4Tag); - previewPanel.showImagePanel(imageTag.getImageCached()); - - } else if ((treeItem instanceof DrawableTag) && (!(treeItem instanceof TextTag)) && (!(treeItem instanceof FontTag)) && internalViewer) { - final Tag tag = (Tag) treeItem; - DrawableTag d = (DrawableTag) tag; - Timelined timelined; - if (treeItem instanceof Timelined && !(treeItem instanceof ButtonTag)) { - timelined = (Timelined) tag; - } else { - timelined = makeTimelined(tag); - } - - previewPanel.setParametersPanelVisible(false); - previewPanel.showImagePanel(timelined, tag.getSwf(), -1); - } else if (treeItem instanceof Frame && internalViewer) { - Frame fn = (Frame) treeItem; - SWF swf = fn.getSwf(); - previewPanel.showImagePanel(fn.timeline.timelined, swf, fn.frame); - } else if ((treeItem instanceof SoundTag)) { //&& isInternalFlashViewerSelected() && (Arrays.asList("mp3", "wav").contains(((SoundTag) tagObj).getExportFormat())))) { - previewPanel.showImagePanel(new SerializableImage(View.loadImage("sound32"))); - previewPanel.setImageReplaceButtonVisible(((Tag) treeItem).isReadOnly() && (treeItem instanceof DefineSoundTag), false); - try { - SoundTagPlayer soundThread = new SoundTagPlayer((SoundTag) treeItem, Configuration.loopMedia.get() ? Integer.MAX_VALUE : 1, true); - previewPanel.setMedia(soundThread); - } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) { - logger.log(Level.SEVERE, null, ex); - } - - } else if ((treeItem instanceof FontTag) && internalViewer) { - previewPanel.showFontPanel((FontTag) treeItem); - } else if ((treeItem instanceof TextTag) && internalViewer) { - previewPanel.showTextPanel((TextTag) treeItem); - } else if ((treeItem instanceof Frame) || (treeItem instanceof CharacterTag) || (treeItem instanceof FontTag) || (treeItem instanceof SoundStreamHeadTypeTag)) { - previewPanel.createAndShowTempSwf(treeItem); - - if (treeItem instanceof TextTag) { - previewPanel.showTextPanel((TextTag) treeItem); - } else if (treeItem instanceof FontTag) { - previewPanel.showFontPanel((FontTag) treeItem); - } else { - previewPanel.setParametersPanelVisible(false); - } - } else { - previewPanel.showEmpty(); - } - } - - public void reload(boolean forceReload) { - tagTree.scrollPathToVisible(tagTree.getSelectionPath()); - if (Configuration.dumpView.get()) { - dumpViewReload(forceReload); - return; - } - - TreeItem treeItem = null; - TreePath treePath = tagTree.getSelectionPath(); - if (treePath != null && tagTree.getModel().treePathExists(treePath)) { - treeItem = (TreeItem) treePath.getLastPathComponent(); - } - - // save last selected node to config - if (treeItem != null) { - SWF swf = treeItem.getSwf(); - if (swf != null) { - swf = swf.getRootSwf(); - } - - if (swf != null) { - SwfSpecificConfiguration swfConf = Configuration.getOrCreateSwfSpecificConfiguration(swf.getShortFileName()); - swfConf.lastSelectedPath = tagTree.getSelectionPathString(); - } - } - - if (!forceReload && (treeItem == oldItem)) { - return; - } - - if (oldItem != treeItem) { - closeTag(); - } - - oldItem = treeItem; - - // show the preview of the tag when the user clicks to the tagname inside the scripts node, too - // this is a little bit inconsistent, beacuse the frames (FrameScript) are not shown - boolean preferScript = false; - if (treeItem instanceof TagScript) { - treeItem = ((TagScript) treeItem).getTag(); - preferScript = true; - } - - folderPreviewPanel.clear(); - previewPanel.clear(); - stopFlashPlayer(); - - previewPanel.setImageReplaceButtonVisible(false, false); - - boolean internalViewer = isInternalFlashViewerSelected(); - - if (treeItem instanceof ScriptPack) { - final ScriptPack scriptLeaf = (ScriptPack) treeItem; - if (setSourceWorker != null) { - setSourceWorker.cancel(true); - setSourceWorker = null; - } - if (!Main.isInited() || !Main.isWorking() || Main.isDebugging()) { - ABCPanel abcPanel = getABCPanel(); - CancellableWorker worker = new CancellableWorker() { - @Override - protected Void doInBackground() throws Exception { - abcPanel.detailPanel.methodTraitPanel.methodCodePanel.clear(); - abcPanel.setAbc(scriptLeaf.abc); - abcPanel.decompiledTextArea.setScript(scriptLeaf, true); - abcPanel.decompiledTextArea.setNoTrait(); - return null; - } - - @Override - protected void onStart() { - Main.startWork(translate("work.decompiling") + "...", this); - } - - @Override - protected void done() { - View.execInEventDispatch(() -> { - setSourceWorker = null; - try { - get(); - } catch (CancellationException ex) { - abcPanel.decompiledTextArea.setText("// " + AppStrings.translate("work.canceled")); - } catch (Exception ex) { - logger.log(Level.SEVERE, "Error", ex); - getABCPanel().decompiledTextArea.setText("// " + AppStrings.translate("decompilationError") + ": " + ex); - } - - Main.stopWork(); - }); - } - }; - - worker.execute(); - setSourceWorker = worker; - } - - showDetail(DETAILCARDAS3NAVIGATOR); - showCard(CARDACTIONSCRIPT3PANEL); - return; - } - - if (treeItem instanceof Tag) { - Tag tag = (Tag) treeItem; - TagInfo tagInfo = new TagInfo(); - tag.getTagInfo(tagInfo); - if (!tagInfo.isEmpty()) { - tagInfoPanel.setTagInfos(tagInfo); - showDetail(DETAILCARDTAGINFO); - } else { - showDetail(DETAILCARDEMPTYPANEL); - } - } else { - showDetail(DETAILCARDEMPTYPANEL); - } - - if (treeItem instanceof HeaderItem) { - headerPanel.load(((HeaderItem) treeItem).getSwf()); - showCard(CARDHEADER); - } else if (treeItem instanceof FolderItem) { - showFolderPreview((FolderItem) treeItem); - } else if (treeItem instanceof SWF) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if (treeItem instanceof MetadataTag) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if (treeItem instanceof DefineBinaryDataTag) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if (treeItem instanceof ASMSource && (!(treeItem instanceof DrawableTag) || preferScript)) { - getActionPanel().setSource((ASMSource) treeItem, !forceReload); - showCard(CARDACTIONSCRIPTPANEL); - } else if (treeItem instanceof ImageTag) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if ((treeItem instanceof DrawableTag) && (!(treeItem instanceof TextTag)) && (!(treeItem instanceof FontTag)) && internalViewer) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if ((treeItem instanceof FontTag) && internalViewer) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if ((treeItem instanceof TextTag) && internalViewer) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if (treeItem instanceof Frame && internalViewer) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if ((treeItem instanceof SoundTag)) { //&& isInternalFlashViewerSelected() && (Arrays.asList("mp3", "wav").contains(((SoundTag) tagObj).getExportFormat())))) { - showPreview(treeItem, previewPanel); - showCard(CARDPREVIEWPANEL); - } else if ((treeItem instanceof Frame) || (treeItem instanceof CharacterTag) || (treeItem instanceof FontTag) || (treeItem instanceof SoundStreamHeadTypeTag)) { - showPreview(treeItem, previewPanel); - - showCard(CARDPREVIEWPANEL); - } else if (treeItem instanceof Tag) { - showGenericTag((Tag) treeItem); - } else { - showCard(CARDEMPTYPANEL); - } - } - - public void repaintTree() { - tagTree.repaint(); - reload(true); - } - - public void showGenericTag(Tag tag) { - previewPanel.showGenericTagPanel(tag); - showCard(CARDPREVIEWPANEL); - } - - public void showTextTagWithNewValue(TextTag textTag, TextTag newTextTag) { - - previewPanel.showTextComparePanel(textTag, newTextTag); - } - - private void showFolderPreview(FolderItem item) { - List folderPreviewItems = new ArrayList<>(); - String folderName = item.getName(); - SWF swf = item.swf; - switch (folderName) { - case TagTreeModel.FOLDER_SHAPES: - for (Tag tag : swf.getTags()) { - if (tag instanceof ShapeTag) { - folderPreviewItems.add(tag); - } - } - break; - case TagTreeModel.FOLDER_MORPHSHAPES: - for (Tag tag : swf.getTags()) { - if (tag instanceof MorphShapeTag) { - folderPreviewItems.add(tag); - } - } - break; - case TagTreeModel.FOLDER_SPRITES: - for (Tag tag : swf.getTags()) { - if (tag instanceof DefineSpriteTag) { - folderPreviewItems.add(tag); - } - } - break; - case TagTreeModel.FOLDER_BUTTONS: - for (Tag tag : swf.getTags()) { - if (tag instanceof ButtonTag) { - folderPreviewItems.add(tag); - } - } - break; - case TagTreeModel.FOLDER_FONTS: - for (Tag tag : swf.getTags()) { - if (tag instanceof FontTag) { - folderPreviewItems.add(tag); - } - } - break; - case TagTreeModel.FOLDER_FRAMES: - for (Frame frame : swf.getTimeline().getFrames()) { - folderPreviewItems.add(frame); - } - break; - case TagTreeModel.FOLDER_IMAGES: - for (Tag tag : swf.getTags()) { - if (tag instanceof ImageTag) { - folderPreviewItems.add(tag); - } - } - break; - case TagTreeModel.FOLDER_TEXTS: - for (Tag tag : swf.getTags()) { - if (tag instanceof TextTag) { - folderPreviewItems.add(tag); - } - } - break; - } - - folderPreviewPanel.setItems(folderPreviewItems); - showCard(CARDFOLDERPREVIEWPANEL); - } - - private boolean isFreeing; - - @Override - public boolean isFreeing() { - return isFreeing; - } - - @Override - public void free() { - isFreeing = true; - } - - public void setErrorState(ErrorState errorState) { - statusPanel.setErrorState(errorState); - } - - public static Timelined makeTimelined(final Tag tag) { - return makeTimelined(tag, -1); - } - - public static Timelined makeTimelined(final Tag tag, final int fontFrameNum) { - - return new Timelined() { - private Timeline tim; - - @Override - public Timeline getTimeline() { - if (tim == null) { - Timeline timeline = new Timeline(tag.getSwf(), this, ((CharacterTag) tag).getCharacterId(), getRect()); - initTimeline(timeline); - tim = timeline; - } - - return tim; - } - - @Override - public void resetTimeline() { - if (tim != null) { - tim.reset(tag.getSwf(), this, ((CharacterTag) tag).getCharacterId(), getRect()); - initTimeline(tim); - } - } - - private void initTimeline(Timeline timeline) { - if (tag instanceof MorphShapeTag) { - timeline.frameRate = MORPH_SHAPE_ANIMATION_FRAME_RATE; - int framesCnt = (int) (timeline.frameRate * MORPH_SHAPE_ANIMATION_LENGTH); - for (int i = 0; i < framesCnt; i++) { - Frame f = new Frame(timeline, i); - DepthState ds = new DepthState(tag.getSwf(), f); - ds.characterId = ((CharacterTag) tag).getCharacterId(); - ds.matrix = new MATRIX(); - ds.ratio = i * 65535 / framesCnt; - f.layers.put(1, ds); - f.layersChanged = true; - timeline.addFrame(f); - } - } else if (tag instanceof FontTag) { - int pageCount = PreviewPanel.getFontPageCount((FontTag) tag); - int frame = fontFrameNum; - if (frame < 0 || frame >= pageCount) { - frame = 0; - } - - Frame f = new Frame(timeline, 0); - DepthState ds = new DepthState(tag.getSwf(), f); - ds.characterId = ((CharacterTag) tag).getCharacterId(); - ds.matrix = new MATRIX(); - f.layers.put(1, ds); - f.layersChanged = true; - timeline.addFrame(f); - timeline.fontFrameNum = frame; - } else { - Frame f = new Frame(timeline, 0); - DepthState ds = new DepthState(tag.getSwf(), f); - ds.characterId = ((CharacterTag) tag).getCharacterId(); - ds.matrix = new MATRIX(); - f.layers.put(1, ds); - timeline.addFrame(f); - } - timeline.displayRect = getRect(); - } - - @Override - public RECT getRect() { - return getRect(new HashSet<>()); - } - - @Override - public RECT getRect(Set added) { - BoundedTag bt = (BoundedTag) tag; - if (!added.contains(bt)) { - return bt.getRect(added); - } - return new RECT(Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE); - } - - @Override - public int hashCode() { - return tag.hashCode(); - } - - @Override - public void setModified(boolean value) { - } - - @Override - public ReadOnlyTagList getTags() { - return ReadOnlyTagList.EMPTY; - } - - @Override - public void removeTag(int index) { - } - - @Override - public void removeTag(Tag tag) { - } - - @Override - public void addTag(Tag tag) { - } - - @Override - public void addTag(int index, Tag tag) { - } - - @Override - public void replaceTag(int index, Tag newTag) { - } - }; - } - - private void disposeInner(Container container) { - for (Component c : container.getComponents()) { - if (c instanceof Container) { - Container c2 = (Container) c; - disposeInner(c2); - } - } - - container.removeAll(); - container.setLayout(null); - if (container instanceof TagEditorPanel) { - Helper.emptyObject(container); - } - } - - public void dispose() { - setDropTarget(null); - disposeInner(this); - Helper.emptyObject(this); - } -} +/* + * Copyright (C) 2010-2016 JPEXS + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.jpexs.decompiler.flash.gui; + +import com.jpexs.decompiler.flash.AbortRetryIgnoreHandler; +import com.jpexs.decompiler.flash.ApplicationInfo; +import com.jpexs.decompiler.flash.EventListener; +import com.jpexs.decompiler.flash.ReadOnlyTagList; +import com.jpexs.decompiler.flash.SWF; +import com.jpexs.decompiler.flash.SWFBundle; +import com.jpexs.decompiler.flash.SWFSourceInfo; +import com.jpexs.decompiler.flash.abc.ABC; +import com.jpexs.decompiler.flash.abc.RenameType; +import com.jpexs.decompiler.flash.abc.ScriptPack; +import com.jpexs.decompiler.flash.abc.avm2.AVM2ConstantPool; +import com.jpexs.decompiler.flash.abc.avm2.deobfuscation.AbcMultiNameCollisionFixer; +import com.jpexs.decompiler.flash.abc.avm2.deobfuscation.DeobfuscationLevel; +import com.jpexs.decompiler.flash.abc.types.traits.Trait; +import com.jpexs.decompiler.flash.configuration.Configuration; +import com.jpexs.decompiler.flash.configuration.ConfigurationItem; +import com.jpexs.decompiler.flash.configuration.SwfSpecificConfiguration; +import com.jpexs.decompiler.flash.dumpview.DumpInfo; +import com.jpexs.decompiler.flash.dumpview.DumpInfoSwfNode; +import com.jpexs.decompiler.flash.exporters.BinaryDataExporter; +import com.jpexs.decompiler.flash.exporters.FontExporter; +import com.jpexs.decompiler.flash.exporters.FrameExporter; +import com.jpexs.decompiler.flash.exporters.ImageExporter; +import com.jpexs.decompiler.flash.exporters.MorphShapeExporter; +import com.jpexs.decompiler.flash.exporters.MovieExporter; +import com.jpexs.decompiler.flash.exporters.ShapeExporter; +import com.jpexs.decompiler.flash.exporters.SoundExporter; +import com.jpexs.decompiler.flash.exporters.SymbolClassExporter; +import com.jpexs.decompiler.flash.exporters.TextExporter; +import com.jpexs.decompiler.flash.exporters.modes.BinaryDataExportMode; +import com.jpexs.decompiler.flash.exporters.modes.ButtonExportMode; +import com.jpexs.decompiler.flash.exporters.modes.FontExportMode; +import com.jpexs.decompiler.flash.exporters.modes.FrameExportMode; +import com.jpexs.decompiler.flash.exporters.modes.ImageExportMode; +import com.jpexs.decompiler.flash.exporters.modes.MorphShapeExportMode; +import com.jpexs.decompiler.flash.exporters.modes.MovieExportMode; +import com.jpexs.decompiler.flash.exporters.modes.ScriptExportMode; +import com.jpexs.decompiler.flash.exporters.modes.ShapeExportMode; +import com.jpexs.decompiler.flash.exporters.modes.SoundExportMode; +import com.jpexs.decompiler.flash.exporters.modes.SpriteExportMode; +import com.jpexs.decompiler.flash.exporters.modes.SymbolClassExportMode; +import com.jpexs.decompiler.flash.exporters.modes.TextExportMode; +import com.jpexs.decompiler.flash.exporters.script.AS2ScriptExporter; +import com.jpexs.decompiler.flash.exporters.script.AS3ScriptExporter; +import com.jpexs.decompiler.flash.exporters.settings.BinaryDataExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.ButtonExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.FontExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.FrameExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.ImageExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.MorphShapeExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.MovieExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.ScriptExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.ShapeExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.SoundExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.SpriteExportSettings; +import com.jpexs.decompiler.flash.exporters.settings.TextExportSettings; +import com.jpexs.decompiler.flash.exporters.swf.SwfJavaExporter; +import com.jpexs.decompiler.flash.exporters.swf.SwfXmlExporter; +import com.jpexs.decompiler.flash.flexsdk.MxmlcAs3ScriptReplacer; +import com.jpexs.decompiler.flash.gui.abc.ABCPanel; +import com.jpexs.decompiler.flash.gui.abc.ABCPanelSearchResult; +import com.jpexs.decompiler.flash.gui.abc.ClassesListTreeModel; +import com.jpexs.decompiler.flash.gui.abc.DecompiledEditorPane; +import com.jpexs.decompiler.flash.gui.abc.DeobfuscationDialog; +import com.jpexs.decompiler.flash.gui.action.ActionPanel; +import com.jpexs.decompiler.flash.gui.action.ActionSearchResult; +import com.jpexs.decompiler.flash.gui.controls.JPersistentSplitPane; +import com.jpexs.decompiler.flash.gui.dumpview.DumpTree; +import com.jpexs.decompiler.flash.gui.dumpview.DumpTreeModel; +import com.jpexs.decompiler.flash.gui.dumpview.DumpViewPanel; +import com.jpexs.decompiler.flash.gui.editor.LineMarkedEditorPane; +import com.jpexs.decompiler.flash.gui.helpers.ObservableList; +import com.jpexs.decompiler.flash.gui.player.FlashPlayerPanel; +import com.jpexs.decompiler.flash.gui.tagtree.TagTree; +import com.jpexs.decompiler.flash.gui.tagtree.TagTreeModel; +import com.jpexs.decompiler.flash.gui.timeline.TimelineViewPanel; +import com.jpexs.decompiler.flash.helpers.FileTextWriter; +import com.jpexs.decompiler.flash.helpers.Freed; +import com.jpexs.decompiler.flash.importers.AS2ScriptImporter; +import com.jpexs.decompiler.flash.importers.AS3ScriptImporter; +import com.jpexs.decompiler.flash.importers.As3ScriptReplacerFactory; +import com.jpexs.decompiler.flash.importers.As3ScriptReplacerInterface; +import com.jpexs.decompiler.flash.importers.BinaryDataImporter; +import com.jpexs.decompiler.flash.importers.FFDecAs3ScriptReplacer; +import com.jpexs.decompiler.flash.importers.ImageImporter; +import com.jpexs.decompiler.flash.importers.ShapeImporter; +import com.jpexs.decompiler.flash.importers.SwfXmlImporter; +import com.jpexs.decompiler.flash.importers.SymbolClassImporter; +import com.jpexs.decompiler.flash.importers.TextImporter; +import com.jpexs.decompiler.flash.importers.svg.SvgImporter; +import com.jpexs.decompiler.flash.tags.ABCContainerTag; +import com.jpexs.decompiler.flash.tags.DefineBinaryDataTag; +import com.jpexs.decompiler.flash.tags.DefineBitsJPEG3Tag; +import com.jpexs.decompiler.flash.tags.DefineBitsJPEG4Tag; +import com.jpexs.decompiler.flash.tags.DefineSoundTag; +import com.jpexs.decompiler.flash.tags.DefineSpriteTag; +import com.jpexs.decompiler.flash.tags.DoActionTag; +import com.jpexs.decompiler.flash.tags.DoInitActionTag; +import com.jpexs.decompiler.flash.tags.FileAttributesTag; +import com.jpexs.decompiler.flash.tags.MetadataTag; +import com.jpexs.decompiler.flash.tags.Tag; +import com.jpexs.decompiler.flash.tags.TagInfo; +import com.jpexs.decompiler.flash.tags.base.ASMSource; +import com.jpexs.decompiler.flash.tags.base.BoundedTag; +import com.jpexs.decompiler.flash.tags.base.ButtonTag; +import com.jpexs.decompiler.flash.tags.base.CharacterTag; +import com.jpexs.decompiler.flash.tags.base.DrawableTag; +import com.jpexs.decompiler.flash.tags.base.FontTag; +import com.jpexs.decompiler.flash.tags.base.ImageTag; +import com.jpexs.decompiler.flash.tags.base.MissingCharacterHandler; +import com.jpexs.decompiler.flash.tags.base.MorphShapeTag; +import com.jpexs.decompiler.flash.tags.base.ShapeTag; +import com.jpexs.decompiler.flash.tags.base.SoundStreamHeadTypeTag; +import com.jpexs.decompiler.flash.tags.base.SoundTag; +import com.jpexs.decompiler.flash.tags.base.SymbolClassTypeTag; +import com.jpexs.decompiler.flash.tags.base.TextImportErrorHandler; +import com.jpexs.decompiler.flash.tags.base.TextTag; +import com.jpexs.decompiler.flash.tags.text.TextAlign; +import com.jpexs.decompiler.flash.tags.text.TextParseException; +import com.jpexs.decompiler.flash.timeline.DepthState; +import com.jpexs.decompiler.flash.timeline.Frame; +import com.jpexs.decompiler.flash.timeline.TagScript; +import com.jpexs.decompiler.flash.timeline.Timeline; +import com.jpexs.decompiler.flash.timeline.Timelined; +import com.jpexs.decompiler.flash.treeitems.FolderItem; +import com.jpexs.decompiler.flash.treeitems.HeaderItem; +import com.jpexs.decompiler.flash.treeitems.SWFList; +import com.jpexs.decompiler.flash.treeitems.TreeItem; +import com.jpexs.decompiler.flash.types.MATRIX; +import com.jpexs.decompiler.flash.types.RECT; +import com.jpexs.decompiler.flash.types.sound.SoundFormat; +import com.jpexs.decompiler.flash.xfl.FLAVersion; +import com.jpexs.helpers.CancellableWorker; +import com.jpexs.helpers.Helper; +import com.jpexs.helpers.Path; +import com.jpexs.helpers.ProgressListener; +import com.jpexs.helpers.SerializableImage; +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Desktop; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DragSourceDragEvent; +import java.awt.dnd.DragSourceDropEvent; +import java.awt.dnd.DragSourceEvent; +import java.awt.dnd.DragSourceListener; +import java.awt.dnd.DropTarget; +import java.awt.dnd.DropTargetDropEvent; +import java.awt.event.ActionEvent; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.UnsupportedAudioFileException; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JColorChooser; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.UIManager; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.filechooser.FileFilter; +import javax.swing.plaf.basic.BasicTreeUI; +import javax.swing.tree.DefaultTreeSelectionModel; +import javax.swing.tree.TreePath; +import jsyntaxpane.DefaultSyntaxKit; + +/** + * + * @author JPEXS + */ +public final class MainPanel extends JPanel implements TreeSelectionListener, SearchListener, Freed { + + private final MainFrame mainFrame; + + private final ObservableList swfs; + + private final JPanel welcomePanel; + + private final TimelineViewPanel timelineViewPanel; + + private final MainFrameStatusPanel statusPanel; + + private final MainFrameMenu mainMenu; + + private final JProgressBar progressBar = new JProgressBar(0, 100); + + public TagTree tagTree; + + public DumpTree dumpTree; + + private final FlashPlayerPanel flashPanel; + + private final FlashPlayerPanel flashPanel2; + + private final JPanel contentPanel; + + private final JPanel displayPanel; + + public FolderPreviewPanel folderPreviewPanel; + + private boolean isWelcomeScreen = true; + + private static final String CARDPREVIEWPANEL = "Preview card"; + + private static final String CARDFOLDERPREVIEWPANEL = "Folder preview card"; + + private static final String CARDEMPTYPANEL = "Empty card"; + + private static final String CARDDUMPVIEW = "Dump view"; + + private static final String CARDACTIONSCRIPTPANEL = "ActionScript card"; + + private static final String CARDACTIONSCRIPT3PANEL = "ActionScript3 card"; + + private static final String CARDHEADER = "Header card"; + + private static final String DETAILCARDAS3NAVIGATOR = "Traits list"; + + private static final String DETAILCARDTAGINFO = "Tag information"; + + private static final String DETAILCARDEMPTYPANEL = "Empty card"; + + private static final String SPLIT_PANE1 = "SPLITPANE1"; + + private static final String WELCOME_PANEL = "WELCOMEPANEL"; + + private static final String TIMELINE_PANEL = "TIMELINEPANEL"; + + private static final String RESOURCES_VIEW = "RESOURCES"; + + private static final String DUMP_VIEW = "DUMP"; + + private static final String TIMELINE_VIEW = "TIMELINE"; + + private final JPersistentSplitPane splitPane1; + + private final JPersistentSplitPane splitPane2; + + private JPanel detailPanel; + + private JTextField filterField = new MyTextField(""); + + private JPanel searchPanel; + + private ABCPanel abcPanel; + + private ActionPanel actionPanel; + + private final PreviewPanel previewPanel; + + private final HeaderInfoPanel headerPanel; + + private DumpViewPanel dumpViewPanel; + + private final JPanel treePanel; + + private final PreviewPanel dumpPreviewPanel; + + private final TagInfoPanel tagInfoPanel; + + private TreePanelMode treePanelMode; + + private CancellableWorker setSourceWorker; + + public TreeItem oldItem; + + // play morph shape in 2 second(s) + public static final int MORPH_SHAPE_ANIMATION_LENGTH = 2; + + public static final int MORPH_SHAPE_ANIMATION_FRAME_RATE = 30; + + private static final Logger logger = Logger.getLogger(MainPanel.class.getName()); + + public void setPercent(int percent) { + progressBar.setValue(percent); + progressBar.setVisible(true); + } + + public void hidePercent() { + if (progressBar.isVisible()) { + progressBar.setVisible(false); + } + } + + public MainFrame getMainFrame() { + return mainFrame; + } + + static { + try { + File.createTempFile("temp", ".swf").delete(); //First call to this is slow, so make it first + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + + public void updateMenu() { + mainMenu.updateComponents(); + } + + private static void addTab(JTabbedPane tabbedPane, Component tab, String title, Icon icon) { + tabbedPane.add(tab); + + JLabel lbl = new JLabel(title); + lbl.setIcon(icon); + lbl.setIconTextGap(5); + lbl.setHorizontalTextPosition(SwingConstants.RIGHT); + + tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, lbl); + } + + public void setStatus(String s) { + statusPanel.setStatus(s); + } + + public void setWorkStatus(String s, CancellableWorker worker) { + statusPanel.setWorkStatus(s, worker); + mainMenu.updateComponents(); + } + + private JPanel createWelcomePanel() { + JPanel welcomePanel = new JPanel(); + welcomePanel.setLayout(new BoxLayout(welcomePanel, BoxLayout.Y_AXIS)); + JLabel welcomeToLabel = new JLabel(translate("startup.welcometo")); + welcomeToLabel.setFont(welcomeToLabel.getFont().deriveFont(40)); + welcomeToLabel.setAlignmentX(0.5f); + JPanel appNamePanel = new JPanel(new FlowLayout()); + JLabel jpLabel = new JLabel("JPEXS "); + jpLabel.setAlignmentX(0.5f); + jpLabel.setForeground(new Color(0, 0, 160)); + jpLabel.setFont(new Font("Tahoma", Font.BOLD, 50)); + jpLabel.setHorizontalAlignment(SwingConstants.CENTER); + appNamePanel.add(jpLabel); + + JLabel ffLabel = new JLabel("Free Flash "); + ffLabel.setAlignmentX(0.5f); + ffLabel.setFont(new Font("Tahoma", Font.BOLD, 50)); + ffLabel.setHorizontalAlignment(SwingConstants.CENTER); + appNamePanel.add(ffLabel); + + JLabel decLabel = new JLabel("Decompiler"); + decLabel.setAlignmentX(0.5f); + decLabel.setForeground(Color.red); + decLabel.setFont(new Font("Tahoma", Font.BOLD, 50)); + decLabel.setHorizontalAlignment(SwingConstants.CENTER); + appNamePanel.add(decLabel); + appNamePanel.setAlignmentX(0.5f); + welcomePanel.add(Box.createGlue()); + welcomePanel.add(welcomeToLabel); + welcomePanel.add(appNamePanel); + JLabel startLabel = new JLabel(translate("startup.selectopen")); + startLabel.setAlignmentX(0.5f); + startLabel.setFont(startLabel.getFont().deriveFont(30)); + welcomePanel.add(startLabel); + welcomePanel.add(Box.createGlue()); + return welcomePanel; + } + + private JPanel createFolderPreviewCard() { + JPanel folderPreviewCard = new JPanel(new BorderLayout()); + folderPreviewPanel = new FolderPreviewPanel(this, new ArrayList<>()); + folderPreviewCard.add(new JScrollPane(folderPreviewPanel), BorderLayout.CENTER); + + return folderPreviewCard; + } + + private JPanel createDumpPreviewCard() { + JPanel dumpViewCard = new JPanel(new BorderLayout()); + dumpViewPanel = new DumpViewPanel(dumpTree); + dumpViewCard.add(new JScrollPane(dumpViewPanel), BorderLayout.CENTER); + + return dumpViewCard; + } + + public String translate(String key) { + return mainFrame.translate(key); + } + + public MainPanel(MainFrame mainFrame, MainFrameMenu mainMenu, FlashPlayerPanel flashPanel, FlashPlayerPanel previewFlashPanel) { + super(); + + this.mainFrame = mainFrame; + this.mainMenu = mainMenu; + this.flashPanel = flashPanel; + this.flashPanel2 = previewFlashPanel; + + mainFrame.setTitle(ApplicationInfo.applicationVerName); + + setLayout(new BorderLayout()); + swfs = new ObservableList<>(); + + detailPanel = new JPanel(); + detailPanel.setLayout(new CardLayout()); + + JPanel whitePanel = new JPanel(); + whitePanel.setBackground(Color.white); + detailPanel.add(whitePanel, DETAILCARDEMPTYPANEL); + + tagInfoPanel = new TagInfoPanel(this); + detailPanel.add(tagInfoPanel, DETAILCARDTAGINFO); + + UIManager.getDefaults().put("TreeUI", BasicTreeUI.class.getName()); + tagTree = new TagTree(null, this); + tagTree.addTreeSelectionListener(this); + tagTree.setSelectionModel(new DefaultTreeSelectionModel() { + private boolean isModified() { + if (abcPanel != null && abcPanel.isEditing()) { + abcPanel.tryAutoSave(); + } + + if (actionPanel != null && actionPanel.isEditing()) { + actionPanel.tryAutoSave(); + } + + if (previewPanel.isEditing()) { + previewPanel.tryAutoSave(); + } + + if (headerPanel.isEditing()) { + headerPanel.tryAutoSave(); + } + + return (abcPanel != null && abcPanel.isEditing()) + || (actionPanel != null && actionPanel.isEditing()) + || previewPanel.isEditing() || headerPanel.isEditing(); + } + + @Override + public void addSelectionPath(TreePath path) { + if (isModified()) { + return; + } + + super.addSelectionPath(path); + } + + @Override + public void addSelectionPaths(TreePath[] paths) { + if (isModified()) { + return; + } + + super.addSelectionPaths(paths); + } + + @Override + public void setSelectionPath(TreePath path) { + if (isModified()) { + return; + } + + super.setSelectionPath(path); + } + + @Override + public void setSelectionPaths(TreePath[] pPaths) { + if (isModified()) { + return; + } + + super.setSelectionPaths(pPaths); + } + + @Override + public void clearSelection() { + if (isModified()) { + return; + } + + super.clearSelection(); + } + + public void setSelection(TreePath[] selection) { + if (isModified()) { + return; + } + + this.selection = selection; + } + + @Override + public void removeSelectionPath(TreePath path) { + if (isModified()) { + return; + } + + super.removeSelectionPath(path); + } + + @Override + public void removeSelectionPaths(TreePath[] paths) { + if (isModified()) { + return; + } + + super.removeSelectionPaths(paths); + } + }); + + DragSource dragSource = DragSource.getDefaultDragSource(); + dragSource.createDefaultDragGestureRecognizer(tagTree, DnDConstants.ACTION_COPY_OR_MOVE, new DragGestureListener() { + @Override + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(DragSource.DefaultCopyDrop, new Transferable() { + @Override + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[]{DataFlavor.javaFileListFlavor}; + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return flavor.equals(DataFlavor.javaFileListFlavor); + } + + @Override + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { + if (flavor.equals(DataFlavor.javaFileListFlavor)) { + List files; + String tempDir = System.getProperty("java.io.tmpdir"); + if (!tempDir.endsWith(File.separator)) { + tempDir += File.separator; + } + Random rnd = new Random(); + tempDir += "ffdec" + File.separator + "export" + File.separator + System.currentTimeMillis() + "_" + rnd.nextInt(1000); + File fTempDir = new File(tempDir); + Path.createDirectorySafe(fTempDir); + + File ftemp = new File(tempDir); + ExportDialog exd = new ExportDialog(null); + try { + files = exportSelection(new GuiAbortRetryIgnoreHandler(), tempDir, exd); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, null, ex); + return null; + } + + files.clear(); + + File[] fs = ftemp.listFiles(); + files.addAll(Arrays.asList(fs)); + + Main.stopWork(); + + for (File f : files) { + f.deleteOnExit(); + } + new File(tempDir).deleteOnExit(); + return files; + + } + return null; + } + }, new DragSourceListener() { + @Override + public void dragEnter(DragSourceDragEvent dsde) { + enableDrop(false); + } + + @Override + public void dragOver(DragSourceDragEvent dsde) { + } + + @Override + public void dropActionChanged(DragSourceDragEvent dsde) { + } + + @Override + public void dragExit(DragSourceEvent dse) { + } + + @Override + public void dragDropEnd(DragSourceDropEvent dsde) { + enableDrop(true); + } + }); + } + }); + + tagTree.createContextMenu(); + + dumpTree = new DumpTree(null, this); + dumpTree.addTreeSelectionListener(this); + dumpTree.createContextMenu(); + + statusPanel = new MainFrameStatusPanel(this); + add(statusPanel, BorderLayout.SOUTH); + + displayPanel = new JPanel(new CardLayout()); + + DefaultSyntaxKit.initKit(); + previewPanel = new PreviewPanel(this, flashPanel); + + dumpPreviewPanel = new PreviewPanel(this, previewFlashPanel); + dumpPreviewPanel.setReadOnly(true); + + displayPanel.add(previewPanel, CARDPREVIEWPANEL); + displayPanel.add(createFolderPreviewCard(), CARDFOLDERPREVIEWPANEL); + displayPanel.add(createDumpPreviewCard(), CARDDUMPVIEW); + + headerPanel = new HeaderInfoPanel(); + displayPanel.add(headerPanel, CARDHEADER); + + displayPanel.add(new JPanel(), CARDEMPTYPANEL); + showCard(CARDEMPTYPANEL); + + searchPanel = new JPanel(); + searchPanel.setLayout(new BorderLayout()); + searchPanel.add(filterField, BorderLayout.CENTER); + searchPanel.add(new JLabel(View.getIcon("search16")), BorderLayout.WEST); + JLabel closeSearchButton = new JLabel(View.getIcon("cancel16")); + closeSearchButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + closeTagTreeSearch(); + } + }); + searchPanel.add(closeSearchButton, BorderLayout.EAST); + searchPanel.setVisible(false); + treePanel = new JPanel(new CardLayout()); + treePanel.add(createResourcesViewCard(), RESOURCES_VIEW); + treePanel.add(createDumpViewCard(), DUMP_VIEW); + //treePanel.add(searchPanel, BorderLayout.SOUTH); + //searchPanel.setVisible(false); + filterField.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void changedUpdate(DocumentEvent e) { + warn(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + warn(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + warn(); + } + + public void warn() { + doFilter(); + } + }); + + //displayPanel.setBorder(BorderFactory.createLineBorder(Color.black)); + splitPane2 = new JPersistentSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, detailPanel, Configuration.guiSplitPane2DividerLocationPercent); + splitPane1 = new JPersistentSplitPane(JSplitPane.HORIZONTAL_SPLIT, splitPane2, displayPanel, Configuration.guiSplitPane1DividerLocationPercent); + + welcomePanel = createWelcomePanel(); + add(welcomePanel, BorderLayout.CENTER); + + timelineViewPanel = new TimelineViewPanel(); + + CardLayout cl3 = new CardLayout(); + contentPanel = new JPanel(cl3); + contentPanel.add(welcomePanel, WELCOME_PANEL); + contentPanel.add(splitPane1, SPLIT_PANE1); + contentPanel.add(timelineViewPanel, TIMELINE_PANEL); + add(contentPanel); + cl3.show(contentPanel, WELCOME_PANEL); + + tagTree.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if ((e.getKeyCode() == 'F') && (e.isControlDown())) { + searchPanel.setVisible(true); + filterField.requestFocusInWindow(); + } + } + }); + detailPanel.setVisible(false); + + updateUi(); + + this.swfs.addCollectionChangedListener((e) -> { + TagTreeModel ttm = tagTree.getModel(); + if (ttm != null) { + if (getCurrentSwf() == null) { + tagTree.setSelectionPath(ttm.getTreePath(ttm.getRoot())); + } + ttm.updateSwfs(e); + tagTree.expandRoot(); + tagTree.expandFirstLevelNodes(); + } + + DumpTreeModel dtm = dumpTree.getModel(); + if (dtm != null) { + List> expandedNodes = View.getExpandedNodes(dumpTree); + dtm.updateSwfs(); + View.expandTreeNodes(dumpTree, expandedNodes); + dumpTree.expandRoot(); + dumpTree.expandFirstLevelNodes(); + } + + if (swfs.isEmpty()) { + tagTree.setUI(new BasicTreeUI() { + { + setHashColor(Color.gray); + } + }); + dumpTree.setUI(new BasicTreeUI() { + { + setHashColor(Color.gray); + } + }); + } + }); + + //Opening files with drag&drop to main window + enableDrop(true); + } + + public void closeTagTreeSearch() { + filterField.setText(""); + doFilter(); + searchPanel.setVisible(false); + } + + public void loadSwfAtPos(SWFList newSwfs, int index) { + previewPanel.clear(); + swfs.set(index, newSwfs); + SWF swf = newSwfs.size() > 0 ? newSwfs.get(0) : null; + if (swf != null) { + updateUi(swf); + } + + doFilter(); + reload(false); + } + + public void load(SWFList newSwfs, boolean first) { + + previewPanel.clear(); + + swfs.add(newSwfs); + SWF swf = newSwfs.size() > 0 ? newSwfs.get(0) : null; + if (swf != null) { + updateUi(swf); + } + + doFilter(); + reload(false); + } + + private ABCPanel getABCPanel() { + if (abcPanel == null) { + abcPanel = new ABCPanel(this); + displayPanel.add(abcPanel, CARDACTIONSCRIPT3PANEL); + detailPanel.add(abcPanel.tabbedPane, DETAILCARDAS3NAVIGATOR); + } + + return abcPanel; + } + + private ActionPanel getActionPanel() { + if (actionPanel == null) { + actionPanel = new ActionPanel(MainPanel.this); + displayPanel.add(actionPanel, CARDACTIONSCRIPTPANEL); + } + + return actionPanel; + } + + private void updateUi(final SWF swf) { + + mainFrame.setTitle(ApplicationInfo.applicationVerName + (Configuration.displayFileName.get() ? " - " + swf.getFileTitle() : "")); + + List abcList = swf.getAbcList(); + + boolean hasAbc = !abcList.isEmpty(); + + if (hasAbc) { + getABCPanel().setAbc(abcList.get(0).getABC()); + } + + if (isWelcomeScreen) { + CardLayout cl = (CardLayout) (contentPanel.getLayout()); + cl.show(contentPanel, SPLIT_PANE1); + isWelcomeScreen = false; + } + + mainMenu.updateComponents(swf); + } + + private void updateUi() { + if (!isWelcomeScreen && swfs.isEmpty()) { + CardLayout cl = (CardLayout) (contentPanel.getLayout()); + cl.show(contentPanel, WELCOME_PANEL); + isWelcomeScreen = true; + closeTagTreeSearch(); + } + + mainFrame.setTitle(ApplicationInfo.applicationVerName); + mainMenu.updateComponents(null); + + showView(getCurrentView()); + } + + private boolean closeConfirmation(SWFList swfList) { + String message = swfList == null + ? translate("message.confirm.closeAll") + : translate("message.confirm.close").replace("{swfName}", swfList.toString()); + + return View.showConfirmDialog(this, message, translate("message.warning"), JOptionPane.OK_CANCEL_OPTION, Configuration.showCloseConfirmation, JOptionPane.OK_OPTION) == JOptionPane.OK_OPTION; + } + + public boolean isModified() { + for (SWFList swfList : swfs) { + for (SWF swf : swfList) { + if (swf.isModified()) { + return true; + } + } + } + + return false; + } + + public boolean closeAll(boolean showCloseConfirmation) { + if (showCloseConfirmation && isModified()) { + boolean closeConfirmResult = closeConfirmation(swfs.size() == 1 ? swfs.get(0) : null); + if (!closeConfirmResult) { + return false; + } + } + + List swfsLists = new ArrayList<>(swfs); + swfs.clear(); + oldItem = null; + clear(); + updateUi(); + + for (SWFList swfList : swfsLists) { + List swfs2 = new ArrayList<>(swfList); + for (SWF swf : swfs2) { + swf.clearTagSwfs(); + } + } + + return true; + } + + public boolean close(SWFList swfList) { + boolean modified = false; + for (SWF swf : swfList) { + if (swf.isModified()) { + modified = true; + } + } + + if (modified) { + boolean closeConfirmResult = closeConfirmation(swfList); + if (!closeConfirmResult) { + return false; + } + } + + swfs.remove(swfList); + oldItem = null; + clear(); + updateUi(); + + List swfs2 = new ArrayList<>(swfList); + for (SWF swf : swfs2) { + swf.clearTagSwfs(); + } + + return true; + } + + public void enableDrop(boolean value) { + if (value) { + setDropTarget(new DropTarget() { + @Override + public synchronized void drop(DropTargetDropEvent dtde) { + try { + dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); + @SuppressWarnings("unchecked") + List droppedFiles = (List) dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); + if (!droppedFiles.isEmpty()) { + SWFSourceInfo[] sourceInfos = new SWFSourceInfo[droppedFiles.size()]; + for (int i = 0; i < droppedFiles.size(); i++) { + sourceInfos[i] = new SWFSourceInfo(null, droppedFiles.get(i).getAbsolutePath(), null); + } + Main.openFile(sourceInfos, null); + } + } catch (UnsupportedFlavorException | IOException ex) { + } + } + }); + } else { + setDropTarget(null); + } + } + + public void updateClassesList() { + List nodes = getASTreeNodes(tagTree); + boolean updateNeeded = false; + for (TreeItem n : nodes) { + if (n instanceof ClassesListTreeModel) { + ((ClassesListTreeModel) n).update(); + updateNeeded = true; + } + } + + refreshTree(); + + if (updateNeeded) { + tagTree.updateUI(); + } + } + + public void doFilter() { + List nodes = getASTreeNodes(tagTree); + for (TreeItem n : nodes) { + if (n instanceof ClassesListTreeModel) { + String filterText = filterField.getText(); + ((ClassesListTreeModel) n).setFilter(filterText); + TagTreeModel tm = tagTree.getModel(); + TreePath path = tm.getTreePath(n); + tm.updateNode(path); + if (!filterText.isEmpty()) { + View.expandTreeNodes(tagTree, path, true); + } + } + } + } + + public void renameIdentifier(SWF swf, String identifier) throws InterruptedException { + String oldName = identifier; + String newName = View.showInputDialog(translate("rename.enternew"), oldName); + if (newName != null) { + if (!oldName.equals(newName)) { + swf.renameAS2Identifier(oldName, newName); + View.showMessageDialog(null, translate("rename.finished.identifier")); + updateClassesList(); + reload(true); + } + } + } + + public void renameMultiname(List abcList, int multiNameIndex) { + String oldName = ""; + AVM2ConstantPool constants = getABCPanel().abc.constants; + if (constants.getMultiname(multiNameIndex).name_index > 0) { + oldName = constants.getString(constants.getMultiname(multiNameIndex).name_index); + } + + String newName = View.showInputDialog(translate("rename.enternew"), oldName); + if (newName != null) { + if (!oldName.equals(newName)) { + int mulCount = 0; + for (ABCContainerTag cnt : abcList) { + ABC abc = cnt.getABC(); + for (int m = 1; m < abc.constants.getMultinameCount(); m++) { + int ni = abc.constants.getMultiname(m).name_index; + String n = ""; + if (ni > 0) { + n = abc.constants.getString(ni); + } + if (n.equals(oldName)) { + abc.renameMultiname(m, newName); + mulCount++; + } + } + } + + View.showMessageDialog(null, translate("rename.finished.multiname").replace("%count%", Integer.toString(mulCount))); + if (abcPanel != null) { + abcPanel.reload(); + } + + updateClassesList(); + reload(true); + ABCPanel abcPanel = getABCPanel(); + abcPanel.hilightScript(abcPanel.getSwf(), abcPanel.decompiledTextArea.getScriptLeaf().getClassPath().toRawString()); + } + } + } + + public List getASTreeNodes(TagTree tree) { + List result = new ArrayList<>(); + TagTreeModel tm = (TagTreeModel) tree.getModel(); + if (tm == null) { + return result; + } + TreeItem root = tm.getRoot(); + for (int i = 0; i < tm.getChildCount(root); i++) { + // first level node can be SWF and SWFBundle + TreeItem node = tm.getChild(root, i); + if (node instanceof SWFBundle) { + for (int j = 0; j < tm.getChildCount(node); j++) { + // child of SWFBundle should be SWF + SWF swfNode = (SWF) tm.getChild(node, j); + result.add(tm.getScriptsNode(swfNode)); + } + } else if (node instanceof SWF) { + SWF swfNode = (SWF) tm.getChild(root, i); + result.add(tm.getScriptsNode(swfNode)); + } + } + return result; + } + + public boolean confirmExperimental() { + return View.showConfirmDialog(null, translate("message.confirm.experimental"), translate("message.warning"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION; + } + + public List exportSelection(AbortRetryIgnoreHandler handler, String selFile, ExportDialog export) throws IOException, InterruptedException { + + List ret = new ArrayList<>(); + List sel = folderPreviewPanel.selectedItems.isEmpty() ? tagTree.getAllSelected() : new ArrayList<>(folderPreviewPanel.selectedItems.values()); + + Set usedSwfs = new HashSet<>(); + for (TreeItem d : sel) { + SWF selectedNodeSwf = d.getSwf(); + if (!usedSwfs.contains(selectedNodeSwf)) { + usedSwfs.add(selectedNodeSwf); + } + } + + Map usedSwfsIds = new HashMap<>(); + for (SWF swf : usedSwfs) { + List as3scripts = new ArrayList<>(); + List images = new ArrayList<>(); + List shapes = new ArrayList<>(); + List morphshapes = new ArrayList<>(); + List buttons = new ArrayList<>(); + List movies = new ArrayList<>(); + List sounds = new ArrayList<>(); + List texts = new ArrayList<>(); + List as12scripts = new ArrayList<>(); + List binaryData = new ArrayList<>(); + Map> frames = new HashMap<>(); + List fonts = new ArrayList<>(); + List symbolNames = new ArrayList<>(); + + for (TreeItem d : sel) { + SWF selectedNodeSwf = d.getSwf(); + + if (selectedNodeSwf != swf) { + continue; + } + + if (d instanceof TagScript) { + Tag tag = ((TagScript) d).getTag(); + if (tag instanceof DoActionTag || tag instanceof DoInitActionTag) { + as12scripts.add(d); + } + } + + if (d instanceof Tag || d instanceof ASMSource) { + TreeNodeType nodeType = TagTree.getTreeNodeType(d); + if (nodeType == TreeNodeType.IMAGE) { + images.add((Tag) d); + } + if (nodeType == TreeNodeType.SHAPE) { + shapes.add((Tag) d); + } + if (nodeType == TreeNodeType.BUTTON) { + buttons.add((Tag) d); + } + if (nodeType == TreeNodeType.MORPH_SHAPE) { + morphshapes.add((Tag) d); + } + if (nodeType == TreeNodeType.AS) { + as12scripts.add(d); + } + if (nodeType == TreeNodeType.MOVIE) { + movies.add((Tag) d); + } + if (nodeType == TreeNodeType.SOUND) { + sounds.add((Tag) d); + } + if (nodeType == TreeNodeType.BINARY_DATA) { + binaryData.add((Tag) d); + } + if (nodeType == TreeNodeType.TEXT) { + texts.add((Tag) d); + } + if (nodeType == TreeNodeType.FONT) { + fonts.add((Tag) d); + } + if (nodeType == TreeNodeType.OTHER_TAG) { + if (d instanceof SymbolClassTypeTag) { + symbolNames.add((Tag) d); + } + } + } + + if (d instanceof Frame) { + Frame fn = (Frame) d; + Timelined parent = fn.timeline.timelined; + int frame = fn.frame; + int parentId = 0; + if (parent instanceof CharacterTag) { + parentId = ((CharacterTag) parent).getCharacterId(); + } + if (!frames.containsKey(parentId)) { + frames.put(parentId, new ArrayList<>()); + } + frames.get(parentId).add(frame); + } + if (d instanceof ScriptPack) { + as3scripts.add((ScriptPack) d); + } + } + + String selFile2; + if (usedSwfs.size() > 1) { + selFile2 = selFile + File.separator + Helper.getNextId(swf.getShortFileName(), usedSwfsIds); + } else { + selFile2 = selFile; + } + + EventListener evl = swf.getExportEventListener(); + + if (export.isOptionEnabled(ImageExportMode.class)) { + ret.addAll(new ImageExporter().exportImages(handler, selFile2 + File.separator + ImageExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(images), + new ImageExportSettings(export.getValue(ImageExportMode.class)), evl)); + } + + if (export.isOptionEnabled(ShapeExportMode.class)) { + ret.addAll(new ShapeExporter().exportShapes(handler, selFile2 + File.separator + ShapeExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(shapes), + new ShapeExportSettings(export.getValue(ShapeExportMode.class), export.getZoom()), evl)); + } + + if (export.isOptionEnabled(MorphShapeExportMode.class)) { + ret.addAll(new MorphShapeExporter().exportMorphShapes(handler, selFile2 + File.separator + MorphShapeExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(morphshapes), + new MorphShapeExportSettings(export.getValue(MorphShapeExportMode.class), export.getZoom()), evl)); + } + + if (export.isOptionEnabled(TextExportMode.class)) { + ret.addAll(new TextExporter().exportTexts(handler, selFile2 + File.separator + TextExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(texts), + new TextExportSettings(export.getValue(TextExportMode.class), Configuration.textExportSingleFile.get(), export.getZoom()), evl)); + } + + if (export.isOptionEnabled(MovieExportMode.class)) { + ret.addAll(new MovieExporter().exportMovies(handler, selFile2 + File.separator + MovieExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(movies), + new MovieExportSettings(export.getValue(MovieExportMode.class)), evl)); + } + + if (export.isOptionEnabled(SoundExportMode.class)) { + ret.addAll(new SoundExporter().exportSounds(handler, selFile2 + File.separator + SoundExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(sounds), + new SoundExportSettings(export.getValue(SoundExportMode.class)), evl)); + } + + if (export.isOptionEnabled(BinaryDataExportMode.class)) { + ret.addAll(new BinaryDataExporter().exportBinaryData(handler, selFile2 + File.separator + BinaryDataExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(binaryData), + new BinaryDataExportSettings(export.getValue(BinaryDataExportMode.class)), evl)); + } + + if (export.isOptionEnabled(FontExportMode.class)) { + ret.addAll(new FontExporter().exportFonts(handler, selFile2 + File.separator + FontExportSettings.EXPORT_FOLDER_NAME, new ReadOnlyTagList(fonts), + new FontExportSettings(export.getValue(FontExportMode.class)), evl)); + } + + if (export.isOptionEnabled(SymbolClassExportMode.class)) { + ret.addAll(new SymbolClassExporter().exportNames(selFile2, new ReadOnlyTagList(symbolNames), evl)); + } + + FrameExporter frameExporter = new FrameExporter(); + + if (export.isOptionEnabled(FrameExportMode.class)) { + FrameExportSettings fes = new FrameExportSettings(export.getValue(FrameExportMode.class), export.getZoom()); + for (Entry> entry : frames.entrySet()) { + int containerId = entry.getKey(); + if (containerId == 0) { + String subFolder = FrameExportSettings.EXPORT_FOLDER_NAME; + ret.addAll(frameExporter.exportFrames(handler, selFile2 + File.separator + subFolder, swf, containerId, entry.getValue(), fes, evl)); + } + } + } + + if (export.isOptionEnabled(SpriteExportMode.class)) { + SpriteExportSettings ses = new SpriteExportSettings(export.getValue(SpriteExportMode.class), export.getZoom()); + for (Entry> entry : frames.entrySet()) { + int containerId = entry.getKey(); + if (containerId != 0) { + String subFolder = SpriteExportSettings.EXPORT_FOLDER_NAME; + ret.addAll(frameExporter.exportFrames(handler, selFile2 + File.separator + subFolder, swf, containerId, entry.getValue(), ses, evl)); + } + } + } + + if (export.isOptionEnabled(ButtonExportMode.class)) { + ButtonExportSettings bes = new ButtonExportSettings(export.getValue(ButtonExportMode.class), export.getZoom()); + for (Tag tag : buttons) { + ButtonTag button = (ButtonTag) tag; + String subFolder = ButtonExportSettings.EXPORT_FOLDER_NAME; + List frameNums = new ArrayList<>(); + frameNums.add(0); // todo: export all frames + ret.addAll(frameExporter.exportFrames(handler, selFile2 + File.separator + subFolder, swf, button.getCharacterId(), frameNums, bes, evl)); + } + } + + if (export.isOptionEnabled(ScriptExportMode.class)) { + if (as3scripts.size() > 0 || as12scripts.size() > 0) { + boolean parallel = Configuration.parallelSpeedUp.get(); + String scriptsFolder = Path.combine(selFile2, ScriptExportSettings.EXPORT_FOLDER_NAME); + Path.createDirectorySafe(new File(scriptsFolder)); + boolean singleScriptFile = Configuration.scriptExportSingleFile.get(); + if (parallel && singleScriptFile) { + logger.log(Level.WARNING, AppStrings.translate("export.script.singleFilePallelModeWarning")); + singleScriptFile = false; + } + + ScriptExportSettings scriptExportSettings = new ScriptExportSettings(export.getValue(ScriptExportMode.class), singleScriptFile); + String singleFileName = Path.combine(scriptsFolder, swf.getShortFileName() + scriptExportSettings.getFileExtension()); + try (FileTextWriter writer = scriptExportSettings.singleFile ? new FileTextWriter(Configuration.getCodeFormatting(), new FileOutputStream(singleFileName)) : null) { + scriptExportSettings.singleFileWriter = writer; + if (swf.isAS3()) { + ret.addAll(new AS3ScriptExporter().exportActionScript3(swf, handler, scriptsFolder, as3scripts, scriptExportSettings, parallel, evl)); + } else { + Map asmsToExport = swf.getASMs(true, as12scripts, false); + ret.addAll(new AS2ScriptExporter().exportAS2Scripts(handler, scriptsFolder, asmsToExport, scriptExportSettings, parallel, evl)); + } + } + } + } + } + + return ret; + } + + public void exportAll(SWF swf, AbortRetryIgnoreHandler handler, String selFile, ExportDialog export) throws IOException, InterruptedException { + boolean exportAll = false; + if (exportAll) { + exportAllDebug(swf, handler, selFile, export); + return; + } + + EventListener evl = swf.getExportEventListener(); + + if (export.isOptionEnabled(ImageExportMode.class)) { + new ImageExporter().exportImages(handler, Path.combine(selFile, ImageExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new ImageExportSettings(export.getValue(ImageExportMode.class)), evl); + } + + if (export.isOptionEnabled(ShapeExportMode.class)) { + new ShapeExporter().exportShapes(handler, Path.combine(selFile, ShapeExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new ShapeExportSettings(export.getValue(ShapeExportMode.class), export.getZoom()), evl); + } + + if (export.isOptionEnabled(MorphShapeExportMode.class)) { + new MorphShapeExporter().exportMorphShapes(handler, Path.combine(selFile, MorphShapeExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new MorphShapeExportSettings(export.getValue(MorphShapeExportMode.class), export.getZoom()), evl); + } + + if (export.isOptionEnabled(TextExportMode.class)) { + new TextExporter().exportTexts(handler, Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new TextExportSettings(export.getValue(TextExportMode.class), Configuration.textExportSingleFile.get(), export.getZoom()), evl); + } + + if (export.isOptionEnabled(MovieExportMode.class)) { + new MovieExporter().exportMovies(handler, Path.combine(selFile, MovieExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new MovieExportSettings(export.getValue(MovieExportMode.class)), evl); + } + + if (export.isOptionEnabled(SoundExportMode.class)) { + new SoundExporter().exportSounds(handler, Path.combine(selFile, SoundExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new SoundExportSettings(export.getValue(SoundExportMode.class)), evl); + } + + if (export.isOptionEnabled(BinaryDataExportMode.class)) { + new BinaryDataExporter().exportBinaryData(handler, Path.combine(selFile, BinaryDataExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new BinaryDataExportSettings(export.getValue(BinaryDataExportMode.class)), evl); + } + + if (export.isOptionEnabled(FontExportMode.class)) { + new FontExporter().exportFonts(handler, Path.combine(selFile, FontExportSettings.EXPORT_FOLDER_NAME), swf.getTags(), + new FontExportSettings(export.getValue(FontExportMode.class)), evl); + } + + if (export.isOptionEnabled(SymbolClassExportMode.class)) { + new SymbolClassExporter().exportNames(selFile, swf.getTags(), evl); + } + + FrameExporter frameExporter = new FrameExporter(); + + if (export.isOptionEnabled(FrameExportMode.class)) { + FrameExportSettings fes = new FrameExportSettings(export.getValue(FrameExportMode.class), export.getZoom()); + frameExporter.exportFrames(handler, Path.combine(selFile, FrameExportSettings.EXPORT_FOLDER_NAME), swf, 0, null, fes, evl); + } + + if (export.isOptionEnabled(SpriteExportMode.class)) { + SpriteExportSettings ses = new SpriteExportSettings(export.getValue(SpriteExportMode.class), export.getZoom()); + for (CharacterTag c : swf.getCharacters().values()) { + if (c instanceof DefineSpriteTag) { + frameExporter.exportFrames(handler, Path.combine(selFile, SpriteExportSettings.EXPORT_FOLDER_NAME), swf, c.getCharacterId(), null, ses, evl); + } + } + } + + if (export.isOptionEnabled(ButtonExportMode.class)) { + ButtonExportSettings bes = new ButtonExportSettings(export.getValue(ButtonExportMode.class), export.getZoom()); + for (CharacterTag c : swf.getCharacters().values()) { + if (c instanceof ButtonTag) { + List frameNums = new ArrayList<>(); + frameNums.add(0); // todo: export all frames + frameExporter.exportFrames(handler, Path.combine(selFile, ButtonExportSettings.EXPORT_FOLDER_NAME), swf, c.getCharacterId(), frameNums, bes, evl); + } + } + } + + if (export.isOptionEnabled(ScriptExportMode.class)) { + boolean parallel = Configuration.parallelSpeedUp.get(); + String scriptsFolder = Path.combine(selFile, ScriptExportSettings.EXPORT_FOLDER_NAME); + Path.createDirectorySafe(new File(scriptsFolder)); + boolean singleScriptFile = Configuration.scriptExportSingleFile.get(); + if (parallel && singleScriptFile) { + logger.log(Level.WARNING, AppStrings.translate("export.script.singleFilePallelModeWarning")); + singleScriptFile = false; + } + + ScriptExportSettings scriptExportSettings = new ScriptExportSettings(export.getValue(ScriptExportMode.class), singleScriptFile); + String singleFileName = Path.combine(scriptsFolder, swf.getShortFileName() + scriptExportSettings.getFileExtension()); + try (FileTextWriter writer = scriptExportSettings.singleFile ? new FileTextWriter(Configuration.getCodeFormatting(), new FileOutputStream(singleFileName)) : null) { + scriptExportSettings.singleFileWriter = writer; + swf.exportActionScript(handler, scriptsFolder, scriptExportSettings, parallel, evl); + } + } + } + + public void exportAllDebug(SWF swf, AbortRetryIgnoreHandler handler, String selFile, ExportDialog export) throws IOException, InterruptedException { + EventListener evl = swf.getExportEventListener(); + + if (export.isOptionEnabled(ImageExportMode.class)) { + for (ImageExportMode exportMode : ImageExportMode.values()) { + new ImageExporter().exportImages(handler, Path.combine(selFile, ImageExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new ImageExportSettings(exportMode), evl); + } + } + + if (export.isOptionEnabled(ShapeExportMode.class)) { + for (ShapeExportMode exportMode : ShapeExportMode.values()) { + new ShapeExporter().exportShapes(handler, Path.combine(selFile, ShapeExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new ShapeExportSettings(exportMode, export.getZoom()), evl); + } + } + + if (export.isOptionEnabled(MorphShapeExportMode.class)) { + for (MorphShapeExportMode exportMode : MorphShapeExportMode.values()) { + new MorphShapeExporter().exportMorphShapes(handler, Path.combine(selFile, MorphShapeExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new MorphShapeExportSettings(exportMode, export.getZoom()), evl); + } + } + + if (export.isOptionEnabled(TextExportMode.class)) { + for (TextExportMode exportMode : TextExportMode.values()) { + new TextExporter().exportTexts(handler, Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new TextExportSettings(exportMode, Configuration.textExportSingleFile.get(), export.getZoom()), evl); + } + } + + if (export.isOptionEnabled(MovieExportMode.class)) { + for (MovieExportMode exportMode : MovieExportMode.values()) { + new MovieExporter().exportMovies(handler, Path.combine(selFile, MovieExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new MovieExportSettings(exportMode), evl); + } + } + + if (export.isOptionEnabled(SoundExportMode.class)) { + for (SoundExportMode exportMode : SoundExportMode.values()) { + new SoundExporter().exportSounds(handler, Path.combine(selFile, SoundExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new SoundExportSettings(exportMode), evl); + } + } + + if (export.isOptionEnabled(BinaryDataExportMode.class)) { + for (BinaryDataExportMode exportMode : BinaryDataExportMode.values()) { + new BinaryDataExporter().exportBinaryData(handler, Path.combine(selFile, BinaryDataExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new BinaryDataExportSettings(exportMode), evl); + } + } + + if (export.isOptionEnabled(FontExportMode.class)) { + for (FontExportMode exportMode : FontExportMode.values()) { + new FontExporter().exportFonts(handler, Path.combine(selFile, FontExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf.getTags(), + new FontExportSettings(exportMode), evl); + } + } + + if (export.isOptionEnabled(SymbolClassExportMode.class)) { + for (SymbolClassExportMode exportMode : SymbolClassExportMode.values()) { + new SymbolClassExporter().exportNames(selFile, swf.getTags(), evl); + } + } + + FrameExporter frameExporter = new FrameExporter(); + + if (export.isOptionEnabled(FrameExportMode.class)) { + for (FrameExportMode exportMode : FrameExportMode.values()) { + FrameExportSettings fes = new FrameExportSettings(exportMode, export.getZoom()); + frameExporter.exportFrames(handler, Path.combine(selFile, FrameExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf, 0, null, fes, evl); + } + } + + if (export.isOptionEnabled(SpriteExportMode.class)) { + for (SpriteExportMode exportMode : SpriteExportMode.values()) { + SpriteExportSettings ses = new SpriteExportSettings(exportMode, export.getZoom()); + for (CharacterTag c : swf.getCharacters().values()) { + if (c instanceof DefineSpriteTag) { + frameExporter.exportFrames(handler, Path.combine(selFile, SpriteExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf, c.getCharacterId(), null, ses, evl); + } + } + } + } + + if (export.isOptionEnabled(ButtonExportMode.class)) { + for (ButtonExportMode exportMode : ButtonExportMode.values()) { + ButtonExportSettings bes = new ButtonExportSettings(exportMode, export.getZoom()); + for (CharacterTag c : swf.getCharacters().values()) { + if (c instanceof ButtonTag) { + List frameNums = new ArrayList<>(); + frameNums.add(0); // todo: export all frames + frameExporter.exportFrames(handler, Path.combine(selFile, ButtonExportSettings.EXPORT_FOLDER_NAME, exportMode.name()), swf, c.getCharacterId(), frameNums, bes, evl); + } + } + } + } + + if (export.isOptionEnabled(ScriptExportMode.class)) { + boolean parallel = Configuration.parallelSpeedUp.get(); + for (ScriptExportMode exportMode : ScriptExportMode.values()) { + String scriptsFolder = Path.combine(selFile, ScriptExportSettings.EXPORT_FOLDER_NAME, exportMode.name()); + Path.createDirectorySafe(new File(scriptsFolder)); + boolean singleScriptFile = Configuration.scriptExportSingleFile.get(); + if (parallel && singleScriptFile) { + logger.log(Level.WARNING, AppStrings.translate("export.script.singleFilePallelModeWarning")); + singleScriptFile = false; + } + + ScriptExportSettings scriptExportSettings = new ScriptExportSettings(exportMode, singleScriptFile); + String singleFileName = Path.combine(scriptsFolder, swf.getShortFileName() + scriptExportSettings.getFileExtension()); + try (FileTextWriter writer = scriptExportSettings.singleFile ? new FileTextWriter(Configuration.getCodeFormatting(), new FileOutputStream(singleFileName)) : null) { + scriptExportSettings.singleFileWriter = writer; + swf.exportActionScript(handler, scriptsFolder, scriptExportSettings, parallel, evl); + } + } + } + } + + public List getSwfs() { + return swfs; + } + + public SWFList getCurrentSwfList() { + SWF swf = getCurrentSwf(); + if (swf == null) { + return null; + } + + return swf.swfList; + } + + public SWF getCurrentSwf() { + if (swfs == null || swfs.isEmpty()) { + return null; + } + + if (treePanelMode == TreePanelMode.TAG_TREE) { + TreeItem treeNode = (TreeItem) tagTree.getLastSelectedPathComponent(); + if (treeNode == null || treeNode instanceof SWFList) { + return null; + } + + return treeNode.getSwf(); + } else if (treePanelMode == TreePanelMode.DUMP_TREE) { + DumpInfo dumpInfo = (DumpInfo) dumpTree.getLastSelectedPathComponent(); + + if (dumpInfo == null) { + return null; + } + + return DumpInfoSwfNode.getSwfNode(dumpInfo).getSwf(); + } + + return null; + } + + public void gotoFrame(int frame) { + TreeItem treeItem = (TreeItem) tagTree.getLastSelectedPathComponent(); + if (treeItem == null) { + return; + } + if (treeItem instanceof Timelined) { + Timelined t = (Timelined) treeItem; + Frame f = tagTree.getModel().getFrame(treeItem.getSwf(), t, frame); + if (f != null) { + setTagTreeSelectedNode(f); + } + } + } + + public void gotoScriptLine(SWF swf, String scriptName, int line, int classIndex, int traitIndex, int methodIndex) { + gotoScriptName(swf, scriptName); + if (abcPanel != null) { + if (Main.isDebugPCode()) { + if (classIndex != -1) { + boolean classChanged = false; + if (abcPanel.decompiledTextArea.getClassIndex() != classIndex) { + abcPanel.decompiledTextArea.setClassIndex(classIndex); + classChanged = true; + } + if (traitIndex != -10 && (classChanged || abcPanel.decompiledTextArea.lastTraitIndex != traitIndex)) { + abcPanel.decompiledTextArea.gotoTrait(traitIndex); + } + } + abcPanel.detailPanel.methodTraitPanel.methodCodePanel.gotoInstrLine(line); + } else { + abcPanel.decompiledTextArea.gotoLine(line); + } + } else if (actionPanel != null) { + if (Main.isDebugPCode()) { + actionPanel.editor.gotoLine(line); + } else { + actionPanel.decompiledEditor.gotoLine(line); + } + } + refreshBreakPoints(); + + } + + public void refreshBreakPoints() { + if (abcPanel != null) { + abcPanel.decompiledTextArea.refreshMarkers(); + abcPanel.detailPanel.methodTraitPanel.methodCodePanel.refreshMarkers(); + } + if (actionPanel != null) { + actionPanel.decompiledEditor.refreshMarkers(); + actionPanel.editor.refreshMarkers(); + } + } + + /* + public void debuggerBreakAt(SWF swf, String cls, int line) { + View.execInEventDispatchLater(new Runnable() { + + @Override + public void run() { + gotoClassLine(swf, cls, line); + if (abcPanel != null) { + abcPanel.decompiledTextArea.addColorMarker(line, DecompiledEditorPane.FG_IP_COLOR, DecompiledEditorPane.BG_IP_COLOR, DecompiledEditorPane.PRIORITY_IP); + } + } + }); + + }*/ + public void gotoScriptName(SWF swf, String scriptName) { + if (swf == null) { + return; + } + if (swf.isAS3()) { + String rawScriptName = scriptName; + if (rawScriptName.startsWith("#PCODE ")) { + rawScriptName = rawScriptName.substring(rawScriptName.indexOf(';') + 1); + } + + List abcList = swf.getAbcList(); + if (!abcList.isEmpty()) { + ABCPanel abcPanel = getABCPanel(); + abcPanel.setAbc(abcList.get(0).getABC()); + abcPanel.hilightScript(swf, rawScriptName); + } + } else { + String rawScriptName = scriptName; + if (rawScriptName.startsWith("#PCODE ")) { + rawScriptName = rawScriptName.substring("#PCODE ".length()); + } + Map asms = swf.getASMs(true); + if (actionPanel != null && asms.containsKey(rawScriptName)) { + actionPanel.setSource(asms.get(rawScriptName), true); + } + } + } + + public void gotoDocumentClass(SWF swf) { + if (swf == null) { + return; + } + + String documentClass = swf.getDocumentClass(); + if (documentClass != null && !Configuration.dumpView.get()) { + List abcList = swf.getAbcList(); + if (!abcList.isEmpty()) { + ABCPanel abcPanel = getABCPanel(); + for (ABCContainerTag c : abcList) { + if (c.getABC().findClassByName(documentClass) > -1) { + abcPanel.setAbc(c.getABC()); + abcPanel.hilightScript(swf, documentClass); + break; + } + } + } + } + } + + public void disableDecompilationChanged() { + clearAllScriptCache(); + + if (abcPanel != null) { + abcPanel.reload(); + } + + updateClassesList(); + } + + private void clearAllScriptCache() { + for (SWFList swfList : swfs) { + for (SWF swf : swfList) { + swf.clearScriptCache(); + } + } + } + + public void searchInActionScriptOrText(Boolean searchInText, SWF swf) { + SearchDialog searchDialog = new SearchDialog(getMainFrame().getWindow(), false); + if (searchInText != null) { + if (searchInText) { + searchDialog.searchInTextsRadioButton.setSelected(true); + } else { + searchDialog.searchInASRadioButton.setSelected(true); + } + } + + if (searchDialog.showDialog() == AppDialog.OK_OPTION) { + final String txt = searchDialog.searchField.getText(); + if (!txt.isEmpty()) { + if (swf.isAS3()) { + getABCPanel(); + } else { + getActionPanel(); + } + + boolean ignoreCase = searchDialog.ignoreCaseCheckBox.isSelected(); + boolean regexp = searchDialog.regexpCheckBox.isSelected(); + + if (searchDialog.searchInASRadioButton.isSelected()) { + new CancellableWorker() { + @Override + protected Void doInBackground() throws Exception { + List abcResult = null; + List actionResult = null; + if (swf.isAS3()) { + abcResult = getABCPanel().search(swf, txt, ignoreCase, regexp, this); + } else { + actionResult = getActionPanel().search(swf, txt, ignoreCase, regexp, this); + } + + List fAbcResult = abcResult; + List fActionResult = actionResult; + View.execInEventDispatch(() -> { + boolean found = false; + if (fAbcResult != null) { + found = true; + getABCPanel().searchPanel.setSearchText(txt); + SearchResultsDialog sr = new SearchResultsDialog<>(getMainFrame().getWindow(), txt, getABCPanel()); + sr.setResults(fAbcResult); + sr.setVisible(true); + } else if (fActionResult != null) { + found = true; + getActionPanel().searchPanel.setSearchText(txt); + + SearchResultsDialog sr = new SearchResultsDialog<>(getMainFrame().getWindow(), txt, getActionPanel()); + sr.setResults(fActionResult); + sr.setVisible(true); + } + + if (!found) { + View.showMessageDialog(null, translate("message.search.notfound").replace("%searchtext%", txt), translate("message.search.notfound.title"), JOptionPane.INFORMATION_MESSAGE); + } + + Main.stopWork(); + }); + + return null; + } + + @Override + protected void done() { + View.execInEventDispatch(() -> { + Main.stopWork(); + }); + + } + }.execute(); + } else if (searchDialog.searchInTextsRadioButton.isSelected()) { + new CancellableWorker() { + @Override + protected Void doInBackground() throws Exception { + List textResult; + SearchPanel textSearchPanel = previewPanel.getTextPanel().getSearchPanel(); + textSearchPanel.setOptions(ignoreCase, regexp); + textResult = searchText(txt, ignoreCase, regexp, swf); + + List fTextResult = textResult; + View.execInEventDispatch(() -> { + textSearchPanel.setSearchText(txt); + boolean found = textSearchPanel.setResults(fTextResult); + if (!found) { + View.showMessageDialog(null, translate("message.search.notfound").replace("%searchtext%", txt), translate("message.search.notfound.title"), JOptionPane.INFORMATION_MESSAGE); + } + + Main.stopWork(); + }); + + return null; + } + + @Override + protected void done() { + View.execInEventDispatch(() -> { + Main.stopWork(); + }); + + } + }.execute(); + } + } + } + } + + public void replaceText() { + SearchDialog replaceDialog = new SearchDialog(getMainFrame().getWindow(), true); + if (replaceDialog.showDialog() == AppDialog.OK_OPTION) { + final String txt = replaceDialog.searchField.getText(); + if (!txt.isEmpty()) { + final SWF swf = getCurrentSwf(); + + new CancellableWorker() { + @Override + protected Void doInBackground() throws Exception { + int findCount = 0; + boolean ignoreCase = replaceDialog.ignoreCaseCheckBox.isSelected(); + boolean regexp = replaceDialog.regexpCheckBox.isSelected(); + String replacement = replaceDialog.replaceField.getText(); + if (!regexp) { + replacement = Matcher.quoteReplacement(replacement); + } + Pattern pat; + if (regexp) { + pat = Pattern.compile(txt, ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); + } else { + pat = Pattern.compile(Pattern.quote(txt), ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); + } + List textTags = new ArrayList<>(); + for (Tag tag : swf.getTags()) { + if (tag instanceof TextTag) { + textTags.add((TextTag) tag); + } + } + for (TextTag textTag : textTags) { + if (!replaceDialog.replaceInParametersCheckBox.isSelected()) { + List texts = textTag.getTexts(); + boolean found = false; + for (int i = 0; i < texts.size(); i++) { + String text = texts.get(i); + if (pat.matcher(text).find()) { + texts.set(i, text.replaceAll(txt, replacement)); + found = true; + findCount++; + } + } + if (found) { + String[] textArray = texts.toArray(new String[texts.size()]); + textTag.setFormattedText(getMissingCharacterHandler(), textTag.getFormattedText(false).text, textArray); + } + } else { + String text = textTag.getFormattedText(false).text; + if (pat.matcher(text).find()) { + textTag.setFormattedText(getMissingCharacterHandler(), text.replaceAll(txt, replacement), null); + findCount++; + } + } + } + + if (findCount > 0) { + swf.clearImageCache(); + repaintTree(); + } + + return null; + } + }.execute(); + } + } + } + + private List searchText(String txt, boolean ignoreCase, boolean regexp, SWF swf) { + if (txt != null && !txt.isEmpty()) { + List found = new ArrayList<>(); + Pattern pat; + if (regexp) { + pat = Pattern.compile(txt, ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); + } else { + pat = Pattern.compile(Pattern.quote(txt), ignoreCase ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); + } + for (Tag tag : swf.getTags()) { + if (tag instanceof TextTag) { + TextTag textTag = (TextTag) tag; + if (pat.matcher(textTag.getFormattedText(false).text).find()) { + found.add(textTag); + } + } + } + + return found; + } + + return null; + } + + @Override + public void updateSearchPos(TextTag item) { + setTagTreeSelectedNode(item); + previewPanel.getTextPanel().updateSearchPos(); + } + + private void setDumpTreeSelectedNode(DumpInfo dumpInfo) { + DumpTreeModel dtm = (DumpTreeModel) dumpTree.getModel(); + TreePath tp = dtm.getDumpInfoPath(dumpInfo); + if (tp != null) { + dumpTree.setSelectionPath(tp); + dumpTree.scrollPathToVisible(tp); + } else { + showCard(CARDEMPTYPANEL); + } + } + + public void setTagTreeSelectedNode(TreeItem treeItem) { + TagTreeModel ttm = tagTree.getModel(); + TreePath tp = ttm.getTreePath(treeItem); + if (tp != null) { + tagTree.setSelectionPath(tp); + tagTree.scrollPathToVisible(tp); + } else { + showCard(CARDEMPTYPANEL); + } + } + + public void autoDeobfuscateChanged() { + Helper.decompilationErrorAdd = AppStrings.translate(Configuration.autoDeobfuscate.get() ? "deobfuscation.comment.failed" : "deobfuscation.comment.tryenable"); + clearAllScriptCache(); + if (abcPanel != null) { + abcPanel.reload(); + } + reload(true); + updateClassesList(); + } + + public void renameColliding(final SWF swf) { + if (swf == null) { + return; + } + if (confirmExperimental()) { + new CancellableWorker() { + @Override + protected Integer doInBackground() throws Exception { + AbcMultiNameCollisionFixer fixer = new AbcMultiNameCollisionFixer(); + return fixer.fixCollisions(swf); + } + + @Override + protected void onStart() { + Main.startWork(translate("work.renaming.identifiers") + "...", this); + } + + @Override + protected void done() { + View.execInEventDispatch(() -> { + try { + int cnt = get(); + Main.stopWork(); + View.showMessageDialog(null, translate("message.rename.renamed").replace("%count%", Integer.toString(cnt))); + swf.assignClassesToSymbols(); + swf.clearScriptCache(); + if (abcPanel != null) { + abcPanel.reload(); + } + updateClassesList(); + reload(true); + } catch (Exception ex) { + logger.log(Level.SEVERE, "Error during renaming identifiers", ex); + Main.stopWork(); + View.showMessageDialog(null, translate("error.occured").replace("%error%", ex.getClass().getSimpleName())); + } + }); + } + }.execute(); + } + } + + public void renameOneIdentifier(final SWF swf) { + if (swf == null) { + return; + } + + FileAttributesTag fileAttributes = swf.getFileAttributes(); + if (fileAttributes != null && fileAttributes.actionScript3) { + final int multiName = getABCPanel().decompiledTextArea.getMultinameUnderCaret(); + final List abcList = swf.getAbcList(); + if (multiName > 0) { + new CancellableWorker() { + @Override + public Void doInBackground() throws Exception { + renameMultiname(abcList, multiName); + return null; + } + + @Override + protected void onStart() { + Main.startWork(translate("work.renaming") + "...", this); + } + + @Override + protected void done() { + Main.stopWork(); + } + }.execute(); + + } else { + View.showMessageDialog(null, translate("message.rename.notfound.multiname"), translate("message.rename.notfound.title"), JOptionPane.INFORMATION_MESSAGE); + } + } else { + final String identifier = getActionPanel().getStringUnderCursor(); + if (identifier != null) { + new CancellableWorker() { + @Override + public Void doInBackground() throws Exception { + try { + renameIdentifier(swf, identifier); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, null, ex); + } + return null; + } + + @Override + protected void onStart() { + Main.startWork(translate("work.renaming") + "...", this); + } + + @Override + protected void done() { + Main.stopWork(); + } + }.execute(); + } else { + View.showMessageDialog(null, translate("message.rename.notfound.identifier"), translate("message.rename.notfound.title"), JOptionPane.INFORMATION_MESSAGE); + } + } + } + + public void exportFla(final SWF swf) { + if (swf == null) { + return; + } + JFileChooser fc = new JFileChooser(); + String selDir = Configuration.lastOpenDir.get(); + fc.setCurrentDirectory(new File(selDir)); + if (!selDir.endsWith(File.separator)) { + selDir += File.separator; + } + String fileName = new File(swf.getFile()).getName(); + fileName = fileName.substring(0, fileName.length() - 4) + ".fla"; + fc.setSelectedFile(new File(selDir + fileName)); + List flaFilters = new ArrayList<>(); + List xflFilters = new ArrayList<>(); + List versions = new ArrayList<>(); + boolean isAS3 = swf.isAS3(); + for (int i = FLAVersion.values().length - 1; i >= 0; i--) { + final FLAVersion v = FLAVersion.values()[i]; + if (!isAS3 && v.minASVersion() > 2) { + // This version does not support AS1/2 + } else { + versions.add(v); + FileFilter f = new FileFilter() { + @Override + public boolean accept(File f) { + return f.isDirectory() || (f.getName().toLowerCase().endsWith(".fla")); + } + + @Override + public String getDescription() { + return translate("filter.fla").replace("%version%", v.applicationName()); + } + }; + if (v == FLAVersion.CS6) { + fc.setFileFilter(f); + } else { + fc.addChoosableFileFilter(f); + } + flaFilters.add(f); + f = new FileFilter() { + @Override + public boolean accept(File f) { + return f.isDirectory() || (f.getName().toLowerCase().endsWith(".xfl")); + } + + @Override + public String getDescription() { + return translate("filter.xfl").replace("%version%", v.applicationName()); + } + }; + fc.addChoosableFileFilter(f); + xflFilters.add(f); + } + } + + fc.setAcceptAllFileFilterUsed(false); + JFrame f = new JFrame(); + View.setWindowIcon(f); + if (fc.showSaveDialog(f) == JFileChooser.APPROVE_OPTION) { + Configuration.lastOpenDir.set(Helper.fixDialogFile(fc.getSelectedFile()).getParentFile().getAbsolutePath()); + File sf = Helper.fixDialogFile(fc.getSelectedFile()); + + FileFilter selectedFilter = fc.getFileFilter(); + final boolean compressed = flaFilters.contains(selectedFilter); + String path = sf.getAbsolutePath(); + if (path.endsWith(".fla") || path.endsWith(".xfl")) { + path = path.substring(0, path.length() - 4); + } + path += compressed ? ".fla" : ".xfl"; + final FLAVersion selectedVersion = versions.get(compressed ? flaFilters.indexOf(selectedFilter) : xflFilters.indexOf(selectedFilter)); + final File selfile = new File(path); + new CancellableWorker() { + @Override + protected Void doInBackground() throws Exception { + Helper.freeMem(); + try { + AbortRetryIgnoreHandler errorHandler = new GuiAbortRetryIgnoreHandler(); + if (compressed) { + swf.exportFla(errorHandler, selfile.getAbsolutePath(), new File(swf.getFile()).getName(), ApplicationInfo.APPLICATION_NAME, ApplicationInfo.applicationVerName, ApplicationInfo.version, Configuration.parallelSpeedUp.get(), selectedVersion); + } else { + swf.exportXfl(errorHandler, selfile.getAbsolutePath(), new File(swf.getFile()).getName(), ApplicationInfo.APPLICATION_NAME, ApplicationInfo.applicationVerName, ApplicationInfo.version, Configuration.parallelSpeedUp.get(), selectedVersion); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, "FLA export error", ex); + View.showMessageDialog(null, translate("error.export") + ": " + ex.getClass().getName() + " " + ex.getLocalizedMessage(), translate("error"), JOptionPane.ERROR_MESSAGE); + } + Helper.freeMem(); + return null; + } + + @Override + protected void onStart() { + Main.startWork(translate("work.exporting.fla") + "...", this); + } + + @Override + protected void done() { + if (Configuration.openFolderAfterFlaExport.get()) { + try { + Desktop.getDesktop().open(selfile.getAbsoluteFile().getParentFile()); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + + Main.stopWork(); + } + }.execute(); + } + } + + public void importText(final SWF swf) { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); + chooser.setDialogTitle(translate("import.select.directory")); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); + File textsFile = new File(Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME, TextExporter.TEXT_EXPORT_FILENAME_FORMATTED)); + TextImporter textImporter = new TextImporter(getMissingCharacterHandler(), new TextImportErrorHandler() { + // "configuration items" for the current replace only + private final ConfigurationItem showAgainImportError = new ConfigurationItem<>("showAgainImportError", true, true); + + private final ConfigurationItem showAgainInvalidText = new ConfigurationItem<>("showAgainInvalidText", true, true); + + private String getTextTagInfo(TextTag textTag) { + StringBuilder ret = new StringBuilder(); + if (textTag != null) { + ret.append(" TextId: ").append(textTag.getCharacterId()).append(" (").append(String.join(", ", textTag.getTexts())).append(")"); + } + + return ret.toString(); + } + + @Override + public boolean handle(TextTag textTag) { + String msg = translate("error.text.import"); + logger.log(Level.SEVERE, msg + getTextTagInfo(textTag)); + return View.showConfirmDialog(MainPanel.this, msg, translate("error"), JOptionPane.OK_CANCEL_OPTION, showAgainImportError, JOptionPane.OK_OPTION) != JOptionPane.OK_OPTION; + } + + @Override + public boolean handle(TextTag textTag, String message, long line) { + String msg = translate("error.text.invalid.continue").replace("%text%", message).replace("%line%", Long.toString(line)); + logger.log(Level.SEVERE, msg + getTextTagInfo(textTag)); + return View.showConfirmDialog(MainPanel.this, msg, translate("error"), JOptionPane.OK_CANCEL_OPTION, showAgainInvalidText, JOptionPane.OK_OPTION) != JOptionPane.OK_OPTION; + } + }); + + // try to import formatted texts + if (textsFile.exists()) { + textImporter.importTextsSingleFileFormatted(textsFile, swf); + } else { + textsFile = new File(Path.combine(selFile, TextExportSettings.EXPORT_FOLDER_NAME, TextExporter.TEXT_EXPORT_FILENAME_PLAIN)); + // try to import plain texts + if (textsFile.exists()) { + textImporter.importTextsSingleFile(textsFile, swf); + } else { + textImporter.importTextsMultipleFiles(selFile, swf); + } + } + + swf.clearImageCache(); + reload(true); + } + } + + public As3ScriptReplacerInterface getAs3ScriptReplacer() { + As3ScriptReplacerInterface r = As3ScriptReplacerFactory.createByConfig(); + if (!r.isAvailable()) { + if (r instanceof MxmlcAs3ScriptReplacer) { + if (View.showConfirmDialog(null, AppStrings.translate("message.flexpath.notset"), AppStrings.translate("error"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) { + Main.advancedSettings("paths"); + } + } else if (r instanceof FFDecAs3ScriptReplacer) { + if (View.showConfirmDialog(this, AppStrings.translate("message.playerpath.lib.notset"), AppStrings.translate("message.action.playerglobal.title"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) { + Main.advancedSettings("paths"); + } + } else { + //Not translated yet - just in case there are more Script replacers in the future. Unused now. + View.showConfirmDialog(this, "Current script replacer is not available", "Script replacer not available", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE); + } + return null; + } + return r; + } + + public void importScript(final SWF swf) { + As3ScriptReplacerInterface as3ScriptReplacer = getAs3ScriptReplacer(); + if (as3ScriptReplacer == null) { + return; + } + String flexLocation = Configuration.flexSdkLocation.get(); + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); + chooser.setDialogTitle(translate("import.select.directory")); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); + String scriptsFolder = Path.combine(selFile, ScriptExportSettings.EXPORT_FOLDER_NAME); + + int countAs2 = new AS2ScriptImporter().importScripts(scriptsFolder, swf.getASMs(true)); + int countAs3 = new AS3ScriptImporter().importScripts(as3ScriptReplacer, scriptsFolder, swf.getAS3Packs()); + + if (countAs3 > 0) { + updateClassesList(); + } + + View.showMessageDialog(this, translate("import.script.result").replace("%count%", Integer.toString(countAs2 + countAs3))); + if (countAs2 != 0 || countAs3 != 0) { + reload(true); + } + } + } + + public void importSymbolClass(final SWF swf) { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); + chooser.setDialogTitle(translate("import.select.directory")); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); + File importFile = new File(Path.combine(selFile, SymbolClassExporter.SYMBOL_CLASS_EXPORT_FILENAME)); + SymbolClassImporter importer = new SymbolClassImporter(); + + if (importFile.exists()) { + importer.importSymbolClasses(importFile, swf); + } + } + } + + private String selectExportDir() { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(Configuration.lastExportDir.get())); + chooser.setDialogTitle(translate("export.select.directory")); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + final String selFile = Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath(); + Configuration.lastExportDir.set(Helper.fixDialogFile(chooser.getSelectedFile()).getAbsolutePath()); + return selFile; + } + return null; + } + + public void export(final boolean onlySel) { + + final SWF swf = getCurrentSwf(); + List sel = tagTree.getAllSelected(); + if (!onlySel) { + sel = null; + } else if (sel.isEmpty()) { + return; + } + final ExportDialog export = new ExportDialog(sel); + if (export.showExportDialog() == AppDialog.OK_OPTION) { + final String selFile = selectExportDir(); + if (selFile != null) { + final long timeBefore = System.currentTimeMillis(); + + new CancellableWorker() { + @Override + public Void doInBackground() throws Exception { + try { + AbortRetryIgnoreHandler errorHandler = new GuiAbortRetryIgnoreHandler(); + if (onlySel) { + exportSelection(errorHandler, selFile, export); + } else { + exportAll(swf, errorHandler, selFile, export); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, "Error during export", ex); + View.showMessageDialog(null, translate("error.export") + ": " + ex.getClass().getName() + " " + ex.getLocalizedMessage()); + } + return null; + } + + @Override + protected void onStart() { + Main.startWork(translate("work.exporting") + "...", this); + } + + @Override + protected void done() { + Main.stopWork(); + long timeAfter = System.currentTimeMillis(); + final long timeMs = timeAfter - timeBefore; + + View.execInEventDispatchLater(() -> { + setStatus(translate("export.finishedin").replace("%time%", Helper.formatTimeSec(timeMs))); + }); + } + }.execute(); + + } + } + } + + public void exportJavaSource() { + List sel = tagTree.getSelected(); + for (TreeItem item : sel) { + if (item instanceof SWF) { + SWF swf = (SWF) item; + final String selFile = selectExportDir(); + if (selFile != null) { + Main.startWork(translate("work.exporting") + "...", null); + + try { + new SwfJavaExporter().exportJavaCode(swf, selFile); + Main.stopWork(); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + } + + public void exportSwfXml() { + List sel = tagTree.getSelected(); + Set swfs = new HashSet<>(); + + for (TreeItem item : sel) { + swfs.add(item.getSwf()); + } + + for (SWF swf : swfs) { + final String selFile = selectExportDir(); + if (selFile != null) { + Main.startWork(translate("work.exporting") + "...", null); + + try { + File outFile = new File(selFile + File.separator + Helper.makeFileName("swf.xml")); + new SwfXmlExporter().exportXml(swf, outFile); + Main.stopWork(); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public void importSwfXml() { + List sel = tagTree.getSelected(); + Set swfs = new HashSet<>(); + for (TreeItem item : sel) { + swfs.add(item.getSwf()); + } + if (swfs.size() > 1) { + return; + } + + for (SWF swf : swfs) { + File selectedFile = showImportFileChooser("filter.xml|*.xml"); + if (selectedFile != null) { + File selfile = Helper.fixDialogFile(selectedFile); + String xml = Helper.readTextFile(selfile.getPath()); + try { + new SwfXmlImporter().importSwf(swf, xml); + swf.clearAllCache(); + swf.assignExportNamesToSymbols(); + swf.assignClassesToSymbols(); + refreshTree(swf); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public void renameIdentifiers(final SWF swf) { + if (swf == null) { + return; + } + if (confirmExperimental()) { + RenameDialog renameDialog = new RenameDialog(); + if (renameDialog.showRenameDialog() == AppDialog.OK_OPTION) { + final RenameType renameType = renameDialog.getRenameType(); + new CancellableWorker() { + @Override + protected Integer doInBackground() throws Exception { + int cnt = swf.deobfuscateIdentifiers(renameType); + return cnt; + } + + @Override + protected void onStart() { + Main.startWork(translate("work.renaming.identifiers") + "...", this); + } + + @Override + protected void done() { + View.execInEventDispatch(() -> { + try { + int cnt = get(); + Main.stopWork(); + View.showMessageDialog(null, translate("message.rename.renamed").replace("%count%", Integer.toString(cnt))); + swf.assignClassesToSymbols(); + swf.clearScriptCache(); + if (abcPanel != null) { + abcPanel.reload(); + } + updateClassesList(); + reload(true); + } catch (Exception ex) { + logger.log(Level.SEVERE, "Error during renaming identifiers", ex); + Main.stopWork(); + View.showMessageDialog(null, translate("error.occured").replace("%error%", ex.getClass().getSimpleName())); + } + }); + } + }.execute(); + } + } + } + + public void deobfuscate() { + DeobfuscationDialog deobfuscationDialog = new DeobfuscationDialog(); + if (deobfuscationDialog.showDialog() == AppDialog.OK_OPTION) { + DeobfuscationLevel level = DeobfuscationLevel.getByLevel(deobfuscationDialog.codeProcessingLevel.getValue()); + new CancellableWorker() { + @Override + protected Void doInBackground() throws Exception { + try { + ABCPanel abcPanel = getABCPanel(); + if (deobfuscationDialog.processAllCheckbox.isSelected()) { + SWF swf = abcPanel.getSwf(); + swf.deobfuscate(level); + } else { + int bi = abcPanel.detailPanel.methodTraitPanel.methodCodePanel.getBodyIndex(); + DecompiledEditorPane decompiledTextArea = abcPanel.decompiledTextArea; + Trait t = abcPanel.decompiledTextArea.getCurrentTrait(); + ABC abc = abcPanel.abc; + if (bi != -1) { + int scriptIndex = decompiledTextArea.getScriptLeaf().scriptIndex; + int classIndex = decompiledTextArea.getClassIndex(); + boolean isStatic = decompiledTextArea.getIsStatic(); + abc.bodies.get(bi).deobfuscate(level, t, scriptIndex, classIndex, isStatic, ""/*FIXME*/); + } + abcPanel.detailPanel.methodTraitPanel.methodCodePanel.setBodyIndex(decompiledTextArea.getScriptLeaf().getPathScriptName(), bi, abc, t, abcPanel.detailPanel.methodTraitPanel.methodCodePanel.getScriptIndex()); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, "Deobfuscation error", ex); + } + + return null; + } + + @Override + protected void onStart() { + Main.startWork(translate("work.deobfuscating") + "...", this); + } + + @Override + protected void done() { + View.execInEventDispatch(() -> { + Main.stopWork(); + View.showMessageDialog(null, translate("work.deobfuscating.complete")); + + clearAllScriptCache(); + getABCPanel().reload(); + updateClassesList(); + }); + } + }.execute(); + } + } + + public void removeNonScripts(SWF swf) { + if (swf == null) { + return; + } + + List tags = swf.getTags().toArrayList(); + List toRemove = new ArrayList<>(); + for (Tag tag : tags) { + System.out.println(tag.getClass()); + if (!(tag instanceof ABCContainerTag || tag instanceof ASMSource)) { + toRemove.add(tag); + } + } + + swf.removeTags(toRemove, true); + refreshTree(swf); + } + + public void removeExceptSelected(SWF swf) { + if (swf == null) { + return; + } + + List sel = tagTree.getAllSelected(); + Set needed = new HashSet<>(); + for (TreeItem item : sel) { + if (item instanceof CharacterTag) { + CharacterTag characterTag = (CharacterTag) item; + characterTag.getNeededCharactersDeep(needed); + needed.add(characterTag.getCharacterId()); + } + } + + List tagsToRemove = new ArrayList<>(); + for (Tag tag : swf.getTags()) { + if (tag instanceof CharacterTag) { + CharacterTag characterTag = (CharacterTag) tag; + if (!needed.contains(characterTag.getCharacterId())) { + tagsToRemove.add(tag); + } + } + } + + swf.removeTags(tagsToRemove, true); + refreshTree(swf); + } + + private void clear() { + dumpViewPanel.clear(); + previewPanel.clear(); + headerPanel.clear(); + folderPreviewPanel.clear(); + if (abcPanel != null) { + abcPanel.clearSwf(); + } + if (actionPanel != null) { + actionPanel.clearSource(); + } + } + + public void refreshTree() { + refreshTree(new SWF[0]); + } + + public void refreshTree(SWF swf) { + refreshTree(new SWF[]{swf}); + } + + public void refreshTree(SWF[] swfs) { + clear(); + showCard(CARDEMPTYPANEL); + TreeItem treeItem = tagTree.getCurrentTreeItem(); + + tagTree.updateSwfs(swfs); + + if (treeItem != null) { + SWF treeItemSwf = treeItem.getSwf().getRootSwf(); + if (this.swfs.contains(treeItemSwf.swfList)) { + setTagTreeSelectedNode(treeItem); + } + } + + reload(true); + } + + public void refreshDecompiled() { + clearAllScriptCache(); + if (abcPanel != null) { + abcPanel.reload(); + } + + reload(true); + updateClassesList(); + } + + private MissingCharacterHandler getMissingCharacterHandler() { + return new MissingCharacterHandler() { + // "configuration items" for the current replace only + private final ConfigurationItem showAgainIgnoreMissingCharacters = new ConfigurationItem<>("showAgainIgnoreMissingCharacters", true, true); + + private boolean ignoreMissingCharacters = false; + + @Override + public boolean getIgnoreMissingCharacters() { + return ignoreMissingCharacters; + } + + @Override + public boolean handle(TextTag textTag, final FontTag font, final char character) { + String fontName = font.getSwf().sourceFontNamesMap.get(font.getFontId()); + if (fontName == null) { + fontName = font.getFontName(); + } + final Font f = FontTag.installedFontsByName.get(fontName); + if (f == null || !f.canDisplay(character)) { + String msg = translate("error.font.nocharacter").replace("%char%", "" + character); + logger.log(Level.SEVERE, "{0} FontId: {1} TextId: {2}", new Object[]{msg, font.getCharacterId(), textTag.getCharacterId()}); + ignoreMissingCharacters = View.showConfirmDialog(null, msg, translate("error"), + JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, + showAgainIgnoreMissingCharacters, + ignoreMissingCharacters ? JOptionPane.OK_OPTION : JOptionPane.CANCEL_OPTION) == JOptionPane.OK_OPTION; + return false; + } + + font.addCharacter(character, f); + + return true; + } + }; + } + + public boolean saveText(TextTag textTag, String formattedText, String[] texts, LineMarkedEditorPane editor) { + try { + if (textTag.setFormattedText(getMissingCharacterHandler(), formattedText, texts)) { + return true; + } + } catch (TextParseException ex) { + if (editor != null) { + editor.gotoLine((int) ex.line); + editor.markError(); + } + + View.showMessageDialog(null, translate("error.text.invalid").replace("%text%", ex.text).replace("%line%", Long.toString(ex.line)), translate("error"), JOptionPane.ERROR_MESSAGE); + } + + return false; + } + + public boolean alignText(TextTag textTag, TextAlign textAlign) { + return (textTag.alignText(textAlign)); + } + + public boolean translateText(TextTag textTag, int diff) { + return textTag.translateText(diff); + } + + public boolean previousTag() { + if (getCurrentView() == VIEW_RESOURCES) { + if (tagTree.getSelectionRows().length > 0) { + int row = tagTree.getSelectionRows()[0]; + if (row > 0) { + tagTree.setSelectionRow(row - 1); + tagTree.scrollRowToVisible(row - 1); + previewPanel.focusTextPanel(); + } + } + return true; + } + return false; + } + + public boolean nextTag() { + if (getCurrentView() == VIEW_RESOURCES) { + if (tagTree.getSelectionRows().length > 0) { + int row = tagTree.getSelectionRows()[0]; + if (row < tagTree.getRowCount() - 1) { + tagTree.setSelectionRow(row + 1); + tagTree.scrollRowToVisible(row + 1); + previewPanel.focusTextPanel(); + } + } + return true; + } + return false; + } + + public void selectBkColorButtonActionPerformed(ActionEvent evt) { + Color newColor = JColorChooser.showDialog(null, AppStrings.translate("dialog.selectbkcolor.title"), View.getSwfBackgroundColor()); + if (newColor != null) { + View.setSwfBackgroundColor(newColor); + reload(true); + } + } + + public void replaceButtonActionPerformed(ActionEvent evt) { + TreeItem item = tagTree.getCurrentTreeItem(); + if (item == null) { + return; + } + + if (item instanceof DefineSoundTag) { + File selectedFile = showImportFileChooser("filter.sounds|*.mp3;*.wav|filter.sounds.mp3|*.mp3|filter.sounds.wav|*.wav"); + if (selectedFile != null) { + File selfile = Helper.fixDialogFile(selectedFile); + DefineSoundTag ds = (DefineSoundTag) item; + int soundFormat = SoundFormat.FORMAT_UNCOMPRESSED_LITTLE_ENDIAN; + if (selfile.getName().toLowerCase().endsWith(".mp3")) { + soundFormat = SoundFormat.FORMAT_MP3; + } + + boolean ok = false; + try { + ok = ds.setSound(new FileInputStream(selfile), soundFormat); + ds.getSwf().clearSoundCache(); + } catch (IOException ex) { + //ignore + } + + if (!ok) { + View.showMessageDialog(null, translate("error.sound.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); + } else { + reload(true); + } + } + } + if (item instanceof ImageTag) { + ImageTag it = (ImageTag) item; + if (it.importSupported()) { + File selectedFile = showImportFileChooser("filter.images|*.jpg;*.jpeg;*.gif;*.png;*.bmp"); + if (selectedFile != null) { + File selfile = Helper.fixDialogFile(selectedFile); + byte[] data = Helper.readFile(selfile.getAbsolutePath()); + try { + Tag newTag = new ImageImporter().importImage(it, data); + SWF swf = it.getSwf(); + if (newTag != null) { + refreshTree(swf); + setTagTreeSelectedNode(newTag); + } + swf.clearImageCache(); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Invalid image", ex); + View.showMessageDialog(null, translate("error.image.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); + } + + reload(true); + } + } + } + if (item instanceof ShapeTag) { + ShapeTag st = (ShapeTag) item; + String filter = "filter.images|*.jpg;*.jpeg;*.gif;*.png;*.bmp;*.svg"; + File selectedFile = showImportFileChooser(filter); + if (selectedFile != null) { + File selfile = Helper.fixDialogFile(selectedFile); + byte[] data = null; + String svgText = null; + if (".svg".equals(Path.getExtension(selfile))) { + svgText = Helper.readTextFile(selfile.getAbsolutePath()); + showSvgImportWarning(); + } else { + data = Helper.readFile(selfile.getAbsolutePath()); + } + try { + Tag newTag = svgText != null ? new SvgImporter().importSvg(st, svgText) : new ShapeImporter().importImage(st, data); + SWF swf = st.getSwf(); + if (newTag != null) { + refreshTree(swf); + setTagTreeSelectedNode(newTag); + } + + swf.clearImageCache(); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Invalid image", ex); + View.showMessageDialog(null, translate("error.image.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); + } + reload(true); + } + } + if (item instanceof DefineBinaryDataTag) { + DefineBinaryDataTag bt = (DefineBinaryDataTag) item; + File selectedFile = showImportFileChooser(""); + if (selectedFile != null) { + File selfile = Helper.fixDialogFile(selectedFile); + byte[] data = Helper.readFile(selfile.getAbsolutePath()); + new BinaryDataImporter().importData(bt, data); + refreshTree(bt.getSwf()); + reload(true); + } + } + } + + public void replaceNoFillButtonActionPerformed(ActionEvent evt) { + TreeItem item = tagTree.getCurrentTreeItem(); + if (item == null) { + return; + } + + if (item instanceof ShapeTag) { + ShapeTag st = (ShapeTag) item; + String filter = "filter.images|*.jpg;*.jpeg;*.gif;*.png;*.bmp;*.svg"; + File selectedFile = showImportFileChooser(filter); + if (selectedFile != null) { + File selfile = Helper.fixDialogFile(selectedFile); + byte[] data = null; + String svgText = null; + if (".svg".equals(Path.getExtension(selfile))) { + svgText = Helper.readTextFile(selfile.getAbsolutePath()); + showSvgImportWarning(); + } else { + data = Helper.readFile(selfile.getAbsolutePath()); + } + try { + Tag newTag = svgText != null ? new SvgImporter().importSvg(st, svgText, false) : new ShapeImporter().importImage(st, data, 0, false); + SWF swf = st.getSwf(); + if (newTag != null) { + refreshTree(swf); + setTagTreeSelectedNode(newTag); + } + + swf.clearImageCache(); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Invalid image", ex); + View.showMessageDialog(null, translate("error.image.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); + } + reload(true); + } + } + } + + private void showSvgImportWarning() { + View.showMessageDialog(null, AppStrings.translate("message.warning.svgImportExperimental"), AppStrings.translate("message.warning"), JOptionPane.WARNING_MESSAGE, Configuration.warningSvgImport); + } + + public void replaceAlphaButtonActionPerformed(ActionEvent evt) { + TreeItem item = tagTree.getCurrentTreeItem(); + if (item == null) { + return; + } + + if (item instanceof DefineBitsJPEG3Tag || item instanceof DefineBitsJPEG4Tag) { + ImageTag it = (ImageTag) item; + if (it.importSupported()) { + File selectedFile = showImportFileChooser(""); + if (selectedFile != null) { + File selfile = Helper.fixDialogFile(selectedFile); + byte[] data = Helper.readFile(selfile.getAbsolutePath()); + try { + new ImageImporter().importImageAlpha(it, data); + SWF swf = it.getSwf(); + swf.clearImageCache(); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Invalid alpha channel data", ex); + View.showMessageDialog(null, translate("error.image.alpha.invalid"), translate("error"), JOptionPane.ERROR_MESSAGE); + } + + reload(true); + } + } + } + } + + public void exportJavaSourceActionPerformed(ActionEvent evt) { + if (Main.isWorking()) { + return; + } + + exportJavaSource(); + } + + public void exportSwfXmlActionPerformed(ActionEvent evt) { + if (Main.isWorking()) { + return; + } + + exportSwfXml(); + } + + public void importSwfXmlActionPerformed(ActionEvent evt) { + if (Main.isWorking()) { + return; + } + + importSwfXml(); + } + + public void exportSelectionActionPerformed(ActionEvent evt) { + if (Main.isWorking()) { + return; + } + + export(true); + } + + public File showImportFileChooser(String filter) { + String[] filterArray = filter.length() > 0 ? filter.split("\\|") : new String[0]; + + JFileChooser fc = new JFileChooser(); + fc.setCurrentDirectory(new File(Configuration.lastOpenDir.get())); + boolean first = true; + for (int i = 0; i < filterArray.length; i += 2) { + final String filterName = filterArray[i]; + final String[] extensions = filterArray[i + 1].split(";"); + for (int j = 0; j < extensions.length; j++) { + if (extensions[j].startsWith("*.")) { + extensions[j] = extensions[j].substring(1); + } + } + FileFilter ff = new FileFilter() { + @Override + public boolean accept(File f) { + if (f.isDirectory()) { + return true; + } + String fileName = f.getName().toLowerCase(); + for (String ext : extensions) { + if (fileName.endsWith(ext)) { + return true; + } + } + return false; + } + + @Override + public String getDescription() { + StringBuilder extStr = new StringBuilder(); + boolean first = true; + for (String ext : extensions) { + if (first) { + first = false; + } else { + extStr.append(","); + } + + extStr.append("*").append(ext); + } + + return translate(filterName).replace("%extensions%", extStr); + } + }; + if (first) { + fc.setFileFilter(ff); + } else { + fc.addChoosableFileFilter(ff); + } + first = false; + } + + JFrame f = new JFrame(); + View.setWindowIcon(f); + if (fc.showOpenDialog(f) == JFileChooser.APPROVE_OPTION) { + File result = fc.getSelectedFile(); + Configuration.lastOpenDir.set(Helper.fixDialogFile(result).getParentFile().getAbsolutePath()); + return result; + } + + return null; + } + + private void showDetail(String card) { + CardLayout cl = (CardLayout) (detailPanel.getLayout()); + cl.show(detailPanel, card); + if (card.equals(DETAILCARDEMPTYPANEL)) { + if (detailPanel.isVisible()) { + detailPanel.setVisible(false); + } + } else if (!detailPanel.isVisible()) { + detailPanel.setVisible(true); + } + } + + private void showCard(String card) { + CardLayout cl = (CardLayout) (displayPanel.getLayout()); + cl.show(displayPanel, card); + } + + @Override + public void valueChanged(TreeSelectionEvent e) { + Object source = e.getSource(); + TreeItem treeItem = (TreeItem) e.getPath().getLastPathComponent(); + + if (!(treeItem instanceof SWFList)) { + SWF swf = treeItem.getSwf(); + if (swfs.isEmpty()) { + // show welcome panel after closing swfs + updateUi(); + } else { + if (swf == null) { + swf = swfs.get(0).get(0); + } + + updateUi(swf); + } + } else { + updateUi(); + } + + reload(false); + + if (source == dumpTree) { + Tag t = null; + if (treeItem instanceof DumpInfo) { + DumpInfo di = (DumpInfo) treeItem; + t = di.getTag(); + } + + showPreview(t, dumpPreviewPanel); + } + } + + public void unloadFlashPlayer() { + if (flashPanel != null) { + try { + flashPanel.close(); + } catch (IOException ex) { + // ignore + } + } + if (flashPanel2 != null) { + try { + flashPanel2.close(); + } catch (IOException ex) { + // ignore + } + } + } + + public void clearDebuggerColors() { + if (abcPanel != null) { + abcPanel.decompiledTextArea.removeColorMarkerOnAllLines(DecompiledEditorPane.IP_MARKER); + abcPanel.detailPanel.methodTraitPanel.methodCodePanel.clearDebuggerColors(); + } + if (actionPanel != null) { + actionPanel.decompiledEditor.removeColorMarkerOnAllLines(DecompiledEditorPane.IP_MARKER); + actionPanel.editor.removeColorMarkerOnAllLines(DecompiledEditorPane.IP_MARKER); + } + } + + private void stopFlashPlayer() { + if (flashPanel != null) { + if (!flashPanel.isStopped()) { + flashPanel.stopSWF(); + } + } + if (flashPanel2 != null) { + if (!flashPanel2.isStopped()) { + flashPanel2.stopSWF(); + } + } + } + + public boolean isInternalFlashViewerSelected() { + return mainMenu.isInternalFlashViewerSelected(); + } + + public static final int VIEW_RESOURCES = 0; + + public static final int VIEW_DUMP = 1; + + public static final int VIEW_TIMELINE = 2; + + private int getCurrentView() { + return Configuration.dumpView.get() ? VIEW_DUMP : VIEW_RESOURCES; + } + + public void setTreeModel(int view) { + switch (view) { + case VIEW_DUMP: + if (dumpTree.getModel() == null) { + DumpTreeModel dtm = new DumpTreeModel(swfs); + dumpTree.setModel(dtm); + dumpTree.expandFirstLevelNodes(); + } + break; + case VIEW_RESOURCES: + if (tagTree.getModel() == null) { + TagTreeModel ttm = new TagTreeModel(swfs, Configuration.tagTreeShowEmptyFolders.get()); + tagTree.setModel(ttm); + tagTree.expandFirstLevelNodes(); + } + break; + } + } + + private JPanel createDumpViewCard() { + JPanel r = new JPanel(new BorderLayout()); + r.add(new JPersistentSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(dumpTree), dumpPreviewPanel, Configuration.guiDumpSplitPaneDividerLocationPercent), BorderLayout.CENTER); + return r; + } + + private JPanel createResourcesViewCard() { + JPanel r = new JPanel(new BorderLayout()); + r.add(new JScrollPane(tagTree), BorderLayout.CENTER); + r.add(searchPanel, BorderLayout.SOUTH); + return r; + } + + public boolean showView(int view) { + + CardLayout cl = (CardLayout) (contentPanel.getLayout()); + CardLayout cl2 = (CardLayout) (treePanel.getLayout()); + + setTreeModel(view); + switch (view) { + case VIEW_DUMP: + if (!isWelcomeScreen) { + cl.show(contentPanel, SPLIT_PANE1); + } + cl2.show(treePanel, DUMP_VIEW); + treePanelMode = TreePanelMode.DUMP_TREE; + showDetail(DETAILCARDEMPTYPANEL); + reload(true); + return true; + case VIEW_RESOURCES: + if (!isWelcomeScreen) { + cl.show(contentPanel, SPLIT_PANE1); + } + cl2.show(treePanel, RESOURCES_VIEW); + + treePanelMode = TreePanelMode.TAG_TREE; + + treePanel.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + tagTree.scrollPathToVisible(tagTree.getSelectionPath()); + } + }); + + reload(true); + return true; + case VIEW_TIMELINE: + final SWF swf = getCurrentSwf(); + if (swf != null) { + TreeItem item = tagTree.getCurrentTreeItem(); + if (item instanceof TagScript) { + item = ((TagScript) item).getTag(); + } + if (item instanceof Timelined) { + timelineViewPanel.setTimelined((Timelined) item); + } else if (item instanceof Frame) { + timelineViewPanel.setTimelined(((Frame) item).timeline.timelined); + } else { + timelineViewPanel.setTimelined(swf); + } + cl.show(contentPanel, TIMELINE_PANEL); + return true; + } + return false; + } + return false; + + } + + private void dumpViewReload(boolean forceReload) { + showDetail(DETAILCARDEMPTYPANEL); + + DumpInfo dumpInfo = (DumpInfo) dumpTree.getLastSelectedPathComponent(); + if (dumpInfo == null) { + showCard(CARDEMPTYPANEL); + return; + } + + dumpViewPanel.revalidate(); + dumpViewPanel.setSelectedNode(dumpInfo); + showCard(CARDDUMPVIEW); + } + + public void loadFromBinaryTag(final DefineBinaryDataTag binaryDataTag) { + loadFromBinaryTag(Arrays.asList(binaryDataTag)); + } + + public void loadFromBinaryTag(final List binaryDataTags) { + + Main.loadingDialog.setVisible(true); + new CancellableWorker() { + @Override + protected Void doInBackground() throws Exception { + try { + for (DefineBinaryDataTag binaryDataTag : binaryDataTags) { + try { + InputStream is = new ByteArrayInputStream(binaryDataTag.binaryData.getRangeData()); + SWF bswf = new SWF(is, null, "(SWF Data)", new ProgressListener() { + @Override + public void progress(int p) { + Main.loadingDialog.setPercent(p); + } + }, Configuration.parallelSpeedUp.get()); + binaryDataTag.innerSwf = bswf; + bswf.binaryData = binaryDataTag; + } catch (IOException ex) { + //ignore + } + } + } catch (InterruptedException ex) { + //ignore + } + + return null; + } + + @Override + protected void onStart() { + Main.startWork(AppStrings.translate("work.reading.swf") + "...", this); + } + + @Override + protected void done() { + View.execInEventDispatch(() -> { + Main.loadingDialog.setVisible(false); + Main.stopWork(); + }); + } + }.execute(); + } + + private void closeTag() { + previewPanel.closeTag(); + } + + public void showPreview(TreeItem treeItem, PreviewPanel previewPanel) { + previewPanel.clear(); + if (treeItem == null) { + previewPanel.showEmpty(); + return; + } + boolean internalViewer = isInternalFlashViewerSelected(); + if (treeItem instanceof SWF) { + SWF swf = (SWF) treeItem; + if (internalViewer) { + previewPanel.showImagePanel(swf, swf, -1); + } else { + previewPanel.setParametersPanelVisible(false); + if (flashPanel != null) { //same for flashPanel2 + previewPanel.showFlashViewerPanel(); + previewPanel.showSwf(swf); + } + } + } else if (treeItem instanceof MetadataTag) { + MetadataTag metadataTag = (MetadataTag) treeItem; + previewPanel.showMetaDataPanel(metadataTag); + } else if (treeItem instanceof DefineBinaryDataTag) { + DefineBinaryDataTag binaryTag = (DefineBinaryDataTag) treeItem; + previewPanel.showBinaryPanel(binaryTag); + } else if (treeItem instanceof ImageTag) { + ImageTag imageTag = (ImageTag) treeItem; + previewPanel.setImageReplaceButtonVisible(!((Tag) imageTag).isReadOnly() && imageTag.importSupported(), imageTag instanceof DefineBitsJPEG3Tag || imageTag instanceof DefineBitsJPEG4Tag); + previewPanel.showImagePanel(imageTag.getImageCached()); + + } else if ((treeItem instanceof DrawableTag) && (!(treeItem instanceof TextTag)) && (!(treeItem instanceof FontTag)) && internalViewer) { + final Tag tag = (Tag) treeItem; + DrawableTag d = (DrawableTag) tag; + Timelined timelined; + if (treeItem instanceof Timelined && !(treeItem instanceof ButtonTag)) { + timelined = (Timelined) tag; + } else { + timelined = makeTimelined(tag); + } + + previewPanel.setParametersPanelVisible(false); + previewPanel.showImagePanel(timelined, tag.getSwf(), -1); + } else if (treeItem instanceof Frame && internalViewer) { + Frame fn = (Frame) treeItem; + SWF swf = fn.getSwf(); + previewPanel.showImagePanel(fn.timeline.timelined, swf, fn.frame); + } else if ((treeItem instanceof SoundTag)) { //&& isInternalFlashViewerSelected() && (Arrays.asList("mp3", "wav").contains(((SoundTag) tagObj).getExportFormat())))) { + previewPanel.showImagePanel(new SerializableImage(View.loadImage("sound32"))); + previewPanel.setImageReplaceButtonVisible(((Tag) treeItem).isReadOnly() && (treeItem instanceof DefineSoundTag), false); + try { + SoundTagPlayer soundThread = new SoundTagPlayer((SoundTag) treeItem, Configuration.loopMedia.get() ? Integer.MAX_VALUE : 1, true); + previewPanel.setMedia(soundThread); + } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) { + logger.log(Level.SEVERE, null, ex); + } + + } else if ((treeItem instanceof FontTag) && internalViewer) { + previewPanel.showFontPanel((FontTag) treeItem); + } else if ((treeItem instanceof TextTag) && internalViewer) { + previewPanel.showTextPanel((TextTag) treeItem); + } else if ((treeItem instanceof Frame) || (treeItem instanceof CharacterTag) || (treeItem instanceof FontTag) || (treeItem instanceof SoundStreamHeadTypeTag)) { + previewPanel.createAndShowTempSwf(treeItem); + + if (treeItem instanceof TextTag) { + previewPanel.showTextPanel((TextTag) treeItem); + } else if (treeItem instanceof FontTag) { + previewPanel.showFontPanel((FontTag) treeItem); + } else { + previewPanel.setParametersPanelVisible(false); + } + } else { + previewPanel.showEmpty(); + } + } + + public void reload(boolean forceReload) { + tagTree.scrollPathToVisible(tagTree.getSelectionPath()); + if (Configuration.dumpView.get()) { + dumpViewReload(forceReload); + return; + } + + TreeItem treeItem = null; + TreePath treePath = tagTree.getSelectionPath(); + if (treePath != null && tagTree.getModel().treePathExists(treePath)) { + treeItem = (TreeItem) treePath.getLastPathComponent(); + } + + // save last selected node to config + if (treeItem != null) { + SWF swf = treeItem.getSwf(); + if (swf != null) { + swf = swf.getRootSwf(); + } + + if (swf != null) { + SwfSpecificConfiguration swfConf = Configuration.getOrCreateSwfSpecificConfiguration(swf.getShortFileName()); + swfConf.lastSelectedPath = tagTree.getSelectionPathString(); + } + } + + if (!forceReload && (treeItem == oldItem)) { + return; + } + + if (oldItem != treeItem) { + closeTag(); + } + + oldItem = treeItem; + + // show the preview of the tag when the user clicks to the tagname inside the scripts node, too + // this is a little bit inconsistent, beacuse the frames (FrameScript) are not shown + boolean preferScript = false; + if (treeItem instanceof TagScript) { + treeItem = ((TagScript) treeItem).getTag(); + preferScript = true; + } + + folderPreviewPanel.clear(); + previewPanel.clear(); + stopFlashPlayer(); + + previewPanel.setImageReplaceButtonVisible(false, false); + + boolean internalViewer = isInternalFlashViewerSelected(); + + if (treeItem instanceof ScriptPack) { + final ScriptPack scriptLeaf = (ScriptPack) treeItem; + if (setSourceWorker != null) { + setSourceWorker.cancel(true); + setSourceWorker = null; + } + if (!Main.isInited() || !Main.isWorking() || Main.isDebugging()) { + ABCPanel abcPanel = getABCPanel(); + CancellableWorker worker = new CancellableWorker() { + @Override + protected Void doInBackground() throws Exception { + abcPanel.detailPanel.methodTraitPanel.methodCodePanel.clear(); + abcPanel.setAbc(scriptLeaf.abc); + abcPanel.decompiledTextArea.setScript(scriptLeaf, true); + abcPanel.decompiledTextArea.setNoTrait(); + return null; + } + + @Override + protected void onStart() { + Main.startWork(translate("work.decompiling") + "...", this); + } + + @Override + protected void done() { + View.execInEventDispatch(() -> { + setSourceWorker = null; + try { + get(); + } catch (CancellationException ex) { + abcPanel.decompiledTextArea.setText("// " + AppStrings.translate("work.canceled")); + } catch (Exception ex) { + logger.log(Level.SEVERE, "Error", ex); + getABCPanel().decompiledTextArea.setText("// " + AppStrings.translate("decompilationError") + ": " + ex); + } + + Main.stopWork(); + }); + } + }; + + worker.execute(); + setSourceWorker = worker; + } + + showDetail(DETAILCARDAS3NAVIGATOR); + showCard(CARDACTIONSCRIPT3PANEL); + return; + } + + if (treeItem instanceof Tag) { + Tag tag = (Tag) treeItem; + TagInfo tagInfo = new TagInfo(); + tag.getTagInfo(tagInfo); + if (!tagInfo.isEmpty()) { + tagInfoPanel.setTagInfos(tagInfo); + showDetail(DETAILCARDTAGINFO); + } else { + showDetail(DETAILCARDEMPTYPANEL); + } + } else { + showDetail(DETAILCARDEMPTYPANEL); + } + + if (treeItem instanceof HeaderItem) { + headerPanel.load(((HeaderItem) treeItem).getSwf()); + showCard(CARDHEADER); + } else if (treeItem instanceof FolderItem) { + showFolderPreview((FolderItem) treeItem); + } else if (treeItem instanceof SWF) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if (treeItem instanceof MetadataTag) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if (treeItem instanceof DefineBinaryDataTag) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if (treeItem instanceof ASMSource && (!(treeItem instanceof DrawableTag) || preferScript)) { + getActionPanel().setSource((ASMSource) treeItem, !forceReload); + showCard(CARDACTIONSCRIPTPANEL); + } else if (treeItem instanceof ImageTag) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if ((treeItem instanceof DrawableTag) && (!(treeItem instanceof TextTag)) && (!(treeItem instanceof FontTag)) && internalViewer) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if ((treeItem instanceof FontTag) && internalViewer) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if ((treeItem instanceof TextTag) && internalViewer) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if (treeItem instanceof Frame && internalViewer) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if ((treeItem instanceof SoundTag)) { //&& isInternalFlashViewerSelected() && (Arrays.asList("mp3", "wav").contains(((SoundTag) tagObj).getExportFormat())))) { + showPreview(treeItem, previewPanel); + showCard(CARDPREVIEWPANEL); + } else if ((treeItem instanceof Frame) || (treeItem instanceof CharacterTag) || (treeItem instanceof FontTag) || (treeItem instanceof SoundStreamHeadTypeTag)) { + showPreview(treeItem, previewPanel); + + showCard(CARDPREVIEWPANEL); + } else if (treeItem instanceof Tag) { + showGenericTag((Tag) treeItem); + } else { + showCard(CARDEMPTYPANEL); + } + } + + public void repaintTree() { + tagTree.repaint(); + reload(true); + } + + public void showGenericTag(Tag tag) { + previewPanel.showGenericTagPanel(tag); + showCard(CARDPREVIEWPANEL); + } + + public void showTextTagWithNewValue(TextTag textTag, TextTag newTextTag) { + + previewPanel.showTextComparePanel(textTag, newTextTag); + } + + private void showFolderPreview(FolderItem item) { + List folderPreviewItems = new ArrayList<>(); + String folderName = item.getName(); + SWF swf = item.swf; + switch (folderName) { + case TagTreeModel.FOLDER_SHAPES: + for (Tag tag : swf.getTags()) { + if (tag instanceof ShapeTag) { + folderPreviewItems.add(tag); + } + } + break; + case TagTreeModel.FOLDER_MORPHSHAPES: + for (Tag tag : swf.getTags()) { + if (tag instanceof MorphShapeTag) { + folderPreviewItems.add(tag); + } + } + break; + case TagTreeModel.FOLDER_SPRITES: + for (Tag tag : swf.getTags()) { + if (tag instanceof DefineSpriteTag) { + folderPreviewItems.add(tag); + } + } + break; + case TagTreeModel.FOLDER_BUTTONS: + for (Tag tag : swf.getTags()) { + if (tag instanceof ButtonTag) { + folderPreviewItems.add(tag); + } + } + break; + case TagTreeModel.FOLDER_FONTS: + for (Tag tag : swf.getTags()) { + if (tag instanceof FontTag) { + folderPreviewItems.add(tag); + } + } + break; + case TagTreeModel.FOLDER_FRAMES: + for (Frame frame : swf.getTimeline().getFrames()) { + folderPreviewItems.add(frame); + } + break; + case TagTreeModel.FOLDER_IMAGES: + for (Tag tag : swf.getTags()) { + if (tag instanceof ImageTag) { + folderPreviewItems.add(tag); + } + } + break; + case TagTreeModel.FOLDER_TEXTS: + for (Tag tag : swf.getTags()) { + if (tag instanceof TextTag) { + folderPreviewItems.add(tag); + } + } + break; + } + + folderPreviewPanel.setItems(folderPreviewItems); + showCard(CARDFOLDERPREVIEWPANEL); + } + + private boolean isFreeing; + + @Override + public boolean isFreeing() { + return isFreeing; + } + + @Override + public void free() { + isFreeing = true; + } + + public void setErrorState(ErrorState errorState) { + statusPanel.setErrorState(errorState); + } + + public static Timelined makeTimelined(final Tag tag) { + return makeTimelined(tag, -1); + } + + public static Timelined makeTimelined(final Tag tag, final int fontFrameNum) { + + return new Timelined() { + private Timeline tim; + + @Override + public Timeline getTimeline() { + if (tim == null) { + Timeline timeline = new Timeline(tag.getSwf(), this, ((CharacterTag) tag).getCharacterId(), getRect()); + initTimeline(timeline); + tim = timeline; + } + + return tim; + } + + @Override + public void resetTimeline() { + if (tim != null) { + tim.reset(tag.getSwf(), this, ((CharacterTag) tag).getCharacterId(), getRect()); + initTimeline(tim); + } + } + + private void initTimeline(Timeline timeline) { + if (tag instanceof MorphShapeTag) { + timeline.frameRate = MORPH_SHAPE_ANIMATION_FRAME_RATE; + int framesCnt = (int) (timeline.frameRate * MORPH_SHAPE_ANIMATION_LENGTH); + for (int i = 0; i < framesCnt; i++) { + Frame f = new Frame(timeline, i); + DepthState ds = new DepthState(tag.getSwf(), f); + ds.characterId = ((CharacterTag) tag).getCharacterId(); + ds.matrix = new MATRIX(); + ds.ratio = i * 65535 / framesCnt; + f.layers.put(1, ds); + f.layersChanged = true; + timeline.addFrame(f); + } + } else if (tag instanceof FontTag) { + int pageCount = PreviewPanel.getFontPageCount((FontTag) tag); + int frame = fontFrameNum; + if (frame < 0 || frame >= pageCount) { + frame = 0; + } + + Frame f = new Frame(timeline, 0); + DepthState ds = new DepthState(tag.getSwf(), f); + ds.characterId = ((CharacterTag) tag).getCharacterId(); + ds.matrix = new MATRIX(); + f.layers.put(1, ds); + f.layersChanged = true; + timeline.addFrame(f); + timeline.fontFrameNum = frame; + } else { + Frame f = new Frame(timeline, 0); + DepthState ds = new DepthState(tag.getSwf(), f); + ds.characterId = ((CharacterTag) tag).getCharacterId(); + ds.matrix = new MATRIX(); + f.layers.put(1, ds); + timeline.addFrame(f); + } + timeline.displayRect = getRect(); + } + + @Override + public RECT getRect() { + return getRect(new HashSet<>()); + } + + @Override + public RECT getRect(Set added) { + BoundedTag bt = (BoundedTag) tag; + if (!added.contains(bt)) { + return bt.getRect(added); + } + return new RECT(Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE); + } + + @Override + public int hashCode() { + return tag.hashCode(); + } + + @Override + public void setModified(boolean value) { + } + + @Override + public ReadOnlyTagList getTags() { + return ReadOnlyTagList.EMPTY; + } + + @Override + public void removeTag(int index) { + } + + @Override + public void removeTag(Tag tag) { + } + + @Override + public void addTag(Tag tag) { + } + + @Override + public void addTag(int index, Tag tag) { + } + + @Override + public void replaceTag(int index, Tag newTag) { + } + }; + } + + private void disposeInner(Container container) { + for (Component c : container.getComponents()) { + if (c instanceof Container) { + Container c2 = (Container) c; + disposeInner(c2); + } + } + + container.removeAll(); + container.setLayout(null); + if (container instanceof TagEditorPanel) { + Helper.emptyObject(container); + } + } + + public void dispose() { + setDropTarget(null); + disposeInner(this); + Helper.emptyObject(this); + } +}